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/SaveAndRestore.h"
28 #include "llvm/Support/raw_ostream.h"
31 static std::string getTypeString(Type *T) {
33 raw_string_ostream Tmp(Result);
38 /// Run: module ::= toplevelentity*
39 bool LLParser::Run() {
43 return ParseTopLevelEntities() ||
44 ValidateEndOfModule();
47 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
49 bool LLParser::ValidateEndOfModule() {
50 // Handle any instruction metadata forward references.
51 if (!ForwardRefInstMetadata.empty()) {
52 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
53 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
55 Instruction *Inst = I->first;
56 const std::vector<MDRef> &MDList = I->second;
58 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
59 unsigned SlotNo = MDList[i].MDSlot;
61 if (SlotNo >= NumberedMetadata.size() ||
62 NumberedMetadata[SlotNo] == nullptr)
63 return Error(MDList[i].Loc, "use of undefined metadata '!" +
65 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
68 ForwardRefInstMetadata.clear();
71 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
72 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
74 // Handle any function attribute group forward references.
75 for (std::map<Value*, std::vector<unsigned> >::iterator
76 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
79 std::vector<unsigned> &Vec = I->second;
82 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
84 B.merge(NumberedAttrBuilders[*VI]);
86 if (Function *Fn = dyn_cast<Function>(V)) {
87 AttributeSet AS = Fn->getAttributes();
88 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
89 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
90 AS.getFnAttributes());
94 // If the alignment was parsed as an attribute, move to the alignment
96 if (FnAttrs.hasAlignmentAttr()) {
97 Fn->setAlignment(FnAttrs.getAlignment());
98 FnAttrs.removeAttribute(Attribute::Alignment);
101 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
102 AttributeSet::get(Context,
103 AttributeSet::FunctionIndex,
105 Fn->setAttributes(AS);
106 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
107 AttributeSet AS = CI->getAttributes();
108 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
109 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
110 AS.getFnAttributes());
112 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
113 AttributeSet::get(Context,
114 AttributeSet::FunctionIndex,
116 CI->setAttributes(AS);
117 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
118 AttributeSet AS = II->getAttributes();
119 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
120 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
121 AS.getFnAttributes());
123 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
124 AttributeSet::get(Context,
125 AttributeSet::FunctionIndex,
127 II->setAttributes(AS);
129 llvm_unreachable("invalid object with forward attribute group reference");
133 // If there are entries in ForwardRefBlockAddresses at this point, the
134 // function was never defined.
135 if (!ForwardRefBlockAddresses.empty())
136 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
137 "expected function name in blockaddress");
139 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
140 if (NumberedTypes[i].second.isValid())
141 return Error(NumberedTypes[i].second,
142 "use of undefined type '%" + Twine(i) + "'");
144 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
145 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
146 if (I->second.second.isValid())
147 return Error(I->second.second,
148 "use of undefined type named '" + I->getKey() + "'");
150 if (!ForwardRefComdats.empty())
151 return Error(ForwardRefComdats.begin()->second,
152 "use of undefined comdat '$" +
153 ForwardRefComdats.begin()->first + "'");
155 if (!ForwardRefVals.empty())
156 return Error(ForwardRefVals.begin()->second.second,
157 "use of undefined value '@" + ForwardRefVals.begin()->first +
160 if (!ForwardRefValIDs.empty())
161 return Error(ForwardRefValIDs.begin()->second.second,
162 "use of undefined value '@" +
163 Twine(ForwardRefValIDs.begin()->first) + "'");
165 if (!ForwardRefMDNodes.empty())
166 return Error(ForwardRefMDNodes.begin()->second.second,
167 "use of undefined metadata '!" +
168 Twine(ForwardRefMDNodes.begin()->first) + "'");
171 // Look for intrinsic functions and CallInst that need to be upgraded
172 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
173 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
175 UpgradeDebugInfo(*M);
180 //===----------------------------------------------------------------------===//
181 // Top-Level Entities
182 //===----------------------------------------------------------------------===//
184 bool LLParser::ParseTopLevelEntities() {
186 switch (Lex.getKind()) {
187 default: return TokError("expected top-level entity");
188 case lltok::Eof: return false;
189 case lltok::kw_declare: if (ParseDeclare()) return true; break;
190 case lltok::kw_define: if (ParseDefine()) return true; break;
191 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
192 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
193 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
194 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
195 case lltok::LocalVar: if (ParseNamedType()) return true; break;
196 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
197 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
198 case lltok::ComdatVar: if (parseComdat()) return true; break;
199 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
200 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
202 // The Global variable production with no name can have many different
203 // optional leading prefixes, the production is:
204 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
205 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
206 // ('constant'|'global') ...
207 case lltok::kw_private: // OptionalLinkage
208 case lltok::kw_internal: // OptionalLinkage
209 case lltok::kw_weak: // OptionalLinkage
210 case lltok::kw_weak_odr: // OptionalLinkage
211 case lltok::kw_linkonce: // OptionalLinkage
212 case lltok::kw_linkonce_odr: // OptionalLinkage
213 case lltok::kw_appending: // OptionalLinkage
214 case lltok::kw_common: // OptionalLinkage
215 case lltok::kw_extern_weak: // OptionalLinkage
216 case lltok::kw_external: // OptionalLinkage
217 case lltok::kw_default: // OptionalVisibility
218 case lltok::kw_hidden: // OptionalVisibility
219 case lltok::kw_protected: // OptionalVisibility
220 case lltok::kw_dllimport: // OptionalDLLStorageClass
221 case lltok::kw_dllexport: // OptionalDLLStorageClass
222 case lltok::kw_thread_local: // OptionalThreadLocal
223 case lltok::kw_addrspace: // OptionalAddrSpace
224 case lltok::kw_constant: // GlobalType
225 case lltok::kw_global: { // GlobalType
226 unsigned Linkage, Visibility, DLLStorageClass;
228 GlobalVariable::ThreadLocalMode TLM;
230 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
231 ParseOptionalVisibility(Visibility) ||
232 ParseOptionalDLLStorageClass(DLLStorageClass) ||
233 ParseOptionalThreadLocal(TLM) ||
234 parseOptionalUnnamedAddr(UnnamedAddr) ||
235 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
236 DLLStorageClass, TLM, UnnamedAddr))
241 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
242 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
243 case lltok::kw_uselistorder_bb:
244 if (ParseUseListOrderBB()) return true; break;
251 /// ::= 'module' 'asm' STRINGCONSTANT
252 bool LLParser::ParseModuleAsm() {
253 assert(Lex.getKind() == lltok::kw_module);
257 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
258 ParseStringConstant(AsmStr)) return true;
260 M->appendModuleInlineAsm(AsmStr);
265 /// ::= 'target' 'triple' '=' STRINGCONSTANT
266 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
267 bool LLParser::ParseTargetDefinition() {
268 assert(Lex.getKind() == lltok::kw_target);
271 default: return TokError("unknown target property");
272 case lltok::kw_triple:
274 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
275 ParseStringConstant(Str))
277 M->setTargetTriple(Str);
279 case lltok::kw_datalayout:
281 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
282 ParseStringConstant(Str))
284 M->setDataLayout(Str);
290 /// ::= 'deplibs' '=' '[' ']'
291 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
292 /// FIXME: Remove in 4.0. Currently parse, but ignore.
293 bool LLParser::ParseDepLibs() {
294 assert(Lex.getKind() == lltok::kw_deplibs);
296 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
297 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
300 if (EatIfPresent(lltok::rsquare))
305 if (ParseStringConstant(Str)) return true;
306 } while (EatIfPresent(lltok::comma));
308 return ParseToken(lltok::rsquare, "expected ']' at end of list");
311 /// ParseUnnamedType:
312 /// ::= LocalVarID '=' 'type' type
313 bool LLParser::ParseUnnamedType() {
314 LocTy TypeLoc = Lex.getLoc();
315 unsigned TypeID = Lex.getUIntVal();
316 Lex.Lex(); // eat LocalVarID;
318 if (ParseToken(lltok::equal, "expected '=' after name") ||
319 ParseToken(lltok::kw_type, "expected 'type' after '='"))
322 if (TypeID >= NumberedTypes.size())
323 NumberedTypes.resize(TypeID+1);
325 Type *Result = nullptr;
326 if (ParseStructDefinition(TypeLoc, "",
327 NumberedTypes[TypeID], Result)) return true;
329 if (!isa<StructType>(Result)) {
330 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
332 return Error(TypeLoc, "non-struct types may not be recursive");
333 Entry.first = Result;
334 Entry.second = SMLoc();
342 /// ::= LocalVar '=' 'type' type
343 bool LLParser::ParseNamedType() {
344 std::string Name = Lex.getStrVal();
345 LocTy NameLoc = Lex.getLoc();
346 Lex.Lex(); // eat LocalVar.
348 if (ParseToken(lltok::equal, "expected '=' after name") ||
349 ParseToken(lltok::kw_type, "expected 'type' after name"))
352 Type *Result = nullptr;
353 if (ParseStructDefinition(NameLoc, Name,
354 NamedTypes[Name], Result)) return true;
356 if (!isa<StructType>(Result)) {
357 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
359 return Error(NameLoc, "non-struct types may not be recursive");
360 Entry.first = Result;
361 Entry.second = SMLoc();
369 /// ::= 'declare' FunctionHeader
370 bool LLParser::ParseDeclare() {
371 assert(Lex.getKind() == lltok::kw_declare);
375 return ParseFunctionHeader(F, false);
379 /// ::= 'define' FunctionHeader '{' ...
380 bool LLParser::ParseDefine() {
381 assert(Lex.getKind() == lltok::kw_define);
385 return ParseFunctionHeader(F, true) ||
386 ParseFunctionBody(*F);
392 bool LLParser::ParseGlobalType(bool &IsConstant) {
393 if (Lex.getKind() == lltok::kw_constant)
395 else if (Lex.getKind() == lltok::kw_global)
399 return TokError("expected 'global' or 'constant'");
405 /// ParseUnnamedGlobal:
406 /// OptionalVisibility ALIAS ...
407 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
408 /// ... -> global variable
409 /// GlobalID '=' OptionalVisibility ALIAS ...
410 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
411 /// ... -> global variable
412 bool LLParser::ParseUnnamedGlobal() {
413 unsigned VarID = NumberedVals.size();
415 LocTy NameLoc = Lex.getLoc();
417 // Handle the GlobalID form.
418 if (Lex.getKind() == lltok::GlobalID) {
419 if (Lex.getUIntVal() != VarID)
420 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
422 Lex.Lex(); // eat GlobalID;
424 if (ParseToken(lltok::equal, "expected '=' after name"))
429 unsigned Linkage, Visibility, DLLStorageClass;
430 GlobalVariable::ThreadLocalMode TLM;
432 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
433 ParseOptionalVisibility(Visibility) ||
434 ParseOptionalDLLStorageClass(DLLStorageClass) ||
435 ParseOptionalThreadLocal(TLM) ||
436 parseOptionalUnnamedAddr(UnnamedAddr))
439 if (Lex.getKind() != lltok::kw_alias)
440 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
441 DLLStorageClass, TLM, UnnamedAddr);
442 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
446 /// ParseNamedGlobal:
447 /// GlobalVar '=' OptionalVisibility ALIAS ...
448 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
449 /// ... -> global variable
450 bool LLParser::ParseNamedGlobal() {
451 assert(Lex.getKind() == lltok::GlobalVar);
452 LocTy NameLoc = Lex.getLoc();
453 std::string Name = Lex.getStrVal();
457 unsigned Linkage, Visibility, DLLStorageClass;
458 GlobalVariable::ThreadLocalMode TLM;
460 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
461 ParseOptionalLinkage(Linkage, HasLinkage) ||
462 ParseOptionalVisibility(Visibility) ||
463 ParseOptionalDLLStorageClass(DLLStorageClass) ||
464 ParseOptionalThreadLocal(TLM) ||
465 parseOptionalUnnamedAddr(UnnamedAddr))
468 if (Lex.getKind() != lltok::kw_alias)
469 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
470 DLLStorageClass, TLM, UnnamedAddr);
472 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
476 bool LLParser::parseComdat() {
477 assert(Lex.getKind() == lltok::ComdatVar);
478 std::string Name = Lex.getStrVal();
479 LocTy NameLoc = Lex.getLoc();
482 if (ParseToken(lltok::equal, "expected '=' here"))
485 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
486 return TokError("expected comdat type");
488 Comdat::SelectionKind SK;
489 switch (Lex.getKind()) {
491 return TokError("unknown selection kind");
495 case lltok::kw_exactmatch:
496 SK = Comdat::ExactMatch;
498 case lltok::kw_largest:
499 SK = Comdat::Largest;
501 case lltok::kw_noduplicates:
502 SK = Comdat::NoDuplicates;
504 case lltok::kw_samesize:
505 SK = Comdat::SameSize;
510 // See if the comdat was forward referenced, if so, use the comdat.
511 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
512 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
513 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
514 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
517 if (I != ComdatSymTab.end())
520 C = M->getOrInsertComdat(Name);
521 C->setSelectionKind(SK);
527 // ::= '!' STRINGCONSTANT
528 bool LLParser::ParseMDString(MDString *&Result) {
530 if (ParseStringConstant(Str)) return true;
531 llvm::UpgradeMDStringConstant(Str);
532 Result = MDString::get(Context, Str);
537 // ::= '!' MDNodeNumber
539 /// This version of ParseMDNodeID returns the slot number and null in the case
540 /// of a forward reference.
541 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
542 // !{ ..., !42, ... }
543 if (ParseUInt32(SlotNo)) return true;
545 // Check existing MDNode.
546 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
547 Result = NumberedMetadata[SlotNo];
553 bool LLParser::ParseMDNodeID(MDNode *&Result) {
554 // !{ ..., !42, ... }
556 if (ParseMDNodeID(Result, MID)) return true;
558 // If not a forward reference, just return it now.
559 if (Result) return false;
561 // Otherwise, create MDNode forward reference.
562 MDNode *FwdNode = MDNode::getTemporary(Context, None);
563 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
565 if (NumberedMetadata.size() <= MID)
566 NumberedMetadata.resize(MID+1);
567 NumberedMetadata[MID] = FwdNode;
572 /// ParseNamedMetadata:
573 /// !foo = !{ !1, !2 }
574 bool LLParser::ParseNamedMetadata() {
575 assert(Lex.getKind() == lltok::MetadataVar);
576 std::string Name = Lex.getStrVal();
579 if (ParseToken(lltok::equal, "expected '=' here") ||
580 ParseToken(lltok::exclaim, "Expected '!' here") ||
581 ParseToken(lltok::lbrace, "Expected '{' here"))
584 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
585 if (Lex.getKind() != lltok::rbrace)
587 if (ParseToken(lltok::exclaim, "Expected '!' here"))
591 if (ParseMDNodeID(N)) return true;
593 } while (EatIfPresent(lltok::comma));
595 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
601 /// ParseStandaloneMetadata:
603 bool LLParser::ParseStandaloneMetadata() {
604 assert(Lex.getKind() == lltok::exclaim);
606 unsigned MetadataID = 0;
610 SmallVector<Value *, 16> Elts;
611 if (ParseUInt32(MetadataID) ||
612 ParseToken(lltok::equal, "expected '=' here") ||
613 ParseType(Ty, TyLoc) ||
614 ParseToken(lltok::exclaim, "Expected '!' here") ||
615 ParseToken(lltok::lbrace, "Expected '{' here") ||
616 ParseMDNodeVector(Elts, nullptr) ||
617 ParseToken(lltok::rbrace, "expected end of metadata node"))
620 MDNode *Init = MDNode::get(Context, Elts);
622 // See if this was forward referenced, if so, handle it.
623 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
624 FI = ForwardRefMDNodes.find(MetadataID);
625 if (FI != ForwardRefMDNodes.end()) {
626 MDNode *Temp = FI->second.first;
627 Temp->replaceAllUsesWith(Init);
628 MDNode::deleteTemporary(Temp);
629 ForwardRefMDNodes.erase(FI);
631 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
633 if (MetadataID >= NumberedMetadata.size())
634 NumberedMetadata.resize(MetadataID+1);
636 if (NumberedMetadata[MetadataID] != nullptr)
637 return TokError("Metadata id is already used");
638 NumberedMetadata[MetadataID] = Init;
644 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
645 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
646 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
650 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
651 /// OptionalDLLStorageClass OptionalThreadLocal
652 /// OptionalUnNammedAddr 'alias' Aliasee
657 /// Everything through OptionalUnNammedAddr has already been parsed.
659 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
660 unsigned Visibility, unsigned DLLStorageClass,
661 GlobalVariable::ThreadLocalMode TLM,
663 assert(Lex.getKind() == lltok::kw_alias);
666 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
668 if(!GlobalAlias::isValidLinkage(Linkage))
669 return Error(NameLoc, "invalid linkage type for alias");
671 if (!isValidVisibilityForLinkage(Visibility, L))
672 return Error(NameLoc,
673 "symbol with local linkage must have default visibility");
676 LocTy AliaseeLoc = Lex.getLoc();
677 if (Lex.getKind() != lltok::kw_bitcast &&
678 Lex.getKind() != lltok::kw_getelementptr &&
679 Lex.getKind() != lltok::kw_addrspacecast &&
680 Lex.getKind() != lltok::kw_inttoptr) {
681 if (ParseGlobalTypeAndValue(Aliasee))
684 // The bitcast dest type is not present, it is implied by the dest type.
688 if (ID.Kind != ValID::t_Constant)
689 return Error(AliaseeLoc, "invalid aliasee");
690 Aliasee = ID.ConstantVal;
693 Type *AliaseeType = Aliasee->getType();
694 auto *PTy = dyn_cast<PointerType>(AliaseeType);
696 return Error(AliaseeLoc, "An alias must have pointer type");
697 Type *Ty = PTy->getElementType();
698 unsigned AddrSpace = PTy->getAddressSpace();
700 // Okay, create the alias but do not insert it into the module yet.
701 std::unique_ptr<GlobalAlias> GA(
702 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
703 Name, Aliasee, /*Parent*/ nullptr));
704 GA->setThreadLocalMode(TLM);
705 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
706 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
707 GA->setUnnamedAddr(UnnamedAddr);
709 // See if this value already exists in the symbol table. If so, it is either
710 // a redefinition or a definition of a forward reference.
711 if (GlobalValue *Val = M->getNamedValue(Name)) {
712 // See if this was a redefinition. If so, there is no entry in
714 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
715 I = ForwardRefVals.find(Name);
716 if (I == ForwardRefVals.end())
717 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
719 // Otherwise, this was a definition of forward ref. Verify that types
721 if (Val->getType() != GA->getType())
722 return Error(NameLoc,
723 "forward reference and definition of alias have different types");
725 // If they agree, just RAUW the old value with the alias and remove the
727 Val->replaceAllUsesWith(GA.get());
728 Val->eraseFromParent();
729 ForwardRefVals.erase(I);
732 // Insert into the module, we know its name won't collide now.
733 M->getAliasList().push_back(GA.get());
734 assert(GA->getName() == Name && "Should not be a name conflict!");
736 // The module owns this now
743 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
744 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
745 /// OptionalExternallyInitialized GlobalType Type Const
746 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
747 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
748 /// OptionalExternallyInitialized GlobalType Type Const
750 /// Everything up to and including OptionalUnNammedAddr has been parsed
753 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
754 unsigned Linkage, bool HasLinkage,
755 unsigned Visibility, unsigned DLLStorageClass,
756 GlobalVariable::ThreadLocalMode TLM,
758 if (!isValidVisibilityForLinkage(Visibility, Linkage))
759 return Error(NameLoc,
760 "symbol with local linkage must have default visibility");
763 bool IsConstant, IsExternallyInitialized;
764 LocTy IsExternallyInitializedLoc;
768 if (ParseOptionalAddrSpace(AddrSpace) ||
769 ParseOptionalToken(lltok::kw_externally_initialized,
770 IsExternallyInitialized,
771 &IsExternallyInitializedLoc) ||
772 ParseGlobalType(IsConstant) ||
773 ParseType(Ty, TyLoc))
776 // If the linkage is specified and is external, then no initializer is
778 Constant *Init = nullptr;
779 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
780 Linkage != GlobalValue::ExternalLinkage)) {
781 if (ParseGlobalValue(Ty, Init))
785 if (Ty->isFunctionTy() || Ty->isLabelTy())
786 return Error(TyLoc, "invalid type for global variable");
788 GlobalVariable *GV = nullptr;
790 // See if the global was forward referenced, if so, use the global.
792 if (GlobalValue *GVal = M->getNamedValue(Name)) {
793 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
794 return Error(NameLoc, "redefinition of global '@" + Name + "'");
795 GV = cast<GlobalVariable>(GVal);
798 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
799 I = ForwardRefValIDs.find(NumberedVals.size());
800 if (I != ForwardRefValIDs.end()) {
801 GV = cast<GlobalVariable>(I->second.first);
802 ForwardRefValIDs.erase(I);
807 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
808 Name, nullptr, GlobalVariable::NotThreadLocal,
811 if (GV->getType()->getElementType() != Ty)
813 "forward reference and definition of global have different types");
815 // Move the forward-reference to the correct spot in the module.
816 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
820 NumberedVals.push_back(GV);
822 // Set the parsed properties on the global.
824 GV->setInitializer(Init);
825 GV->setConstant(IsConstant);
826 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
827 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
828 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
829 GV->setExternallyInitialized(IsExternallyInitialized);
830 GV->setThreadLocalMode(TLM);
831 GV->setUnnamedAddr(UnnamedAddr);
833 // Parse attributes on the global.
834 while (Lex.getKind() == lltok::comma) {
837 if (Lex.getKind() == lltok::kw_section) {
839 GV->setSection(Lex.getStrVal());
840 if (ParseToken(lltok::StringConstant, "expected global section string"))
842 } else if (Lex.getKind() == lltok::kw_align) {
844 if (ParseOptionalAlignment(Alignment)) return true;
845 GV->setAlignment(Alignment);
848 if (parseOptionalComdat(C))
853 return TokError("unknown global variable property!");
860 /// ParseUnnamedAttrGrp
861 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
862 bool LLParser::ParseUnnamedAttrGrp() {
863 assert(Lex.getKind() == lltok::kw_attributes);
864 LocTy AttrGrpLoc = Lex.getLoc();
867 assert(Lex.getKind() == lltok::AttrGrpID);
868 unsigned VarID = Lex.getUIntVal();
869 std::vector<unsigned> unused;
873 if (ParseToken(lltok::equal, "expected '=' here") ||
874 ParseToken(lltok::lbrace, "expected '{' here") ||
875 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
877 ParseToken(lltok::rbrace, "expected end of attribute group"))
880 if (!NumberedAttrBuilders[VarID].hasAttributes())
881 return Error(AttrGrpLoc, "attribute group has no attributes");
886 /// ParseFnAttributeValuePairs
887 /// ::= <attr> | <attr> '=' <value>
888 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
889 std::vector<unsigned> &FwdRefAttrGrps,
890 bool inAttrGrp, LocTy &BuiltinLoc) {
891 bool HaveError = false;
896 lltok::Kind Token = Lex.getKind();
897 if (Token == lltok::kw_builtin)
898 BuiltinLoc = Lex.getLoc();
901 if (!inAttrGrp) return HaveError;
902 return Error(Lex.getLoc(), "unterminated attribute group");
907 case lltok::AttrGrpID: {
908 // Allow a function to reference an attribute group:
910 // define void @foo() #1 { ... }
914 "cannot have an attribute group reference in an attribute group");
916 unsigned AttrGrpNum = Lex.getUIntVal();
917 if (inAttrGrp) break;
919 // Save the reference to the attribute group. We'll fill it in later.
920 FwdRefAttrGrps.push_back(AttrGrpNum);
923 // Target-dependent attributes:
924 case lltok::StringConstant: {
925 std::string Attr = Lex.getStrVal();
928 if (EatIfPresent(lltok::equal) &&
929 ParseStringConstant(Val))
932 B.addAttribute(Attr, Val);
936 // Target-independent attributes:
937 case lltok::kw_align: {
938 // As a hack, we allow function alignment to be initially parsed as an
939 // attribute on a function declaration/definition or added to an attribute
940 // group and later moved to the alignment field.
944 if (ParseToken(lltok::equal, "expected '=' here") ||
945 ParseUInt32(Alignment))
948 if (ParseOptionalAlignment(Alignment))
951 B.addAlignmentAttr(Alignment);
954 case lltok::kw_alignstack: {
958 if (ParseToken(lltok::equal, "expected '=' here") ||
959 ParseUInt32(Alignment))
962 if (ParseOptionalStackAlignment(Alignment))
965 B.addStackAlignmentAttr(Alignment);
968 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
969 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
970 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
971 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
972 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
973 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
974 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
975 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
976 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
977 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
978 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
979 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
980 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
981 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
982 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
983 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
984 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
985 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
986 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
987 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
988 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
989 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
990 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
991 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
992 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
993 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
994 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
997 case lltok::kw_inreg:
998 case lltok::kw_signext:
999 case lltok::kw_zeroext:
1002 "invalid use of attribute on a function");
1004 case lltok::kw_byval:
1005 case lltok::kw_dereferenceable:
1006 case lltok::kw_inalloca:
1007 case lltok::kw_nest:
1008 case lltok::kw_noalias:
1009 case lltok::kw_nocapture:
1010 case lltok::kw_nonnull:
1011 case lltok::kw_returned:
1012 case lltok::kw_sret:
1015 "invalid use of parameter-only attribute on a function");
1023 //===----------------------------------------------------------------------===//
1024 // GlobalValue Reference/Resolution Routines.
1025 //===----------------------------------------------------------------------===//
1027 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1028 /// forward reference record if needed. This can return null if the value
1029 /// exists but does not have the right type.
1030 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1032 PointerType *PTy = dyn_cast<PointerType>(Ty);
1034 Error(Loc, "global variable reference must have pointer type");
1038 // Look this name up in the normal function symbol table.
1040 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1042 // If this is a forward reference for the value, see if we already created a
1043 // forward ref record.
1045 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1046 I = ForwardRefVals.find(Name);
1047 if (I != ForwardRefVals.end())
1048 Val = I->second.first;
1051 // If we have the value in the symbol table or fwd-ref table, return it.
1053 if (Val->getType() == Ty) return Val;
1054 Error(Loc, "'@" + Name + "' defined with type '" +
1055 getTypeString(Val->getType()) + "'");
1059 // Otherwise, create a new forward reference for this value and remember it.
1060 GlobalValue *FwdVal;
1061 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1062 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1064 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1065 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1066 nullptr, GlobalVariable::NotThreadLocal,
1067 PTy->getAddressSpace());
1069 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1073 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1074 PointerType *PTy = dyn_cast<PointerType>(Ty);
1076 Error(Loc, "global variable reference must have pointer type");
1080 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1082 // If this is a forward reference for the value, see if we already created a
1083 // forward ref record.
1085 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1086 I = ForwardRefValIDs.find(ID);
1087 if (I != ForwardRefValIDs.end())
1088 Val = I->second.first;
1091 // If we have the value in the symbol table or fwd-ref table, return it.
1093 if (Val->getType() == Ty) return Val;
1094 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1095 getTypeString(Val->getType()) + "'");
1099 // Otherwise, create a new forward reference for this value and remember it.
1100 GlobalValue *FwdVal;
1101 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1102 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1104 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1105 GlobalValue::ExternalWeakLinkage, nullptr, "");
1107 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1112 //===----------------------------------------------------------------------===//
1113 // Comdat Reference/Resolution Routines.
1114 //===----------------------------------------------------------------------===//
1116 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1117 // Look this name up in the comdat symbol table.
1118 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1119 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1120 if (I != ComdatSymTab.end())
1123 // Otherwise, create a new forward reference for this value and remember it.
1124 Comdat *C = M->getOrInsertComdat(Name);
1125 ForwardRefComdats[Name] = Loc;
1130 //===----------------------------------------------------------------------===//
1132 //===----------------------------------------------------------------------===//
1134 /// ParseToken - If the current token has the specified kind, eat it and return
1135 /// success. Otherwise, emit the specified error and return failure.
1136 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1137 if (Lex.getKind() != T)
1138 return TokError(ErrMsg);
1143 /// ParseStringConstant
1144 /// ::= StringConstant
1145 bool LLParser::ParseStringConstant(std::string &Result) {
1146 if (Lex.getKind() != lltok::StringConstant)
1147 return TokError("expected string constant");
1148 Result = Lex.getStrVal();
1155 bool LLParser::ParseUInt32(unsigned &Val) {
1156 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1157 return TokError("expected integer");
1158 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1159 if (Val64 != unsigned(Val64))
1160 return TokError("expected 32-bit integer (too large)");
1168 bool LLParser::ParseUInt64(uint64_t &Val) {
1169 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1170 return TokError("expected integer");
1171 Val = Lex.getAPSIntVal().getLimitedValue();
1177 /// := 'localdynamic'
1178 /// := 'initialexec'
1180 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1181 switch (Lex.getKind()) {
1183 return TokError("expected localdynamic, initialexec or localexec");
1184 case lltok::kw_localdynamic:
1185 TLM = GlobalVariable::LocalDynamicTLSModel;
1187 case lltok::kw_initialexec:
1188 TLM = GlobalVariable::InitialExecTLSModel;
1190 case lltok::kw_localexec:
1191 TLM = GlobalVariable::LocalExecTLSModel;
1199 /// ParseOptionalThreadLocal
1201 /// := 'thread_local'
1202 /// := 'thread_local' '(' tlsmodel ')'
1203 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1204 TLM = GlobalVariable::NotThreadLocal;
1205 if (!EatIfPresent(lltok::kw_thread_local))
1208 TLM = GlobalVariable::GeneralDynamicTLSModel;
1209 if (Lex.getKind() == lltok::lparen) {
1211 return ParseTLSModel(TLM) ||
1212 ParseToken(lltok::rparen, "expected ')' after thread local model");
1217 /// ParseOptionalAddrSpace
1219 /// := 'addrspace' '(' uint32 ')'
1220 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1222 if (!EatIfPresent(lltok::kw_addrspace))
1224 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1225 ParseUInt32(AddrSpace) ||
1226 ParseToken(lltok::rparen, "expected ')' in address space");
1229 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1230 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1231 bool HaveError = false;
1236 lltok::Kind Token = Lex.getKind();
1238 default: // End of attributes.
1240 case lltok::kw_align: {
1242 if (ParseOptionalAlignment(Alignment))
1244 B.addAlignmentAttr(Alignment);
1247 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1248 case lltok::kw_dereferenceable: {
1250 if (ParseOptionalDereferenceableBytes(Bytes))
1252 B.addDereferenceableAttr(Bytes);
1255 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1256 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1257 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1258 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1259 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1260 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1261 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1262 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1263 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1264 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1265 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1266 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1268 case lltok::kw_alignstack:
1269 case lltok::kw_alwaysinline:
1270 case lltok::kw_builtin:
1271 case lltok::kw_inlinehint:
1272 case lltok::kw_jumptable:
1273 case lltok::kw_minsize:
1274 case lltok::kw_naked:
1275 case lltok::kw_nobuiltin:
1276 case lltok::kw_noduplicate:
1277 case lltok::kw_noimplicitfloat:
1278 case lltok::kw_noinline:
1279 case lltok::kw_nonlazybind:
1280 case lltok::kw_noredzone:
1281 case lltok::kw_noreturn:
1282 case lltok::kw_nounwind:
1283 case lltok::kw_optnone:
1284 case lltok::kw_optsize:
1285 case lltok::kw_returns_twice:
1286 case lltok::kw_sanitize_address:
1287 case lltok::kw_sanitize_memory:
1288 case lltok::kw_sanitize_thread:
1290 case lltok::kw_sspreq:
1291 case lltok::kw_sspstrong:
1292 case lltok::kw_uwtable:
1293 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1301 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1302 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1303 bool HaveError = false;
1308 lltok::Kind Token = Lex.getKind();
1310 default: // End of attributes.
1312 case lltok::kw_dereferenceable: {
1314 if (ParseOptionalDereferenceableBytes(Bytes))
1316 B.addDereferenceableAttr(Bytes);
1319 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1320 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1321 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1322 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1323 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1326 case lltok::kw_align:
1327 case lltok::kw_byval:
1328 case lltok::kw_inalloca:
1329 case lltok::kw_nest:
1330 case lltok::kw_nocapture:
1331 case lltok::kw_returned:
1332 case lltok::kw_sret:
1333 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1336 case lltok::kw_alignstack:
1337 case lltok::kw_alwaysinline:
1338 case lltok::kw_builtin:
1339 case lltok::kw_cold:
1340 case lltok::kw_inlinehint:
1341 case lltok::kw_jumptable:
1342 case lltok::kw_minsize:
1343 case lltok::kw_naked:
1344 case lltok::kw_nobuiltin:
1345 case lltok::kw_noduplicate:
1346 case lltok::kw_noimplicitfloat:
1347 case lltok::kw_noinline:
1348 case lltok::kw_nonlazybind:
1349 case lltok::kw_noredzone:
1350 case lltok::kw_noreturn:
1351 case lltok::kw_nounwind:
1352 case lltok::kw_optnone:
1353 case lltok::kw_optsize:
1354 case lltok::kw_returns_twice:
1355 case lltok::kw_sanitize_address:
1356 case lltok::kw_sanitize_memory:
1357 case lltok::kw_sanitize_thread:
1359 case lltok::kw_sspreq:
1360 case lltok::kw_sspstrong:
1361 case lltok::kw_uwtable:
1362 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1365 case lltok::kw_readnone:
1366 case lltok::kw_readonly:
1367 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1374 /// ParseOptionalLinkage
1381 /// ::= 'linkonce_odr'
1382 /// ::= 'available_externally'
1385 /// ::= 'extern_weak'
1387 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1389 switch (Lex.getKind()) {
1390 default: Res=GlobalValue::ExternalLinkage; return false;
1391 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1392 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1393 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1394 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1395 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1396 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1397 case lltok::kw_available_externally:
1398 Res = GlobalValue::AvailableExternallyLinkage;
1400 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1401 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1402 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1403 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1410 /// ParseOptionalVisibility
1416 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1417 switch (Lex.getKind()) {
1418 default: Res = GlobalValue::DefaultVisibility; return false;
1419 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1420 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1421 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1427 /// ParseOptionalDLLStorageClass
1432 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1433 switch (Lex.getKind()) {
1434 default: Res = GlobalValue::DefaultStorageClass; return false;
1435 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1436 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1442 /// ParseOptionalCallingConv
1446 /// ::= 'kw_intel_ocl_bicc'
1448 /// ::= 'x86_stdcallcc'
1449 /// ::= 'x86_fastcallcc'
1450 /// ::= 'x86_thiscallcc'
1451 /// ::= 'arm_apcscc'
1452 /// ::= 'arm_aapcscc'
1453 /// ::= 'arm_aapcs_vfpcc'
1454 /// ::= 'msp430_intrcc'
1455 /// ::= 'ptx_kernel'
1456 /// ::= 'ptx_device'
1458 /// ::= 'spir_kernel'
1459 /// ::= 'x86_64_sysvcc'
1460 /// ::= 'x86_64_win64cc'
1461 /// ::= 'webkit_jscc'
1463 /// ::= 'preserve_mostcc'
1464 /// ::= 'preserve_allcc'
1467 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1468 switch (Lex.getKind()) {
1469 default: CC = CallingConv::C; return false;
1470 case lltok::kw_ccc: CC = CallingConv::C; break;
1471 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1472 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1473 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1474 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1475 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1476 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1477 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1478 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1479 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1480 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1481 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1482 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1483 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1484 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1485 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1486 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1487 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1488 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1489 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1490 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1491 case lltok::kw_cc: {
1492 unsigned ArbitraryCC;
1494 if (ParseUInt32(ArbitraryCC))
1496 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1505 /// ParseInstructionMetadata
1506 /// ::= !dbg !42 (',' !dbg !57)*
1507 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1508 PerFunctionState *PFS) {
1510 if (Lex.getKind() != lltok::MetadataVar)
1511 return TokError("expected metadata after comma");
1513 std::string Name = Lex.getStrVal();
1514 unsigned MDK = M->getMDKindID(Name);
1518 SMLoc Loc = Lex.getLoc();
1520 if (ParseToken(lltok::exclaim, "expected '!' here"))
1523 // This code is similar to that of ParseMetadataValue, however it needs to
1524 // have special-case code for a forward reference; see the comments on
1525 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1526 // at the top level here.
1527 if (Lex.getKind() == lltok::lbrace) {
1529 if (ParseMetadataListValue(ID, PFS))
1531 assert(ID.Kind == ValID::t_MDNode);
1532 Inst->setMetadata(MDK, ID.MDNodeVal);
1534 unsigned NodeID = 0;
1535 if (ParseMDNodeID(Node, NodeID))
1538 // If we got the node, add it to the instruction.
1539 Inst->setMetadata(MDK, Node);
1541 MDRef R = { Loc, MDK, NodeID };
1542 // Otherwise, remember that this should be resolved later.
1543 ForwardRefInstMetadata[Inst].push_back(R);
1547 if (MDK == LLVMContext::MD_tbaa)
1548 InstsWithTBAATag.push_back(Inst);
1550 // If this is the end of the list, we're done.
1551 } while (EatIfPresent(lltok::comma));
1555 /// ParseOptionalAlignment
1558 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1560 if (!EatIfPresent(lltok::kw_align))
1562 LocTy AlignLoc = Lex.getLoc();
1563 if (ParseUInt32(Alignment)) return true;
1564 if (!isPowerOf2_32(Alignment))
1565 return Error(AlignLoc, "alignment is not a power of two");
1566 if (Alignment > Value::MaximumAlignment)
1567 return Error(AlignLoc, "huge alignments are not supported yet");
1571 /// ParseOptionalDereferenceableBytes
1573 /// ::= 'dereferenceable' '(' 4 ')'
1574 bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1576 if (!EatIfPresent(lltok::kw_dereferenceable))
1578 LocTy ParenLoc = Lex.getLoc();
1579 if (!EatIfPresent(lltok::lparen))
1580 return Error(ParenLoc, "expected '('");
1581 LocTy DerefLoc = Lex.getLoc();
1582 if (ParseUInt64(Bytes)) return true;
1583 ParenLoc = Lex.getLoc();
1584 if (!EatIfPresent(lltok::rparen))
1585 return Error(ParenLoc, "expected ')'");
1587 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1591 /// ParseOptionalCommaAlign
1595 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1597 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1598 bool &AteExtraComma) {
1599 AteExtraComma = false;
1600 while (EatIfPresent(lltok::comma)) {
1601 // Metadata at the end is an early exit.
1602 if (Lex.getKind() == lltok::MetadataVar) {
1603 AteExtraComma = true;
1607 if (Lex.getKind() != lltok::kw_align)
1608 return Error(Lex.getLoc(), "expected metadata or 'align'");
1610 if (ParseOptionalAlignment(Alignment)) return true;
1616 /// ParseScopeAndOrdering
1617 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1620 /// This sets Scope and Ordering to the parsed values.
1621 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1622 AtomicOrdering &Ordering) {
1626 Scope = CrossThread;
1627 if (EatIfPresent(lltok::kw_singlethread))
1628 Scope = SingleThread;
1630 return ParseOrdering(Ordering);
1634 /// ::= AtomicOrdering
1636 /// This sets Ordering to the parsed value.
1637 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1638 switch (Lex.getKind()) {
1639 default: return TokError("Expected ordering on atomic instruction");
1640 case lltok::kw_unordered: Ordering = Unordered; break;
1641 case lltok::kw_monotonic: Ordering = Monotonic; break;
1642 case lltok::kw_acquire: Ordering = Acquire; break;
1643 case lltok::kw_release: Ordering = Release; break;
1644 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1645 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1651 /// ParseOptionalStackAlignment
1653 /// ::= 'alignstack' '(' 4 ')'
1654 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1656 if (!EatIfPresent(lltok::kw_alignstack))
1658 LocTy ParenLoc = Lex.getLoc();
1659 if (!EatIfPresent(lltok::lparen))
1660 return Error(ParenLoc, "expected '('");
1661 LocTy AlignLoc = Lex.getLoc();
1662 if (ParseUInt32(Alignment)) return true;
1663 ParenLoc = Lex.getLoc();
1664 if (!EatIfPresent(lltok::rparen))
1665 return Error(ParenLoc, "expected ')'");
1666 if (!isPowerOf2_32(Alignment))
1667 return Error(AlignLoc, "stack alignment is not a power of two");
1671 /// ParseIndexList - This parses the index list for an insert/extractvalue
1672 /// instruction. This sets AteExtraComma in the case where we eat an extra
1673 /// comma at the end of the line and find that it is followed by metadata.
1674 /// Clients that don't allow metadata can call the version of this function that
1675 /// only takes one argument.
1678 /// ::= (',' uint32)+
1680 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1681 bool &AteExtraComma) {
1682 AteExtraComma = false;
1684 if (Lex.getKind() != lltok::comma)
1685 return TokError("expected ',' as start of index list");
1687 while (EatIfPresent(lltok::comma)) {
1688 if (Lex.getKind() == lltok::MetadataVar) {
1689 AteExtraComma = true;
1693 if (ParseUInt32(Idx)) return true;
1694 Indices.push_back(Idx);
1700 //===----------------------------------------------------------------------===//
1702 //===----------------------------------------------------------------------===//
1704 /// ParseType - Parse a type.
1705 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1706 SMLoc TypeLoc = Lex.getLoc();
1707 switch (Lex.getKind()) {
1709 return TokError("expected type");
1711 // Type ::= 'float' | 'void' (etc)
1712 Result = Lex.getTyVal();
1716 // Type ::= StructType
1717 if (ParseAnonStructType(Result, false))
1720 case lltok::lsquare:
1721 // Type ::= '[' ... ']'
1722 Lex.Lex(); // eat the lsquare.
1723 if (ParseArrayVectorType(Result, false))
1726 case lltok::less: // Either vector or packed struct.
1727 // Type ::= '<' ... '>'
1729 if (Lex.getKind() == lltok::lbrace) {
1730 if (ParseAnonStructType(Result, true) ||
1731 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1733 } else if (ParseArrayVectorType(Result, true))
1736 case lltok::LocalVar: {
1738 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1740 // If the type hasn't been defined yet, create a forward definition and
1741 // remember where that forward def'n was seen (in case it never is defined).
1743 Entry.first = StructType::create(Context, Lex.getStrVal());
1744 Entry.second = Lex.getLoc();
1746 Result = Entry.first;
1751 case lltok::LocalVarID: {
1753 if (Lex.getUIntVal() >= NumberedTypes.size())
1754 NumberedTypes.resize(Lex.getUIntVal()+1);
1755 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1757 // If the type hasn't been defined yet, create a forward definition and
1758 // remember where that forward def'n was seen (in case it never is defined).
1760 Entry.first = StructType::create(Context);
1761 Entry.second = Lex.getLoc();
1763 Result = Entry.first;
1769 // Parse the type suffixes.
1771 switch (Lex.getKind()) {
1774 if (!AllowVoid && Result->isVoidTy())
1775 return Error(TypeLoc, "void type only allowed for function results");
1778 // Type ::= Type '*'
1780 if (Result->isLabelTy())
1781 return TokError("basic block pointers are invalid");
1782 if (Result->isVoidTy())
1783 return TokError("pointers to void are invalid - use i8* instead");
1784 if (!PointerType::isValidElementType(Result))
1785 return TokError("pointer to this type is invalid");
1786 Result = PointerType::getUnqual(Result);
1790 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1791 case lltok::kw_addrspace: {
1792 if (Result->isLabelTy())
1793 return TokError("basic block pointers are invalid");
1794 if (Result->isVoidTy())
1795 return TokError("pointers to void are invalid; use i8* instead");
1796 if (!PointerType::isValidElementType(Result))
1797 return TokError("pointer to this type is invalid");
1799 if (ParseOptionalAddrSpace(AddrSpace) ||
1800 ParseToken(lltok::star, "expected '*' in address space"))
1803 Result = PointerType::get(Result, AddrSpace);
1807 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1809 if (ParseFunctionType(Result))
1816 /// ParseParameterList
1818 /// ::= '(' Arg (',' Arg)* ')'
1820 /// ::= Type OptionalAttributes Value OptionalAttributes
1821 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1822 PerFunctionState &PFS) {
1823 if (ParseToken(lltok::lparen, "expected '(' in call"))
1826 unsigned AttrIndex = 1;
1827 while (Lex.getKind() != lltok::rparen) {
1828 // If this isn't the first argument, we need a comma.
1829 if (!ArgList.empty() &&
1830 ParseToken(lltok::comma, "expected ',' in argument list"))
1833 // Parse the argument.
1835 Type *ArgTy = nullptr;
1836 AttrBuilder ArgAttrs;
1838 if (ParseType(ArgTy, ArgLoc))
1841 // Otherwise, handle normal operands.
1842 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1844 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1849 Lex.Lex(); // Lex the ')'.
1855 /// ParseArgumentList - Parse the argument list for a function type or function
1857 /// ::= '(' ArgTypeListI ')'
1861 /// ::= ArgTypeList ',' '...'
1862 /// ::= ArgType (',' ArgType)*
1864 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1867 assert(Lex.getKind() == lltok::lparen);
1868 Lex.Lex(); // eat the (.
1870 if (Lex.getKind() == lltok::rparen) {
1872 } else if (Lex.getKind() == lltok::dotdotdot) {
1876 LocTy TypeLoc = Lex.getLoc();
1877 Type *ArgTy = nullptr;
1881 if (ParseType(ArgTy) ||
1882 ParseOptionalParamAttrs(Attrs)) return true;
1884 if (ArgTy->isVoidTy())
1885 return Error(TypeLoc, "argument can not have void type");
1887 if (Lex.getKind() == lltok::LocalVar) {
1888 Name = Lex.getStrVal();
1892 if (!FunctionType::isValidArgumentType(ArgTy))
1893 return Error(TypeLoc, "invalid type for function argument");
1895 unsigned AttrIndex = 1;
1896 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1897 AttributeSet::get(ArgTy->getContext(),
1898 AttrIndex++, Attrs), Name));
1900 while (EatIfPresent(lltok::comma)) {
1901 // Handle ... at end of arg list.
1902 if (EatIfPresent(lltok::dotdotdot)) {
1907 // Otherwise must be an argument type.
1908 TypeLoc = Lex.getLoc();
1909 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1911 if (ArgTy->isVoidTy())
1912 return Error(TypeLoc, "argument can not have void type");
1914 if (Lex.getKind() == lltok::LocalVar) {
1915 Name = Lex.getStrVal();
1921 if (!ArgTy->isFirstClassType())
1922 return Error(TypeLoc, "invalid type for function argument");
1924 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1925 AttributeSet::get(ArgTy->getContext(),
1926 AttrIndex++, Attrs),
1931 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1934 /// ParseFunctionType
1935 /// ::= Type ArgumentList OptionalAttrs
1936 bool LLParser::ParseFunctionType(Type *&Result) {
1937 assert(Lex.getKind() == lltok::lparen);
1939 if (!FunctionType::isValidReturnType(Result))
1940 return TokError("invalid function return type");
1942 SmallVector<ArgInfo, 8> ArgList;
1944 if (ParseArgumentList(ArgList, isVarArg))
1947 // Reject names on the arguments lists.
1948 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1949 if (!ArgList[i].Name.empty())
1950 return Error(ArgList[i].Loc, "argument name invalid in function type");
1951 if (ArgList[i].Attrs.hasAttributes(i + 1))
1952 return Error(ArgList[i].Loc,
1953 "argument attributes invalid in function type");
1956 SmallVector<Type*, 16> ArgListTy;
1957 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1958 ArgListTy.push_back(ArgList[i].Ty);
1960 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1964 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1966 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1967 SmallVector<Type*, 8> Elts;
1968 if (ParseStructBody(Elts)) return true;
1970 Result = StructType::get(Context, Elts, Packed);
1974 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1975 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1976 std::pair<Type*, LocTy> &Entry,
1978 // If the type was already defined, diagnose the redefinition.
1979 if (Entry.first && !Entry.second.isValid())
1980 return Error(TypeLoc, "redefinition of type");
1982 // If we have opaque, just return without filling in the definition for the
1983 // struct. This counts as a definition as far as the .ll file goes.
1984 if (EatIfPresent(lltok::kw_opaque)) {
1985 // This type is being defined, so clear the location to indicate this.
1986 Entry.second = SMLoc();
1988 // If this type number has never been uttered, create it.
1990 Entry.first = StructType::create(Context, Name);
1991 ResultTy = Entry.first;
1995 // If the type starts with '<', then it is either a packed struct or a vector.
1996 bool isPacked = EatIfPresent(lltok::less);
1998 // If we don't have a struct, then we have a random type alias, which we
1999 // accept for compatibility with old files. These types are not allowed to be
2000 // forward referenced and not allowed to be recursive.
2001 if (Lex.getKind() != lltok::lbrace) {
2003 return Error(TypeLoc, "forward references to non-struct type");
2007 return ParseArrayVectorType(ResultTy, true);
2008 return ParseType(ResultTy);
2011 // This type is being defined, so clear the location to indicate this.
2012 Entry.second = SMLoc();
2014 // If this type number has never been uttered, create it.
2016 Entry.first = StructType::create(Context, Name);
2018 StructType *STy = cast<StructType>(Entry.first);
2020 SmallVector<Type*, 8> Body;
2021 if (ParseStructBody(Body) ||
2022 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2025 STy->setBody(Body, isPacked);
2031 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2034 /// ::= '{' Type (',' Type)* '}'
2035 /// ::= '<' '{' '}' '>'
2036 /// ::= '<' '{' Type (',' Type)* '}' '>'
2037 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2038 assert(Lex.getKind() == lltok::lbrace);
2039 Lex.Lex(); // Consume the '{'
2041 // Handle the empty struct.
2042 if (EatIfPresent(lltok::rbrace))
2045 LocTy EltTyLoc = Lex.getLoc();
2047 if (ParseType(Ty)) return true;
2050 if (!StructType::isValidElementType(Ty))
2051 return Error(EltTyLoc, "invalid element type for struct");
2053 while (EatIfPresent(lltok::comma)) {
2054 EltTyLoc = Lex.getLoc();
2055 if (ParseType(Ty)) return true;
2057 if (!StructType::isValidElementType(Ty))
2058 return Error(EltTyLoc, "invalid element type for struct");
2063 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2066 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2067 /// token has already been consumed.
2069 /// ::= '[' APSINTVAL 'x' Types ']'
2070 /// ::= '<' APSINTVAL 'x' Types '>'
2071 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2072 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2073 Lex.getAPSIntVal().getBitWidth() > 64)
2074 return TokError("expected number in address space");
2076 LocTy SizeLoc = Lex.getLoc();
2077 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2080 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2083 LocTy TypeLoc = Lex.getLoc();
2084 Type *EltTy = nullptr;
2085 if (ParseType(EltTy)) return true;
2087 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2088 "expected end of sequential type"))
2093 return Error(SizeLoc, "zero element vector is illegal");
2094 if ((unsigned)Size != Size)
2095 return Error(SizeLoc, "size too large for vector");
2096 if (!VectorType::isValidElementType(EltTy))
2097 return Error(TypeLoc, "invalid vector element type");
2098 Result = VectorType::get(EltTy, unsigned(Size));
2100 if (!ArrayType::isValidElementType(EltTy))
2101 return Error(TypeLoc, "invalid array element type");
2102 Result = ArrayType::get(EltTy, Size);
2107 //===----------------------------------------------------------------------===//
2108 // Function Semantic Analysis.
2109 //===----------------------------------------------------------------------===//
2111 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2113 : P(p), F(f), FunctionNumber(functionNumber) {
2115 // Insert unnamed arguments into the NumberedVals list.
2116 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2119 NumberedVals.push_back(AI);
2122 LLParser::PerFunctionState::~PerFunctionState() {
2123 // If there were any forward referenced non-basicblock values, delete them.
2124 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2125 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2126 if (!isa<BasicBlock>(I->second.first)) {
2127 I->second.first->replaceAllUsesWith(
2128 UndefValue::get(I->second.first->getType()));
2129 delete I->second.first;
2130 I->second.first = nullptr;
2133 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2134 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2135 if (!isa<BasicBlock>(I->second.first)) {
2136 I->second.first->replaceAllUsesWith(
2137 UndefValue::get(I->second.first->getType()));
2138 delete I->second.first;
2139 I->second.first = nullptr;
2143 bool LLParser::PerFunctionState::FinishFunction() {
2144 if (!ForwardRefVals.empty())
2145 return P.Error(ForwardRefVals.begin()->second.second,
2146 "use of undefined value '%" + ForwardRefVals.begin()->first +
2148 if (!ForwardRefValIDs.empty())
2149 return P.Error(ForwardRefValIDs.begin()->second.second,
2150 "use of undefined value '%" +
2151 Twine(ForwardRefValIDs.begin()->first) + "'");
2156 /// GetVal - Get a value with the specified name or ID, creating a
2157 /// forward reference record if needed. This can return null if the value
2158 /// exists but does not have the right type.
2159 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2160 Type *Ty, LocTy Loc) {
2161 // Look this name up in the normal function symbol table.
2162 Value *Val = F.getValueSymbolTable().lookup(Name);
2164 // If this is a forward reference for the value, see if we already created a
2165 // forward ref record.
2167 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2168 I = ForwardRefVals.find(Name);
2169 if (I != ForwardRefVals.end())
2170 Val = I->second.first;
2173 // If we have the value in the symbol table or fwd-ref table, return it.
2175 if (Val->getType() == Ty) return Val;
2176 if (Ty->isLabelTy())
2177 P.Error(Loc, "'%" + Name + "' is not a basic block");
2179 P.Error(Loc, "'%" + Name + "' defined with type '" +
2180 getTypeString(Val->getType()) + "'");
2184 // Don't make placeholders with invalid type.
2185 if (!Ty->isFirstClassType()) {
2186 P.Error(Loc, "invalid use of a non-first-class type");
2190 // Otherwise, create a new forward reference for this value and remember it.
2192 if (Ty->isLabelTy())
2193 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2195 FwdVal = new Argument(Ty, Name);
2197 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2201 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2203 // Look this name up in the normal function symbol table.
2204 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2206 // If this is a forward reference for the value, see if we already created a
2207 // forward ref record.
2209 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2210 I = ForwardRefValIDs.find(ID);
2211 if (I != ForwardRefValIDs.end())
2212 Val = I->second.first;
2215 // If we have the value in the symbol table or fwd-ref table, return it.
2217 if (Val->getType() == Ty) return Val;
2218 if (Ty->isLabelTy())
2219 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2221 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2222 getTypeString(Val->getType()) + "'");
2226 if (!Ty->isFirstClassType()) {
2227 P.Error(Loc, "invalid use of a non-first-class type");
2231 // Otherwise, create a new forward reference for this value and remember it.
2233 if (Ty->isLabelTy())
2234 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2236 FwdVal = new Argument(Ty);
2238 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2242 /// SetInstName - After an instruction is parsed and inserted into its
2243 /// basic block, this installs its name.
2244 bool LLParser::PerFunctionState::SetInstName(int NameID,
2245 const std::string &NameStr,
2246 LocTy NameLoc, Instruction *Inst) {
2247 // If this instruction has void type, it cannot have a name or ID specified.
2248 if (Inst->getType()->isVoidTy()) {
2249 if (NameID != -1 || !NameStr.empty())
2250 return P.Error(NameLoc, "instructions returning void cannot have a name");
2254 // If this was a numbered instruction, verify that the instruction is the
2255 // expected value and resolve any forward references.
2256 if (NameStr.empty()) {
2257 // If neither a name nor an ID was specified, just use the next ID.
2259 NameID = NumberedVals.size();
2261 if (unsigned(NameID) != NumberedVals.size())
2262 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2263 Twine(NumberedVals.size()) + "'");
2265 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2266 ForwardRefValIDs.find(NameID);
2267 if (FI != ForwardRefValIDs.end()) {
2268 if (FI->second.first->getType() != Inst->getType())
2269 return P.Error(NameLoc, "instruction forward referenced with type '" +
2270 getTypeString(FI->second.first->getType()) + "'");
2271 FI->second.first->replaceAllUsesWith(Inst);
2272 delete FI->second.first;
2273 ForwardRefValIDs.erase(FI);
2276 NumberedVals.push_back(Inst);
2280 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2281 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2282 FI = ForwardRefVals.find(NameStr);
2283 if (FI != ForwardRefVals.end()) {
2284 if (FI->second.first->getType() != Inst->getType())
2285 return P.Error(NameLoc, "instruction forward referenced with type '" +
2286 getTypeString(FI->second.first->getType()) + "'");
2287 FI->second.first->replaceAllUsesWith(Inst);
2288 delete FI->second.first;
2289 ForwardRefVals.erase(FI);
2292 // Set the name on the instruction.
2293 Inst->setName(NameStr);
2295 if (Inst->getName() != NameStr)
2296 return P.Error(NameLoc, "multiple definition of local value named '" +
2301 /// GetBB - Get a basic block with the specified name or ID, creating a
2302 /// forward reference record if needed.
2303 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2305 return cast_or_null<BasicBlock>(GetVal(Name,
2306 Type::getLabelTy(F.getContext()), Loc));
2309 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2310 return cast_or_null<BasicBlock>(GetVal(ID,
2311 Type::getLabelTy(F.getContext()), Loc));
2314 /// DefineBB - Define the specified basic block, which is either named or
2315 /// unnamed. If there is an error, this returns null otherwise it returns
2316 /// the block being defined.
2317 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2321 BB = GetBB(NumberedVals.size(), Loc);
2323 BB = GetBB(Name, Loc);
2324 if (!BB) return nullptr; // Already diagnosed error.
2326 // Move the block to the end of the function. Forward ref'd blocks are
2327 // inserted wherever they happen to be referenced.
2328 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2330 // Remove the block from forward ref sets.
2332 ForwardRefValIDs.erase(NumberedVals.size());
2333 NumberedVals.push_back(BB);
2335 // BB forward references are already in the function symbol table.
2336 ForwardRefVals.erase(Name);
2342 //===----------------------------------------------------------------------===//
2344 //===----------------------------------------------------------------------===//
2346 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2347 /// type implied. For example, if we parse "4" we don't know what integer type
2348 /// it has. The value will later be combined with its type and checked for
2349 /// sanity. PFS is used to convert function-local operands of metadata (since
2350 /// metadata operands are not just parsed here but also converted to values).
2351 /// PFS can be null when we are not parsing metadata values inside a function.
2352 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2353 ID.Loc = Lex.getLoc();
2354 switch (Lex.getKind()) {
2355 default: return TokError("expected value token");
2356 case lltok::GlobalID: // @42
2357 ID.UIntVal = Lex.getUIntVal();
2358 ID.Kind = ValID::t_GlobalID;
2360 case lltok::GlobalVar: // @foo
2361 ID.StrVal = Lex.getStrVal();
2362 ID.Kind = ValID::t_GlobalName;
2364 case lltok::LocalVarID: // %42
2365 ID.UIntVal = Lex.getUIntVal();
2366 ID.Kind = ValID::t_LocalID;
2368 case lltok::LocalVar: // %foo
2369 ID.StrVal = Lex.getStrVal();
2370 ID.Kind = ValID::t_LocalName;
2372 case lltok::exclaim: // !42, !{...}, or !"foo"
2373 return ParseMetadataValue(ID, PFS);
2375 ID.APSIntVal = Lex.getAPSIntVal();
2376 ID.Kind = ValID::t_APSInt;
2378 case lltok::APFloat:
2379 ID.APFloatVal = Lex.getAPFloatVal();
2380 ID.Kind = ValID::t_APFloat;
2382 case lltok::kw_true:
2383 ID.ConstantVal = ConstantInt::getTrue(Context);
2384 ID.Kind = ValID::t_Constant;
2386 case lltok::kw_false:
2387 ID.ConstantVal = ConstantInt::getFalse(Context);
2388 ID.Kind = ValID::t_Constant;
2390 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2391 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2392 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2394 case lltok::lbrace: {
2395 // ValID ::= '{' ConstVector '}'
2397 SmallVector<Constant*, 16> Elts;
2398 if (ParseGlobalValueVector(Elts) ||
2399 ParseToken(lltok::rbrace, "expected end of struct constant"))
2402 ID.ConstantStructElts = new Constant*[Elts.size()];
2403 ID.UIntVal = Elts.size();
2404 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2405 ID.Kind = ValID::t_ConstantStruct;
2409 // ValID ::= '<' ConstVector '>' --> Vector.
2410 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2412 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2414 SmallVector<Constant*, 16> Elts;
2415 LocTy FirstEltLoc = Lex.getLoc();
2416 if (ParseGlobalValueVector(Elts) ||
2418 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2419 ParseToken(lltok::greater, "expected end of constant"))
2422 if (isPackedStruct) {
2423 ID.ConstantStructElts = new Constant*[Elts.size()];
2424 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2425 ID.UIntVal = Elts.size();
2426 ID.Kind = ValID::t_PackedConstantStruct;
2431 return Error(ID.Loc, "constant vector must not be empty");
2433 if (!Elts[0]->getType()->isIntegerTy() &&
2434 !Elts[0]->getType()->isFloatingPointTy() &&
2435 !Elts[0]->getType()->isPointerTy())
2436 return Error(FirstEltLoc,
2437 "vector elements must have integer, pointer or floating point type");
2439 // Verify that all the vector elements have the same type.
2440 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2441 if (Elts[i]->getType() != Elts[0]->getType())
2442 return Error(FirstEltLoc,
2443 "vector element #" + Twine(i) +
2444 " is not of type '" + getTypeString(Elts[0]->getType()));
2446 ID.ConstantVal = ConstantVector::get(Elts);
2447 ID.Kind = ValID::t_Constant;
2450 case lltok::lsquare: { // Array Constant
2452 SmallVector<Constant*, 16> Elts;
2453 LocTy FirstEltLoc = Lex.getLoc();
2454 if (ParseGlobalValueVector(Elts) ||
2455 ParseToken(lltok::rsquare, "expected end of array constant"))
2458 // Handle empty element.
2460 // Use undef instead of an array because it's inconvenient to determine
2461 // the element type at this point, there being no elements to examine.
2462 ID.Kind = ValID::t_EmptyArray;
2466 if (!Elts[0]->getType()->isFirstClassType())
2467 return Error(FirstEltLoc, "invalid array element type: " +
2468 getTypeString(Elts[0]->getType()));
2470 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2472 // Verify all elements are correct type!
2473 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2474 if (Elts[i]->getType() != Elts[0]->getType())
2475 return Error(FirstEltLoc,
2476 "array element #" + Twine(i) +
2477 " is not of type '" + getTypeString(Elts[0]->getType()));
2480 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2481 ID.Kind = ValID::t_Constant;
2484 case lltok::kw_c: // c "foo"
2486 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2488 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2489 ID.Kind = ValID::t_Constant;
2492 case lltok::kw_asm: {
2493 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2495 bool HasSideEffect, AlignStack, AsmDialect;
2497 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2498 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2499 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2500 ParseStringConstant(ID.StrVal) ||
2501 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2502 ParseToken(lltok::StringConstant, "expected constraint string"))
2504 ID.StrVal2 = Lex.getStrVal();
2505 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2506 (unsigned(AsmDialect)<<2);
2507 ID.Kind = ValID::t_InlineAsm;
2511 case lltok::kw_blockaddress: {
2512 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2517 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2519 ParseToken(lltok::comma, "expected comma in block address expression")||
2520 ParseValID(Label) ||
2521 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2524 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2525 return Error(Fn.Loc, "expected function name in blockaddress");
2526 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2527 return Error(Label.Loc, "expected basic block name in blockaddress");
2529 // Try to find the function (but skip it if it's forward-referenced).
2530 GlobalValue *GV = nullptr;
2531 if (Fn.Kind == ValID::t_GlobalID) {
2532 if (Fn.UIntVal < NumberedVals.size())
2533 GV = NumberedVals[Fn.UIntVal];
2534 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2535 GV = M->getNamedValue(Fn.StrVal);
2537 Function *F = nullptr;
2539 // Confirm that it's actually a function with a definition.
2540 if (!isa<Function>(GV))
2541 return Error(Fn.Loc, "expected function name in blockaddress");
2542 F = cast<Function>(GV);
2543 if (F->isDeclaration())
2544 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2548 // Make a global variable as a placeholder for this reference.
2549 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2551 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2552 GlobalValue::InternalLinkage, nullptr, "");
2553 ID.ConstantVal = FwdRef;
2554 ID.Kind = ValID::t_Constant;
2558 // We found the function; now find the basic block. Don't use PFS, since we
2559 // might be inside a constant expression.
2561 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2562 if (Label.Kind == ValID::t_LocalID)
2563 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2565 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2567 return Error(Label.Loc, "referenced value is not a basic block");
2569 if (Label.Kind == ValID::t_LocalID)
2570 return Error(Label.Loc, "cannot take address of numeric label after "
2571 "the function is defined");
2572 BB = dyn_cast_or_null<BasicBlock>(
2573 F->getValueSymbolTable().lookup(Label.StrVal));
2575 return Error(Label.Loc, "referenced value is not a basic block");
2578 ID.ConstantVal = BlockAddress::get(F, BB);
2579 ID.Kind = ValID::t_Constant;
2583 case lltok::kw_trunc:
2584 case lltok::kw_zext:
2585 case lltok::kw_sext:
2586 case lltok::kw_fptrunc:
2587 case lltok::kw_fpext:
2588 case lltok::kw_bitcast:
2589 case lltok::kw_addrspacecast:
2590 case lltok::kw_uitofp:
2591 case lltok::kw_sitofp:
2592 case lltok::kw_fptoui:
2593 case lltok::kw_fptosi:
2594 case lltok::kw_inttoptr:
2595 case lltok::kw_ptrtoint: {
2596 unsigned Opc = Lex.getUIntVal();
2597 Type *DestTy = nullptr;
2600 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2601 ParseGlobalTypeAndValue(SrcVal) ||
2602 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2603 ParseType(DestTy) ||
2604 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2606 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2607 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2608 getTypeString(SrcVal->getType()) + "' to '" +
2609 getTypeString(DestTy) + "'");
2610 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2612 ID.Kind = ValID::t_Constant;
2615 case lltok::kw_extractvalue: {
2618 SmallVector<unsigned, 4> Indices;
2619 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2620 ParseGlobalTypeAndValue(Val) ||
2621 ParseIndexList(Indices) ||
2622 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2625 if (!Val->getType()->isAggregateType())
2626 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2627 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2628 return Error(ID.Loc, "invalid indices for extractvalue");
2629 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2630 ID.Kind = ValID::t_Constant;
2633 case lltok::kw_insertvalue: {
2635 Constant *Val0, *Val1;
2636 SmallVector<unsigned, 4> Indices;
2637 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2638 ParseGlobalTypeAndValue(Val0) ||
2639 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2640 ParseGlobalTypeAndValue(Val1) ||
2641 ParseIndexList(Indices) ||
2642 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2644 if (!Val0->getType()->isAggregateType())
2645 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2646 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2647 return Error(ID.Loc, "invalid indices for insertvalue");
2648 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2649 ID.Kind = ValID::t_Constant;
2652 case lltok::kw_icmp:
2653 case lltok::kw_fcmp: {
2654 unsigned PredVal, Opc = Lex.getUIntVal();
2655 Constant *Val0, *Val1;
2657 if (ParseCmpPredicate(PredVal, Opc) ||
2658 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2659 ParseGlobalTypeAndValue(Val0) ||
2660 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2661 ParseGlobalTypeAndValue(Val1) ||
2662 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2665 if (Val0->getType() != Val1->getType())
2666 return Error(ID.Loc, "compare operands must have the same type");
2668 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2670 if (Opc == Instruction::FCmp) {
2671 if (!Val0->getType()->isFPOrFPVectorTy())
2672 return Error(ID.Loc, "fcmp requires floating point operands");
2673 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2675 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2676 if (!Val0->getType()->isIntOrIntVectorTy() &&
2677 !Val0->getType()->getScalarType()->isPointerTy())
2678 return Error(ID.Loc, "icmp requires pointer or integer operands");
2679 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2681 ID.Kind = ValID::t_Constant;
2685 // Binary Operators.
2687 case lltok::kw_fadd:
2689 case lltok::kw_fsub:
2691 case lltok::kw_fmul:
2692 case lltok::kw_udiv:
2693 case lltok::kw_sdiv:
2694 case lltok::kw_fdiv:
2695 case lltok::kw_urem:
2696 case lltok::kw_srem:
2697 case lltok::kw_frem:
2699 case lltok::kw_lshr:
2700 case lltok::kw_ashr: {
2704 unsigned Opc = Lex.getUIntVal();
2705 Constant *Val0, *Val1;
2707 LocTy ModifierLoc = Lex.getLoc();
2708 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2709 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2710 if (EatIfPresent(lltok::kw_nuw))
2712 if (EatIfPresent(lltok::kw_nsw)) {
2714 if (EatIfPresent(lltok::kw_nuw))
2717 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2718 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2719 if (EatIfPresent(lltok::kw_exact))
2722 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2723 ParseGlobalTypeAndValue(Val0) ||
2724 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2725 ParseGlobalTypeAndValue(Val1) ||
2726 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2728 if (Val0->getType() != Val1->getType())
2729 return Error(ID.Loc, "operands of constexpr must have same type");
2730 if (!Val0->getType()->isIntOrIntVectorTy()) {
2732 return Error(ModifierLoc, "nuw only applies to integer operations");
2734 return Error(ModifierLoc, "nsw only applies to integer operations");
2736 // Check that the type is valid for the operator.
2738 case Instruction::Add:
2739 case Instruction::Sub:
2740 case Instruction::Mul:
2741 case Instruction::UDiv:
2742 case Instruction::SDiv:
2743 case Instruction::URem:
2744 case Instruction::SRem:
2745 case Instruction::Shl:
2746 case Instruction::AShr:
2747 case Instruction::LShr:
2748 if (!Val0->getType()->isIntOrIntVectorTy())
2749 return Error(ID.Loc, "constexpr requires integer operands");
2751 case Instruction::FAdd:
2752 case Instruction::FSub:
2753 case Instruction::FMul:
2754 case Instruction::FDiv:
2755 case Instruction::FRem:
2756 if (!Val0->getType()->isFPOrFPVectorTy())
2757 return Error(ID.Loc, "constexpr requires fp operands");
2759 default: llvm_unreachable("Unknown binary operator!");
2762 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2763 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2764 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2765 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2767 ID.Kind = ValID::t_Constant;
2771 // Logical Operations
2774 case lltok::kw_xor: {
2775 unsigned Opc = Lex.getUIntVal();
2776 Constant *Val0, *Val1;
2778 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2779 ParseGlobalTypeAndValue(Val0) ||
2780 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2781 ParseGlobalTypeAndValue(Val1) ||
2782 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2784 if (Val0->getType() != Val1->getType())
2785 return Error(ID.Loc, "operands of constexpr must have same type");
2786 if (!Val0->getType()->isIntOrIntVectorTy())
2787 return Error(ID.Loc,
2788 "constexpr requires integer or integer vector operands");
2789 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2790 ID.Kind = ValID::t_Constant;
2794 case lltok::kw_getelementptr:
2795 case lltok::kw_shufflevector:
2796 case lltok::kw_insertelement:
2797 case lltok::kw_extractelement:
2798 case lltok::kw_select: {
2799 unsigned Opc = Lex.getUIntVal();
2800 SmallVector<Constant*, 16> Elts;
2801 bool InBounds = false;
2803 if (Opc == Instruction::GetElementPtr)
2804 InBounds = EatIfPresent(lltok::kw_inbounds);
2805 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2806 ParseGlobalValueVector(Elts) ||
2807 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2810 if (Opc == Instruction::GetElementPtr) {
2811 if (Elts.size() == 0 ||
2812 !Elts[0]->getType()->getScalarType()->isPointerTy())
2813 return Error(ID.Loc, "getelementptr requires pointer operand");
2815 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2816 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2817 return Error(ID.Loc, "invalid indices for getelementptr");
2818 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2820 } else if (Opc == Instruction::Select) {
2821 if (Elts.size() != 3)
2822 return Error(ID.Loc, "expected three operands to select");
2823 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2825 return Error(ID.Loc, Reason);
2826 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2827 } else if (Opc == Instruction::ShuffleVector) {
2828 if (Elts.size() != 3)
2829 return Error(ID.Loc, "expected three operands to shufflevector");
2830 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2831 return Error(ID.Loc, "invalid operands to shufflevector");
2833 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2834 } else if (Opc == Instruction::ExtractElement) {
2835 if (Elts.size() != 2)
2836 return Error(ID.Loc, "expected two operands to extractelement");
2837 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2838 return Error(ID.Loc, "invalid extractelement operands");
2839 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2841 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2842 if (Elts.size() != 3)
2843 return Error(ID.Loc, "expected three operands to insertelement");
2844 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2845 return Error(ID.Loc, "invalid insertelement operands");
2847 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2850 ID.Kind = ValID::t_Constant;
2859 /// ParseGlobalValue - Parse a global value with the specified type.
2860 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2864 bool Parsed = ParseValID(ID) ||
2865 ConvertValIDToValue(Ty, ID, V, nullptr);
2866 if (V && !(C = dyn_cast<Constant>(V)))
2867 return Error(ID.Loc, "global values must be constants");
2871 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2873 return ParseType(Ty) ||
2874 ParseGlobalValue(Ty, V);
2877 bool LLParser::parseOptionalComdat(Comdat *&C) {
2879 if (!EatIfPresent(lltok::kw_comdat))
2881 if (Lex.getKind() != lltok::ComdatVar)
2882 return TokError("expected comdat variable");
2883 LocTy Loc = Lex.getLoc();
2884 StringRef Name = Lex.getStrVal();
2885 C = getComdat(Name, Loc);
2890 /// ParseGlobalValueVector
2892 /// ::= TypeAndValue (',' TypeAndValue)*
2893 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2895 if (Lex.getKind() == lltok::rbrace ||
2896 Lex.getKind() == lltok::rsquare ||
2897 Lex.getKind() == lltok::greater ||
2898 Lex.getKind() == lltok::rparen)
2902 if (ParseGlobalTypeAndValue(C)) return true;
2905 while (EatIfPresent(lltok::comma)) {
2906 if (ParseGlobalTypeAndValue(C)) return true;
2913 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2914 assert(Lex.getKind() == lltok::lbrace);
2917 SmallVector<Value*, 16> Elts;
2918 if (ParseMDNodeVector(Elts, PFS) ||
2919 ParseToken(lltok::rbrace, "expected end of metadata node"))
2922 ID.MDNodeVal = MDNode::get(Context, Elts);
2923 ID.Kind = ValID::t_MDNode;
2927 /// ParseMetadataValue
2931 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2932 assert(Lex.getKind() == lltok::exclaim);
2937 if (Lex.getKind() == lltok::lbrace)
2938 return ParseMetadataListValue(ID, PFS);
2940 // Standalone metadata reference
2942 if (Lex.getKind() == lltok::APSInt) {
2943 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2944 ID.Kind = ValID::t_MDNode;
2949 // ::= '!' STRINGCONSTANT
2950 if (ParseMDString(ID.MDStringVal)) return true;
2951 ID.Kind = ValID::t_MDString;
2956 //===----------------------------------------------------------------------===//
2957 // Function Parsing.
2958 //===----------------------------------------------------------------------===//
2960 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2961 PerFunctionState *PFS) {
2962 if (Ty->isFunctionTy())
2963 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2966 case ValID::t_LocalID:
2967 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2968 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2969 return V == nullptr;
2970 case ValID::t_LocalName:
2971 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2972 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2973 return V == nullptr;
2974 case ValID::t_InlineAsm: {
2975 PointerType *PTy = dyn_cast<PointerType>(Ty);
2977 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
2978 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2979 return Error(ID.Loc, "invalid type for inline asm constraint string");
2980 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2981 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2984 case ValID::t_MDNode:
2985 if (!Ty->isMetadataTy())
2986 return Error(ID.Loc, "metadata value must have metadata type");
2989 case ValID::t_MDString:
2990 if (!Ty->isMetadataTy())
2991 return Error(ID.Loc, "metadata value must have metadata type");
2994 case ValID::t_GlobalName:
2995 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2996 return V == nullptr;
2997 case ValID::t_GlobalID:
2998 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2999 return V == nullptr;
3000 case ValID::t_APSInt:
3001 if (!Ty->isIntegerTy())
3002 return Error(ID.Loc, "integer constant must have integer type");
3003 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3004 V = ConstantInt::get(Context, ID.APSIntVal);
3006 case ValID::t_APFloat:
3007 if (!Ty->isFloatingPointTy() ||
3008 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3009 return Error(ID.Loc, "floating point constant invalid for type");
3011 // The lexer has no type info, so builds all half, float, and double FP
3012 // constants as double. Fix this here. Long double does not need this.
3013 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3016 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3018 else if (Ty->isFloatTy())
3019 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3022 V = ConstantFP::get(Context, ID.APFloatVal);
3024 if (V->getType() != Ty)
3025 return Error(ID.Loc, "floating point constant does not have type '" +
3026 getTypeString(Ty) + "'");
3030 if (!Ty->isPointerTy())
3031 return Error(ID.Loc, "null must be a pointer type");
3032 V = ConstantPointerNull::get(cast<PointerType>(Ty));
3034 case ValID::t_Undef:
3035 // FIXME: LabelTy should not be a first-class type.
3036 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3037 return Error(ID.Loc, "invalid type for undef constant");
3038 V = UndefValue::get(Ty);
3040 case ValID::t_EmptyArray:
3041 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3042 return Error(ID.Loc, "invalid empty array initializer");
3043 V = UndefValue::get(Ty);
3046 // FIXME: LabelTy should not be a first-class type.
3047 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3048 return Error(ID.Loc, "invalid type for null constant");
3049 V = Constant::getNullValue(Ty);
3051 case ValID::t_Constant:
3052 if (ID.ConstantVal->getType() != Ty)
3053 return Error(ID.Loc, "constant expression type mismatch");
3057 case ValID::t_ConstantStruct:
3058 case ValID::t_PackedConstantStruct:
3059 if (StructType *ST = dyn_cast<StructType>(Ty)) {
3060 if (ST->getNumElements() != ID.UIntVal)
3061 return Error(ID.Loc,
3062 "initializer with struct type has wrong # elements");
3063 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3064 return Error(ID.Loc, "packed'ness of initializer and type don't match");
3066 // Verify that the elements are compatible with the structtype.
3067 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3068 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3069 return Error(ID.Loc, "element " + Twine(i) +
3070 " of struct initializer doesn't match struct element type");
3072 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3075 return Error(ID.Loc, "constant expression type mismatch");
3078 llvm_unreachable("Invalid ValID");
3081 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
3084 return ParseValID(ID, PFS) ||
3085 ConvertValIDToValue(Ty, ID, V, PFS);
3088 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
3090 return ParseType(Ty) ||
3091 ParseValue(Ty, V, PFS);
3094 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3095 PerFunctionState &PFS) {
3098 if (ParseTypeAndValue(V, PFS)) return true;
3099 if (!isa<BasicBlock>(V))
3100 return Error(Loc, "expected a basic block");
3101 BB = cast<BasicBlock>(V);
3107 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3108 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3109 /// OptionalAlign OptGC OptionalPrefix
3110 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3111 // Parse the linkage.
3112 LocTy LinkageLoc = Lex.getLoc();
3115 unsigned Visibility;
3116 unsigned DLLStorageClass;
3117 AttrBuilder RetAttrs;
3119 Type *RetType = nullptr;
3120 LocTy RetTypeLoc = Lex.getLoc();
3121 if (ParseOptionalLinkage(Linkage) ||
3122 ParseOptionalVisibility(Visibility) ||
3123 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3124 ParseOptionalCallingConv(CC) ||
3125 ParseOptionalReturnAttrs(RetAttrs) ||
3126 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3129 // Verify that the linkage is ok.
3130 switch ((GlobalValue::LinkageTypes)Linkage) {
3131 case GlobalValue::ExternalLinkage:
3132 break; // always ok.
3133 case GlobalValue::ExternalWeakLinkage:
3135 return Error(LinkageLoc, "invalid linkage for function definition");
3137 case GlobalValue::PrivateLinkage:
3138 case GlobalValue::InternalLinkage:
3139 case GlobalValue::AvailableExternallyLinkage:
3140 case GlobalValue::LinkOnceAnyLinkage:
3141 case GlobalValue::LinkOnceODRLinkage:
3142 case GlobalValue::WeakAnyLinkage:
3143 case GlobalValue::WeakODRLinkage:
3145 return Error(LinkageLoc, "invalid linkage for function declaration");
3147 case GlobalValue::AppendingLinkage:
3148 case GlobalValue::CommonLinkage:
3149 return Error(LinkageLoc, "invalid function linkage type");
3152 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3153 return Error(LinkageLoc,
3154 "symbol with local linkage must have default visibility");
3156 if (!FunctionType::isValidReturnType(RetType))
3157 return Error(RetTypeLoc, "invalid function return type");
3159 LocTy NameLoc = Lex.getLoc();
3161 std::string FunctionName;
3162 if (Lex.getKind() == lltok::GlobalVar) {
3163 FunctionName = Lex.getStrVal();
3164 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3165 unsigned NameID = Lex.getUIntVal();
3167 if (NameID != NumberedVals.size())
3168 return TokError("function expected to be numbered '%" +
3169 Twine(NumberedVals.size()) + "'");
3171 return TokError("expected function name");
3176 if (Lex.getKind() != lltok::lparen)
3177 return TokError("expected '(' in function argument list");
3179 SmallVector<ArgInfo, 8> ArgList;
3181 AttrBuilder FuncAttrs;
3182 std::vector<unsigned> FwdRefAttrGrps;
3184 std::string Section;
3188 LocTy UnnamedAddrLoc;
3189 Constant *Prefix = nullptr;
3192 if (ParseArgumentList(ArgList, isVarArg) ||
3193 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3195 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3197 (EatIfPresent(lltok::kw_section) &&
3198 ParseStringConstant(Section)) ||
3199 parseOptionalComdat(C) ||
3200 ParseOptionalAlignment(Alignment) ||
3201 (EatIfPresent(lltok::kw_gc) &&
3202 ParseStringConstant(GC)) ||
3203 (EatIfPresent(lltok::kw_prefix) &&
3204 ParseGlobalTypeAndValue(Prefix)))
3207 if (FuncAttrs.contains(Attribute::Builtin))
3208 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3210 // If the alignment was parsed as an attribute, move to the alignment field.
3211 if (FuncAttrs.hasAlignmentAttr()) {
3212 Alignment = FuncAttrs.getAlignment();
3213 FuncAttrs.removeAttribute(Attribute::Alignment);
3216 // Okay, if we got here, the function is syntactically valid. Convert types
3217 // and do semantic checks.
3218 std::vector<Type*> ParamTypeList;
3219 SmallVector<AttributeSet, 8> Attrs;
3221 if (RetAttrs.hasAttributes())
3222 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3223 AttributeSet::ReturnIndex,
3226 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3227 ParamTypeList.push_back(ArgList[i].Ty);
3228 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3229 AttrBuilder B(ArgList[i].Attrs, i + 1);
3230 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3234 if (FuncAttrs.hasAttributes())
3235 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3236 AttributeSet::FunctionIndex,
3239 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3241 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3242 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3245 FunctionType::get(RetType, ParamTypeList, isVarArg);
3246 PointerType *PFT = PointerType::getUnqual(FT);
3249 if (!FunctionName.empty()) {
3250 // If this was a definition of a forward reference, remove the definition
3251 // from the forward reference table and fill in the forward ref.
3252 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3253 ForwardRefVals.find(FunctionName);
3254 if (FRVI != ForwardRefVals.end()) {
3255 Fn = M->getFunction(FunctionName);
3257 return Error(FRVI->second.second, "invalid forward reference to "
3258 "function as global value!");
3259 if (Fn->getType() != PFT)
3260 return Error(FRVI->second.second, "invalid forward reference to "
3261 "function '" + FunctionName + "' with wrong type!");
3263 ForwardRefVals.erase(FRVI);
3264 } else if ((Fn = M->getFunction(FunctionName))) {
3265 // Reject redefinitions.
3266 return Error(NameLoc, "invalid redefinition of function '" +
3267 FunctionName + "'");
3268 } else if (M->getNamedValue(FunctionName)) {
3269 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3273 // If this is a definition of a forward referenced function, make sure the
3275 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3276 = ForwardRefValIDs.find(NumberedVals.size());
3277 if (I != ForwardRefValIDs.end()) {
3278 Fn = cast<Function>(I->second.first);
3279 if (Fn->getType() != PFT)
3280 return Error(NameLoc, "type of definition and forward reference of '@" +
3281 Twine(NumberedVals.size()) + "' disagree");
3282 ForwardRefValIDs.erase(I);
3287 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3288 else // Move the forward-reference to the correct spot in the module.
3289 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3291 if (FunctionName.empty())
3292 NumberedVals.push_back(Fn);
3294 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3295 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3296 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3297 Fn->setCallingConv(CC);
3298 Fn->setAttributes(PAL);
3299 Fn->setUnnamedAddr(UnnamedAddr);
3300 Fn->setAlignment(Alignment);
3301 Fn->setSection(Section);
3303 if (!GC.empty()) Fn->setGC(GC.c_str());
3304 Fn->setPrefixData(Prefix);
3305 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3307 // Add all of the arguments we parsed to the function.
3308 Function::arg_iterator ArgIt = Fn->arg_begin();
3309 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3310 // If the argument has a name, insert it into the argument symbol table.
3311 if (ArgList[i].Name.empty()) continue;
3313 // Set the name, if it conflicted, it will be auto-renamed.
3314 ArgIt->setName(ArgList[i].Name);
3316 if (ArgIt->getName() != ArgList[i].Name)
3317 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3318 ArgList[i].Name + "'");
3324 // Check the a declaration has no block address forward references.
3326 if (FunctionName.empty()) {
3327 ID.Kind = ValID::t_GlobalID;
3328 ID.UIntVal = NumberedVals.size() - 1;
3330 ID.Kind = ValID::t_GlobalName;
3331 ID.StrVal = FunctionName;
3333 auto Blocks = ForwardRefBlockAddresses.find(ID);
3334 if (Blocks != ForwardRefBlockAddresses.end())
3335 return Error(Blocks->first.Loc,
3336 "cannot take blockaddress inside a declaration");
3340 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
3342 if (FunctionNumber == -1) {
3343 ID.Kind = ValID::t_GlobalName;
3344 ID.StrVal = F.getName();
3346 ID.Kind = ValID::t_GlobalID;
3347 ID.UIntVal = FunctionNumber;
3350 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
3351 if (Blocks == P.ForwardRefBlockAddresses.end())
3354 for (const auto &I : Blocks->second) {
3355 const ValID &BBID = I.first;
3356 GlobalValue *GV = I.second;
3358 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
3359 "Expected local id or name");
3361 if (BBID.Kind == ValID::t_LocalName)
3362 BB = GetBB(BBID.StrVal, BBID.Loc);
3364 BB = GetBB(BBID.UIntVal, BBID.Loc);
3366 return P.Error(BBID.Loc, "referenced value is not a basic block");
3368 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
3369 GV->eraseFromParent();
3372 P.ForwardRefBlockAddresses.erase(Blocks);
3376 /// ParseFunctionBody
3377 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
3378 bool LLParser::ParseFunctionBody(Function &Fn) {
3379 if (Lex.getKind() != lltok::lbrace)
3380 return TokError("expected '{' in function body");
3381 Lex.Lex(); // eat the {.
3383 int FunctionNumber = -1;
3384 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3386 PerFunctionState PFS(*this, Fn, FunctionNumber);
3388 // Resolve block addresses and allow basic blocks to be forward-declared
3389 // within this function.
3390 if (PFS.resolveForwardRefBlockAddresses())
3392 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
3394 // We need at least one basic block.
3395 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
3396 return TokError("function body requires at least one basic block");
3398 while (Lex.getKind() != lltok::rbrace &&
3399 Lex.getKind() != lltok::kw_uselistorder)
3400 if (ParseBasicBlock(PFS)) return true;
3402 while (Lex.getKind() != lltok::rbrace)
3403 if (ParseUseListOrder(&PFS))
3409 // Verify function is ok.
3410 return PFS.FinishFunction();
3414 /// ::= LabelStr? Instruction*
3415 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3416 // If this basic block starts out with a name, remember it.
3418 LocTy NameLoc = Lex.getLoc();
3419 if (Lex.getKind() == lltok::LabelStr) {
3420 Name = Lex.getStrVal();
3424 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3425 if (!BB) return true;
3427 std::string NameStr;
3429 // Parse the instructions in this block until we get a terminator.
3432 // This instruction may have three possibilities for a name: a) none
3433 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3434 LocTy NameLoc = Lex.getLoc();
3438 if (Lex.getKind() == lltok::LocalVarID) {
3439 NameID = Lex.getUIntVal();
3441 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3443 } else if (Lex.getKind() == lltok::LocalVar) {
3444 NameStr = Lex.getStrVal();
3446 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3450 switch (ParseInstruction(Inst, BB, PFS)) {
3451 default: llvm_unreachable("Unknown ParseInstruction result!");
3452 case InstError: return true;
3454 BB->getInstList().push_back(Inst);
3456 // With a normal result, we check to see if the instruction is followed by
3457 // a comma and metadata.
3458 if (EatIfPresent(lltok::comma))
3459 if (ParseInstructionMetadata(Inst, &PFS))
3462 case InstExtraComma:
3463 BB->getInstList().push_back(Inst);
3465 // If the instruction parser ate an extra comma at the end of it, it
3466 // *must* be followed by metadata.
3467 if (ParseInstructionMetadata(Inst, &PFS))
3472 // Set the name on the instruction.
3473 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3474 } while (!isa<TerminatorInst>(Inst));
3479 //===----------------------------------------------------------------------===//
3480 // Instruction Parsing.
3481 //===----------------------------------------------------------------------===//
3483 /// ParseInstruction - Parse one of the many different instructions.
3485 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3486 PerFunctionState &PFS) {
3487 lltok::Kind Token = Lex.getKind();
3488 if (Token == lltok::Eof)
3489 return TokError("found end of file when expecting more instructions");
3490 LocTy Loc = Lex.getLoc();
3491 unsigned KeywordVal = Lex.getUIntVal();
3492 Lex.Lex(); // Eat the keyword.
3495 default: return Error(Loc, "expected instruction opcode");
3496 // Terminator Instructions.
3497 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3498 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3499 case lltok::kw_br: return ParseBr(Inst, PFS);
3500 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3501 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3502 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3503 case lltok::kw_resume: return ParseResume(Inst, PFS);
3504 // Binary Operators.
3508 case lltok::kw_shl: {
3509 bool NUW = EatIfPresent(lltok::kw_nuw);
3510 bool NSW = EatIfPresent(lltok::kw_nsw);
3511 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3513 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3515 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3516 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3519 case lltok::kw_fadd:
3520 case lltok::kw_fsub:
3521 case lltok::kw_fmul:
3522 case lltok::kw_fdiv:
3523 case lltok::kw_frem: {
3524 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3525 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3529 Inst->setFastMathFlags(FMF);
3533 case lltok::kw_sdiv:
3534 case lltok::kw_udiv:
3535 case lltok::kw_lshr:
3536 case lltok::kw_ashr: {
3537 bool Exact = EatIfPresent(lltok::kw_exact);
3539 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3540 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3544 case lltok::kw_urem:
3545 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3548 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3549 case lltok::kw_icmp:
3550 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3552 case lltok::kw_trunc:
3553 case lltok::kw_zext:
3554 case lltok::kw_sext:
3555 case lltok::kw_fptrunc:
3556 case lltok::kw_fpext:
3557 case lltok::kw_bitcast:
3558 case lltok::kw_addrspacecast:
3559 case lltok::kw_uitofp:
3560 case lltok::kw_sitofp:
3561 case lltok::kw_fptoui:
3562 case lltok::kw_fptosi:
3563 case lltok::kw_inttoptr:
3564 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3566 case lltok::kw_select: return ParseSelect(Inst, PFS);
3567 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3568 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3569 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3570 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3571 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3572 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3574 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3575 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3576 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3578 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3579 case lltok::kw_load: return ParseLoad(Inst, PFS);
3580 case lltok::kw_store: return ParseStore(Inst, PFS);
3581 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3582 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3583 case lltok::kw_fence: return ParseFence(Inst, PFS);
3584 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3585 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3586 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3590 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3591 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3592 if (Opc == Instruction::FCmp) {
3593 switch (Lex.getKind()) {
3594 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3595 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3596 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3597 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3598 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3599 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3600 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3601 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3602 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3603 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3604 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3605 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3606 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3607 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3608 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3609 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3610 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3613 switch (Lex.getKind()) {
3614 default: return TokError("expected icmp predicate (e.g. 'eq')");
3615 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3616 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3617 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3618 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3619 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3620 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3621 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3622 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3623 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3624 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3631 //===----------------------------------------------------------------------===//
3632 // Terminator Instructions.
3633 //===----------------------------------------------------------------------===//
3635 /// ParseRet - Parse a return instruction.
3636 /// ::= 'ret' void (',' !dbg, !1)*
3637 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3638 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3639 PerFunctionState &PFS) {
3640 SMLoc TypeLoc = Lex.getLoc();
3642 if (ParseType(Ty, true /*void allowed*/)) return true;
3644 Type *ResType = PFS.getFunction().getReturnType();
3646 if (Ty->isVoidTy()) {
3647 if (!ResType->isVoidTy())
3648 return Error(TypeLoc, "value doesn't match function result type '" +
3649 getTypeString(ResType) + "'");
3651 Inst = ReturnInst::Create(Context);
3656 if (ParseValue(Ty, RV, PFS)) return true;
3658 if (ResType != RV->getType())
3659 return Error(TypeLoc, "value doesn't match function result type '" +
3660 getTypeString(ResType) + "'");
3662 Inst = ReturnInst::Create(Context, RV);
3668 /// ::= 'br' TypeAndValue
3669 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3670 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3673 BasicBlock *Op1, *Op2;
3674 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3676 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3677 Inst = BranchInst::Create(BB);
3681 if (Op0->getType() != Type::getInt1Ty(Context))
3682 return Error(Loc, "branch condition must have 'i1' type");
3684 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3685 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3686 ParseToken(lltok::comma, "expected ',' after true destination") ||
3687 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3690 Inst = BranchInst::Create(Op1, Op2, Op0);
3696 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3698 /// ::= (TypeAndValue ',' TypeAndValue)*
3699 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3700 LocTy CondLoc, BBLoc;
3702 BasicBlock *DefaultBB;
3703 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3704 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3705 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3706 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3709 if (!Cond->getType()->isIntegerTy())
3710 return Error(CondLoc, "switch condition must have integer type");
3712 // Parse the jump table pairs.
3713 SmallPtrSet<Value*, 32> SeenCases;
3714 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3715 while (Lex.getKind() != lltok::rsquare) {
3719 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3720 ParseToken(lltok::comma, "expected ',' after case value") ||
3721 ParseTypeAndBasicBlock(DestBB, PFS))
3724 if (!SeenCases.insert(Constant))
3725 return Error(CondLoc, "duplicate case value in switch");
3726 if (!isa<ConstantInt>(Constant))
3727 return Error(CondLoc, "case value is not a constant integer");
3729 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3732 Lex.Lex(); // Eat the ']'.
3734 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3735 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3736 SI->addCase(Table[i].first, Table[i].second);
3743 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3744 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3747 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3748 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3749 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3752 if (!Address->getType()->isPointerTy())
3753 return Error(AddrLoc, "indirectbr address must have pointer type");
3755 // Parse the destination list.
3756 SmallVector<BasicBlock*, 16> DestList;
3758 if (Lex.getKind() != lltok::rsquare) {
3760 if (ParseTypeAndBasicBlock(DestBB, PFS))
3762 DestList.push_back(DestBB);
3764 while (EatIfPresent(lltok::comma)) {
3765 if (ParseTypeAndBasicBlock(DestBB, PFS))
3767 DestList.push_back(DestBB);
3771 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3774 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3775 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3776 IBI->addDestination(DestList[i]);
3783 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3784 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3785 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3786 LocTy CallLoc = Lex.getLoc();
3787 AttrBuilder RetAttrs, FnAttrs;
3788 std::vector<unsigned> FwdRefAttrGrps;
3791 Type *RetType = nullptr;
3794 SmallVector<ParamInfo, 16> ArgList;
3796 BasicBlock *NormalBB, *UnwindBB;
3797 if (ParseOptionalCallingConv(CC) ||
3798 ParseOptionalReturnAttrs(RetAttrs) ||
3799 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3800 ParseValID(CalleeID) ||
3801 ParseParameterList(ArgList, PFS) ||
3802 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3804 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3805 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3806 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3807 ParseTypeAndBasicBlock(UnwindBB, PFS))
3810 // If RetType is a non-function pointer type, then this is the short syntax
3811 // for the call, which means that RetType is just the return type. Infer the
3812 // rest of the function argument types from the arguments that are present.
3813 PointerType *PFTy = nullptr;
3814 FunctionType *Ty = nullptr;
3815 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3816 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3817 // Pull out the types of all of the arguments...
3818 std::vector<Type*> ParamTypes;
3819 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3820 ParamTypes.push_back(ArgList[i].V->getType());
3822 if (!FunctionType::isValidReturnType(RetType))
3823 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3825 Ty = FunctionType::get(RetType, ParamTypes, false);
3826 PFTy = PointerType::getUnqual(Ty);
3829 // Look up the callee.
3831 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3833 // Set up the Attribute for the function.
3834 SmallVector<AttributeSet, 8> Attrs;
3835 if (RetAttrs.hasAttributes())
3836 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3837 AttributeSet::ReturnIndex,
3840 SmallVector<Value*, 8> Args;
3842 // Loop through FunctionType's arguments and ensure they are specified
3843 // correctly. Also, gather any parameter attributes.
3844 FunctionType::param_iterator I = Ty->param_begin();
3845 FunctionType::param_iterator E = Ty->param_end();
3846 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3847 Type *ExpectedTy = nullptr;
3850 } else if (!Ty->isVarArg()) {
3851 return Error(ArgList[i].Loc, "too many arguments specified");
3854 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3855 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3856 getTypeString(ExpectedTy) + "'");
3857 Args.push_back(ArgList[i].V);
3858 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3859 AttrBuilder B(ArgList[i].Attrs, i + 1);
3860 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3865 return Error(CallLoc, "not enough parameters specified for call");
3867 if (FnAttrs.hasAttributes())
3868 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3869 AttributeSet::FunctionIndex,
3872 // Finish off the Attribute and check them
3873 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3875 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3876 II->setCallingConv(CC);
3877 II->setAttributes(PAL);
3878 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3884 /// ::= 'resume' TypeAndValue
3885 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3886 Value *Exn; LocTy ExnLoc;
3887 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3890 ResumeInst *RI = ResumeInst::Create(Exn);
3895 //===----------------------------------------------------------------------===//
3896 // Binary Operators.
3897 //===----------------------------------------------------------------------===//
3900 /// ::= ArithmeticOps TypeAndValue ',' Value
3902 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3903 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3904 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3905 unsigned Opc, unsigned OperandType) {
3906 LocTy Loc; Value *LHS, *RHS;
3907 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3908 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3909 ParseValue(LHS->getType(), RHS, PFS))
3913 switch (OperandType) {
3914 default: llvm_unreachable("Unknown operand type!");
3915 case 0: // int or FP.
3916 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3917 LHS->getType()->isFPOrFPVectorTy();
3919 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3920 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3924 return Error(Loc, "invalid operand type for instruction");
3926 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3931 /// ::= ArithmeticOps TypeAndValue ',' Value {
3932 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3934 LocTy Loc; Value *LHS, *RHS;
3935 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3936 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3937 ParseValue(LHS->getType(), RHS, PFS))
3940 if (!LHS->getType()->isIntOrIntVectorTy())
3941 return Error(Loc,"instruction requires integer or integer vector operands");
3943 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3949 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3950 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3951 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3953 // Parse the integer/fp comparison predicate.
3957 if (ParseCmpPredicate(Pred, Opc) ||
3958 ParseTypeAndValue(LHS, Loc, PFS) ||
3959 ParseToken(lltok::comma, "expected ',' after compare value") ||
3960 ParseValue(LHS->getType(), RHS, PFS))
3963 if (Opc == Instruction::FCmp) {
3964 if (!LHS->getType()->isFPOrFPVectorTy())
3965 return Error(Loc, "fcmp requires floating point operands");
3966 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3968 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3969 if (!LHS->getType()->isIntOrIntVectorTy() &&
3970 !LHS->getType()->getScalarType()->isPointerTy())
3971 return Error(Loc, "icmp requires integer operands");
3972 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3977 //===----------------------------------------------------------------------===//
3978 // Other Instructions.
3979 //===----------------------------------------------------------------------===//
3983 /// ::= CastOpc TypeAndValue 'to' Type
3984 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3988 Type *DestTy = nullptr;
3989 if (ParseTypeAndValue(Op, Loc, PFS) ||
3990 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3994 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3995 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3996 return Error(Loc, "invalid cast opcode for cast from '" +
3997 getTypeString(Op->getType()) + "' to '" +
3998 getTypeString(DestTy) + "'");
4000 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4005 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4006 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4008 Value *Op0, *Op1, *Op2;
4009 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4010 ParseToken(lltok::comma, "expected ',' after select condition") ||
4011 ParseTypeAndValue(Op1, PFS) ||
4012 ParseToken(lltok::comma, "expected ',' after select value") ||
4013 ParseTypeAndValue(Op2, PFS))
4016 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4017 return Error(Loc, Reason);
4019 Inst = SelectInst::Create(Op0, Op1, Op2);
4024 /// ::= 'va_arg' TypeAndValue ',' Type
4025 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
4027 Type *EltTy = nullptr;
4029 if (ParseTypeAndValue(Op, PFS) ||
4030 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
4031 ParseType(EltTy, TypeLoc))
4034 if (!EltTy->isFirstClassType())
4035 return Error(TypeLoc, "va_arg requires operand with first class type");
4037 Inst = new VAArgInst(Op, EltTy);
4041 /// ParseExtractElement
4042 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4043 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4046 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4047 ParseToken(lltok::comma, "expected ',' after extract value") ||
4048 ParseTypeAndValue(Op1, PFS))
4051 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4052 return Error(Loc, "invalid extractelement operands");
4054 Inst = ExtractElementInst::Create(Op0, Op1);
4058 /// ParseInsertElement
4059 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4060 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4062 Value *Op0, *Op1, *Op2;
4063 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4064 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4065 ParseTypeAndValue(Op1, PFS) ||
4066 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4067 ParseTypeAndValue(Op2, PFS))
4070 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
4071 return Error(Loc, "invalid insertelement operands");
4073 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4077 /// ParseShuffleVector
4078 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4079 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4081 Value *Op0, *Op1, *Op2;
4082 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4083 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4084 ParseTypeAndValue(Op1, PFS) ||
4085 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4086 ParseTypeAndValue(Op2, PFS))
4089 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
4090 return Error(Loc, "invalid shufflevector operands");
4092 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4097 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
4098 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
4099 Type *Ty = nullptr; LocTy TypeLoc;
4102 if (ParseType(Ty, TypeLoc) ||
4103 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4104 ParseValue(Ty, Op0, PFS) ||
4105 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4106 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4107 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4110 bool AteExtraComma = false;
4111 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4113 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
4115 if (!EatIfPresent(lltok::comma))
4118 if (Lex.getKind() == lltok::MetadataVar) {
4119 AteExtraComma = true;
4123 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4124 ParseValue(Ty, Op0, PFS) ||
4125 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4126 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4127 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4131 if (!Ty->isFirstClassType())
4132 return Error(TypeLoc, "phi node must have first class type");
4134 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
4135 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4136 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4138 return AteExtraComma ? InstExtraComma : InstNormal;
4142 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4144 /// ::= 'catch' TypeAndValue
4146 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4147 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
4148 Type *Ty = nullptr; LocTy TyLoc;
4149 Value *PersFn; LocTy PersFnLoc;
4151 if (ParseType(Ty, TyLoc) ||
4152 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4153 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4156 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4157 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4159 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4160 LandingPadInst::ClauseType CT;
4161 if (EatIfPresent(lltok::kw_catch))
4162 CT = LandingPadInst::Catch;
4163 else if (EatIfPresent(lltok::kw_filter))
4164 CT = LandingPadInst::Filter;
4166 return TokError("expected 'catch' or 'filter' clause type");
4170 if (ParseTypeAndValue(V, VLoc, PFS)) {
4175 // A 'catch' type expects a non-array constant. A filter clause expects an
4177 if (CT == LandingPadInst::Catch) {
4178 if (isa<ArrayType>(V->getType()))
4179 Error(VLoc, "'catch' clause has an invalid type");
4181 if (!isa<ArrayType>(V->getType()))
4182 Error(VLoc, "'filter' clause has an invalid type");
4185 LP->addClause(cast<Constant>(V));
4193 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4194 /// ParameterList OptionalAttrs
4195 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4196 /// ParameterList OptionalAttrs
4197 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4198 /// ParameterList OptionalAttrs
4199 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4200 CallInst::TailCallKind TCK) {
4201 AttrBuilder RetAttrs, FnAttrs;
4202 std::vector<unsigned> FwdRefAttrGrps;
4205 Type *RetType = nullptr;
4208 SmallVector<ParamInfo, 16> ArgList;
4209 LocTy CallLoc = Lex.getLoc();
4211 if ((TCK != CallInst::TCK_None &&
4212 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4213 ParseOptionalCallingConv(CC) ||
4214 ParseOptionalReturnAttrs(RetAttrs) ||
4215 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4216 ParseValID(CalleeID) ||
4217 ParseParameterList(ArgList, PFS) ||
4218 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4222 // If RetType is a non-function pointer type, then this is the short syntax
4223 // for the call, which means that RetType is just the return type. Infer the
4224 // rest of the function argument types from the arguments that are present.
4225 PointerType *PFTy = nullptr;
4226 FunctionType *Ty = nullptr;
4227 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4228 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4229 // Pull out the types of all of the arguments...
4230 std::vector<Type*> ParamTypes;
4231 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4232 ParamTypes.push_back(ArgList[i].V->getType());
4234 if (!FunctionType::isValidReturnType(RetType))
4235 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4237 Ty = FunctionType::get(RetType, ParamTypes, false);
4238 PFTy = PointerType::getUnqual(Ty);
4241 // Look up the callee.
4243 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4245 // Set up the Attribute for the function.
4246 SmallVector<AttributeSet, 8> Attrs;
4247 if (RetAttrs.hasAttributes())
4248 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4249 AttributeSet::ReturnIndex,
4252 SmallVector<Value*, 8> Args;
4254 // Loop through FunctionType's arguments and ensure they are specified
4255 // correctly. Also, gather any parameter attributes.
4256 FunctionType::param_iterator I = Ty->param_begin();
4257 FunctionType::param_iterator E = Ty->param_end();
4258 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4259 Type *ExpectedTy = nullptr;
4262 } else if (!Ty->isVarArg()) {
4263 return Error(ArgList[i].Loc, "too many arguments specified");
4266 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4267 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4268 getTypeString(ExpectedTy) + "'");
4269 Args.push_back(ArgList[i].V);
4270 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4271 AttrBuilder B(ArgList[i].Attrs, i + 1);
4272 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4277 return Error(CallLoc, "not enough parameters specified for call");
4279 if (FnAttrs.hasAttributes())
4280 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4281 AttributeSet::FunctionIndex,
4284 // Finish off the Attribute and check them
4285 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4287 CallInst *CI = CallInst::Create(Callee, Args);
4288 CI->setTailCallKind(TCK);
4289 CI->setCallingConv(CC);
4290 CI->setAttributes(PAL);
4291 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4296 //===----------------------------------------------------------------------===//
4297 // Memory Instructions.
4298 //===----------------------------------------------------------------------===//
4301 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4302 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4303 Value *Size = nullptr;
4305 unsigned Alignment = 0;
4308 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4310 if (ParseType(Ty)) return true;
4312 bool AteExtraComma = false;
4313 if (EatIfPresent(lltok::comma)) {
4314 if (Lex.getKind() == lltok::kw_align) {
4315 if (ParseOptionalAlignment(Alignment)) return true;
4316 } else if (Lex.getKind() == lltok::MetadataVar) {
4317 AteExtraComma = true;
4319 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4320 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4325 if (Size && !Size->getType()->isIntegerTy())
4326 return Error(SizeLoc, "element count must have integer type");
4328 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4329 AI->setUsedWithInAlloca(IsInAlloca);
4331 return AteExtraComma ? InstExtraComma : InstNormal;
4335 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4336 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4337 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4338 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4339 Value *Val; LocTy Loc;
4340 unsigned Alignment = 0;
4341 bool AteExtraComma = false;
4342 bool isAtomic = false;
4343 AtomicOrdering Ordering = NotAtomic;
4344 SynchronizationScope Scope = CrossThread;
4346 if (Lex.getKind() == lltok::kw_atomic) {
4351 bool isVolatile = false;
4352 if (Lex.getKind() == lltok::kw_volatile) {
4357 if (ParseTypeAndValue(Val, Loc, PFS) ||
4358 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4359 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4362 if (!Val->getType()->isPointerTy() ||
4363 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4364 return Error(Loc, "load operand must be a pointer to a first class type");
4365 if (isAtomic && !Alignment)
4366 return Error(Loc, "atomic load must have explicit non-zero alignment");
4367 if (Ordering == Release || Ordering == AcquireRelease)
4368 return Error(Loc, "atomic load cannot use Release ordering");
4370 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4371 return AteExtraComma ? InstExtraComma : InstNormal;
4376 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4377 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4378 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4379 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4380 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4381 unsigned Alignment = 0;
4382 bool AteExtraComma = false;
4383 bool isAtomic = false;
4384 AtomicOrdering Ordering = NotAtomic;
4385 SynchronizationScope Scope = CrossThread;
4387 if (Lex.getKind() == lltok::kw_atomic) {
4392 bool isVolatile = false;
4393 if (Lex.getKind() == lltok::kw_volatile) {
4398 if (ParseTypeAndValue(Val, Loc, PFS) ||
4399 ParseToken(lltok::comma, "expected ',' after store operand") ||
4400 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4401 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4402 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4405 if (!Ptr->getType()->isPointerTy())
4406 return Error(PtrLoc, "store operand must be a pointer");
4407 if (!Val->getType()->isFirstClassType())
4408 return Error(Loc, "store operand must be a first class value");
4409 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4410 return Error(Loc, "stored value and pointer type do not match");
4411 if (isAtomic && !Alignment)
4412 return Error(Loc, "atomic store must have explicit non-zero alignment");
4413 if (Ordering == Acquire || Ordering == AcquireRelease)
4414 return Error(Loc, "atomic store cannot use Acquire ordering");
4416 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4417 return AteExtraComma ? InstExtraComma : InstNormal;
4421 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4422 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
4423 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4424 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4425 bool AteExtraComma = false;
4426 AtomicOrdering SuccessOrdering = NotAtomic;
4427 AtomicOrdering FailureOrdering = NotAtomic;
4428 SynchronizationScope Scope = CrossThread;
4429 bool isVolatile = false;
4430 bool isWeak = false;
4432 if (EatIfPresent(lltok::kw_weak))
4435 if (EatIfPresent(lltok::kw_volatile))
4438 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4439 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4440 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4441 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4442 ParseTypeAndValue(New, NewLoc, PFS) ||
4443 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4444 ParseOrdering(FailureOrdering))
4447 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4448 return TokError("cmpxchg cannot be unordered");
4449 if (SuccessOrdering < FailureOrdering)
4450 return TokError("cmpxchg must be at least as ordered on success as failure");
4451 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4452 return TokError("cmpxchg failure ordering cannot include release semantics");
4453 if (!Ptr->getType()->isPointerTy())
4454 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4455 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4456 return Error(CmpLoc, "compare value and pointer type do not match");
4457 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4458 return Error(NewLoc, "new value and pointer type do not match");
4459 if (!New->getType()->isIntegerTy())
4460 return Error(NewLoc, "cmpxchg operand must be an integer");
4461 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4462 if (Size < 8 || (Size & (Size - 1)))
4463 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4466 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4467 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
4468 CXI->setVolatile(isVolatile);
4469 CXI->setWeak(isWeak);
4471 return AteExtraComma ? InstExtraComma : InstNormal;
4475 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4476 /// 'singlethread'? AtomicOrdering
4477 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4478 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4479 bool AteExtraComma = false;
4480 AtomicOrdering Ordering = NotAtomic;
4481 SynchronizationScope Scope = CrossThread;
4482 bool isVolatile = false;
4483 AtomicRMWInst::BinOp Operation;
4485 if (EatIfPresent(lltok::kw_volatile))
4488 switch (Lex.getKind()) {
4489 default: return TokError("expected binary operation in atomicrmw");
4490 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4491 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4492 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4493 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4494 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4495 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4496 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4497 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4498 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4499 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4500 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4502 Lex.Lex(); // Eat the operation.
4504 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4505 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4506 ParseTypeAndValue(Val, ValLoc, PFS) ||
4507 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4510 if (Ordering == Unordered)
4511 return TokError("atomicrmw cannot be unordered");
4512 if (!Ptr->getType()->isPointerTy())
4513 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4514 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4515 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4516 if (!Val->getType()->isIntegerTy())
4517 return Error(ValLoc, "atomicrmw operand must be an integer");
4518 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4519 if (Size < 8 || (Size & (Size - 1)))
4520 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4523 AtomicRMWInst *RMWI =
4524 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4525 RMWI->setVolatile(isVolatile);
4527 return AteExtraComma ? InstExtraComma : InstNormal;
4531 /// ::= 'fence' 'singlethread'? AtomicOrdering
4532 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4533 AtomicOrdering Ordering = NotAtomic;
4534 SynchronizationScope Scope = CrossThread;
4535 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4538 if (Ordering == Unordered)
4539 return TokError("fence cannot be unordered");
4540 if (Ordering == Monotonic)
4541 return TokError("fence cannot be monotonic");
4543 Inst = new FenceInst(Context, Ordering, Scope);
4547 /// ParseGetElementPtr
4548 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4549 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4550 Value *Ptr = nullptr;
4551 Value *Val = nullptr;
4554 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4556 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4558 Type *BaseType = Ptr->getType();
4559 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4560 if (!BasePointerType)
4561 return Error(Loc, "base of getelementptr must be a pointer");
4563 SmallVector<Value*, 16> Indices;
4564 bool AteExtraComma = false;
4565 while (EatIfPresent(lltok::comma)) {
4566 if (Lex.getKind() == lltok::MetadataVar) {
4567 AteExtraComma = true;
4570 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4571 if (!Val->getType()->getScalarType()->isIntegerTy())
4572 return Error(EltLoc, "getelementptr index must be an integer");
4573 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4574 return Error(EltLoc, "getelementptr index type missmatch");
4575 if (Val->getType()->isVectorTy()) {
4576 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4577 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4578 if (ValNumEl != PtrNumEl)
4579 return Error(EltLoc,
4580 "getelementptr vector index has a wrong number of elements");
4582 Indices.push_back(Val);
4585 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4586 return Error(Loc, "base element of getelementptr must be sized");
4588 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4589 return Error(Loc, "invalid getelementptr indices");
4590 Inst = GetElementPtrInst::Create(Ptr, Indices);
4592 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4593 return AteExtraComma ? InstExtraComma : InstNormal;
4596 /// ParseExtractValue
4597 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4598 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4599 Value *Val; LocTy Loc;
4600 SmallVector<unsigned, 4> Indices;
4602 if (ParseTypeAndValue(Val, Loc, PFS) ||
4603 ParseIndexList(Indices, AteExtraComma))
4606 if (!Val->getType()->isAggregateType())
4607 return Error(Loc, "extractvalue operand must be aggregate type");
4609 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4610 return Error(Loc, "invalid indices for extractvalue");
4611 Inst = ExtractValueInst::Create(Val, Indices);
4612 return AteExtraComma ? InstExtraComma : InstNormal;
4615 /// ParseInsertValue
4616 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4617 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4618 Value *Val0, *Val1; LocTy Loc0, Loc1;
4619 SmallVector<unsigned, 4> Indices;
4621 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4622 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4623 ParseTypeAndValue(Val1, Loc1, PFS) ||
4624 ParseIndexList(Indices, AteExtraComma))
4627 if (!Val0->getType()->isAggregateType())
4628 return Error(Loc0, "insertvalue operand must be aggregate type");
4630 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4631 return Error(Loc0, "invalid indices for insertvalue");
4632 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4633 return AteExtraComma ? InstExtraComma : InstNormal;
4636 //===----------------------------------------------------------------------===//
4637 // Embedded metadata.
4638 //===----------------------------------------------------------------------===//
4640 /// ParseMDNodeVector
4641 /// ::= Element (',' Element)*
4643 /// ::= 'null' | TypeAndValue
4644 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4645 PerFunctionState *PFS) {
4646 // Check for an empty list.
4647 if (Lex.getKind() == lltok::rbrace)
4651 // Null is a special case since it is typeless.
4652 if (EatIfPresent(lltok::kw_null)) {
4653 Elts.push_back(nullptr);
4658 if (ParseTypeAndValue(V, PFS)) return true;
4660 } while (EatIfPresent(lltok::comma));
4665 //===----------------------------------------------------------------------===//
4666 // Use-list order directives.
4667 //===----------------------------------------------------------------------===//
4668 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
4671 return Error(Loc, "value has no uses");
4673 unsigned NumUses = 0;
4674 SmallDenseMap<const Use *, unsigned, 16> Order;
4675 for (const Use &U : V->uses()) {
4676 if (++NumUses > Indexes.size())
4678 Order[&U] = Indexes[NumUses - 1];
4681 return Error(Loc, "value only has one use");
4682 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
4683 return Error(Loc, "wrong number of indexes, expected " +
4684 Twine(std::distance(V->use_begin(), V->use_end())));
4686 V->sortUseList([&](const Use &L, const Use &R) {
4687 return Order.lookup(&L) < Order.lookup(&R);
4692 /// ParseUseListOrderIndexes
4693 /// ::= '{' uint32 (',' uint32)+ '}'
4694 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
4695 SMLoc Loc = Lex.getLoc();
4696 if (ParseToken(lltok::lbrace, "expected '{' here"))
4698 if (Lex.getKind() == lltok::rbrace)
4699 return Lex.Error("expected non-empty list of uselistorder indexes");
4701 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
4702 // indexes should be distinct numbers in the range [0, size-1], and should
4704 unsigned Offset = 0;
4706 bool IsOrdered = true;
4707 assert(Indexes.empty() && "Expected empty order vector");
4710 if (ParseUInt32(Index))
4713 // Update consistency checks.
4714 Offset += Index - Indexes.size();
4715 Max = std::max(Max, Index);
4716 IsOrdered &= Index == Indexes.size();
4718 Indexes.push_back(Index);
4719 } while (EatIfPresent(lltok::comma));
4721 if (ParseToken(lltok::rbrace, "expected '}' here"))
4724 if (Indexes.size() < 2)
4725 return Error(Loc, "expected >= 2 uselistorder indexes");
4726 if (Offset != 0 || Max >= Indexes.size())
4727 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
4729 return Error(Loc, "expected uselistorder indexes to change the order");
4734 /// ParseUseListOrder
4735 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
4736 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
4737 SMLoc Loc = Lex.getLoc();
4738 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
4742 SmallVector<unsigned, 16> Indexes;
4743 if (ParseTypeAndValue(V, PFS) ||
4744 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
4745 ParseUseListOrderIndexes(Indexes))
4748 return sortUseListOrder(V, Indexes, Loc);
4751 /// ParseUseListOrderBB
4752 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
4753 bool LLParser::ParseUseListOrderBB() {
4754 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
4755 SMLoc Loc = Lex.getLoc();
4759 SmallVector<unsigned, 16> Indexes;
4760 if (ParseValID(Fn) ||
4761 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4762 ParseValID(Label) ||
4763 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4764 ParseUseListOrderIndexes(Indexes))
4767 // Check the function.
4769 if (Fn.Kind == ValID::t_GlobalName)
4770 GV = M->getNamedValue(Fn.StrVal);
4771 else if (Fn.Kind == ValID::t_GlobalID)
4772 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
4774 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4776 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
4777 auto *F = dyn_cast<Function>(GV);
4779 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4780 if (F->isDeclaration())
4781 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
4783 // Check the basic block.
4784 if (Label.Kind == ValID::t_LocalID)
4785 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
4786 if (Label.Kind != ValID::t_LocalName)
4787 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
4788 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
4790 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
4791 if (!isa<BasicBlock>(V))
4792 return Error(Label.Loc, "expected basic block in uselistorder_bb");
4794 return sortUseListOrder(V, Indexes, Loc);