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 assert(!NumberedMetadata[SlotNo]->isFunctionLocal() &&
66 "Unexpected function-local metadata");
67 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
70 ForwardRefInstMetadata.clear();
73 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
74 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
76 // Handle any function attribute group forward references.
77 for (std::map<Value*, std::vector<unsigned> >::iterator
78 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
81 std::vector<unsigned> &Vec = I->second;
84 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
86 B.merge(NumberedAttrBuilders[*VI]);
88 if (Function *Fn = dyn_cast<Function>(V)) {
89 AttributeSet AS = Fn->getAttributes();
90 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
91 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
92 AS.getFnAttributes());
96 // If the alignment was parsed as an attribute, move to the alignment
98 if (FnAttrs.hasAlignmentAttr()) {
99 Fn->setAlignment(FnAttrs.getAlignment());
100 FnAttrs.removeAttribute(Attribute::Alignment);
103 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
104 AttributeSet::get(Context,
105 AttributeSet::FunctionIndex,
107 Fn->setAttributes(AS);
108 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
109 AttributeSet AS = CI->getAttributes();
110 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
111 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
112 AS.getFnAttributes());
114 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
115 AttributeSet::get(Context,
116 AttributeSet::FunctionIndex,
118 CI->setAttributes(AS);
119 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
120 AttributeSet AS = II->getAttributes();
121 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
122 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
123 AS.getFnAttributes());
125 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
126 AttributeSet::get(Context,
127 AttributeSet::FunctionIndex,
129 II->setAttributes(AS);
131 llvm_unreachable("invalid object with forward attribute group reference");
135 // If there are entries in ForwardRefBlockAddresses at this point, the
136 // function was never defined.
137 if (!ForwardRefBlockAddresses.empty())
138 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
139 "expected function name in blockaddress");
141 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
142 if (NumberedTypes[i].second.isValid())
143 return Error(NumberedTypes[i].second,
144 "use of undefined type '%" + Twine(i) + "'");
146 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
147 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
148 if (I->second.second.isValid())
149 return Error(I->second.second,
150 "use of undefined type named '" + I->getKey() + "'");
152 if (!ForwardRefComdats.empty())
153 return Error(ForwardRefComdats.begin()->second,
154 "use of undefined comdat '$" +
155 ForwardRefComdats.begin()->first + "'");
157 if (!ForwardRefVals.empty())
158 return Error(ForwardRefVals.begin()->second.second,
159 "use of undefined value '@" + ForwardRefVals.begin()->first +
162 if (!ForwardRefValIDs.empty())
163 return Error(ForwardRefValIDs.begin()->second.second,
164 "use of undefined value '@" +
165 Twine(ForwardRefValIDs.begin()->first) + "'");
167 if (!ForwardRefMDNodes.empty())
168 return Error(ForwardRefMDNodes.begin()->second.second,
169 "use of undefined metadata '!" +
170 Twine(ForwardRefMDNodes.begin()->first) + "'");
173 // Look for intrinsic functions and CallInst that need to be upgraded
174 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
175 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
177 UpgradeDebugInfo(*M);
182 //===----------------------------------------------------------------------===//
183 // Top-Level Entities
184 //===----------------------------------------------------------------------===//
186 bool LLParser::ParseTopLevelEntities() {
188 switch (Lex.getKind()) {
189 default: return TokError("expected top-level entity");
190 case lltok::Eof: return false;
191 case lltok::kw_declare: if (ParseDeclare()) return true; break;
192 case lltok::kw_define: if (ParseDefine()) return true; break;
193 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
194 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
195 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
196 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
197 case lltok::LocalVar: if (ParseNamedType()) return true; break;
198 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
199 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
200 case lltok::ComdatVar: if (parseComdat()) return true; break;
201 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
202 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
204 // The Global variable production with no name can have many different
205 // optional leading prefixes, the production is:
206 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
207 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
208 // ('constant'|'global') ...
209 case lltok::kw_private: // OptionalLinkage
210 case lltok::kw_internal: // OptionalLinkage
211 case lltok::kw_weak: // OptionalLinkage
212 case lltok::kw_weak_odr: // OptionalLinkage
213 case lltok::kw_linkonce: // OptionalLinkage
214 case lltok::kw_linkonce_odr: // OptionalLinkage
215 case lltok::kw_appending: // OptionalLinkage
216 case lltok::kw_common: // OptionalLinkage
217 case lltok::kw_extern_weak: // OptionalLinkage
218 case lltok::kw_external: // OptionalLinkage
219 case lltok::kw_default: // OptionalVisibility
220 case lltok::kw_hidden: // OptionalVisibility
221 case lltok::kw_protected: // OptionalVisibility
222 case lltok::kw_dllimport: // OptionalDLLStorageClass
223 case lltok::kw_dllexport: // OptionalDLLStorageClass
224 case lltok::kw_thread_local: // OptionalThreadLocal
225 case lltok::kw_addrspace: // OptionalAddrSpace
226 case lltok::kw_constant: // GlobalType
227 case lltok::kw_global: { // GlobalType
228 unsigned Linkage, Visibility, DLLStorageClass;
230 GlobalVariable::ThreadLocalMode TLM;
232 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
233 ParseOptionalVisibility(Visibility) ||
234 ParseOptionalDLLStorageClass(DLLStorageClass) ||
235 ParseOptionalThreadLocal(TLM) ||
236 parseOptionalUnnamedAddr(UnnamedAddr) ||
237 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
238 DLLStorageClass, TLM, UnnamedAddr))
243 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
244 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
245 case lltok::kw_uselistorder_bb:
246 if (ParseUseListOrderBB()) return true; break;
253 /// ::= 'module' 'asm' STRINGCONSTANT
254 bool LLParser::ParseModuleAsm() {
255 assert(Lex.getKind() == lltok::kw_module);
259 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
260 ParseStringConstant(AsmStr)) return true;
262 M->appendModuleInlineAsm(AsmStr);
267 /// ::= 'target' 'triple' '=' STRINGCONSTANT
268 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
269 bool LLParser::ParseTargetDefinition() {
270 assert(Lex.getKind() == lltok::kw_target);
273 default: return TokError("unknown target property");
274 case lltok::kw_triple:
276 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
277 ParseStringConstant(Str))
279 M->setTargetTriple(Str);
281 case lltok::kw_datalayout:
283 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
284 ParseStringConstant(Str))
286 M->setDataLayout(Str);
292 /// ::= 'deplibs' '=' '[' ']'
293 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
294 /// FIXME: Remove in 4.0. Currently parse, but ignore.
295 bool LLParser::ParseDepLibs() {
296 assert(Lex.getKind() == lltok::kw_deplibs);
298 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
299 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
302 if (EatIfPresent(lltok::rsquare))
307 if (ParseStringConstant(Str)) return true;
308 } while (EatIfPresent(lltok::comma));
310 return ParseToken(lltok::rsquare, "expected ']' at end of list");
313 /// ParseUnnamedType:
314 /// ::= LocalVarID '=' 'type' type
315 bool LLParser::ParseUnnamedType() {
316 LocTy TypeLoc = Lex.getLoc();
317 unsigned TypeID = Lex.getUIntVal();
318 Lex.Lex(); // eat LocalVarID;
320 if (ParseToken(lltok::equal, "expected '=' after name") ||
321 ParseToken(lltok::kw_type, "expected 'type' after '='"))
324 if (TypeID >= NumberedTypes.size())
325 NumberedTypes.resize(TypeID+1);
327 Type *Result = nullptr;
328 if (ParseStructDefinition(TypeLoc, "",
329 NumberedTypes[TypeID], Result)) return true;
331 if (!isa<StructType>(Result)) {
332 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
334 return Error(TypeLoc, "non-struct types may not be recursive");
335 Entry.first = Result;
336 Entry.second = SMLoc();
344 /// ::= LocalVar '=' 'type' type
345 bool LLParser::ParseNamedType() {
346 std::string Name = Lex.getStrVal();
347 LocTy NameLoc = Lex.getLoc();
348 Lex.Lex(); // eat LocalVar.
350 if (ParseToken(lltok::equal, "expected '=' after name") ||
351 ParseToken(lltok::kw_type, "expected 'type' after name"))
354 Type *Result = nullptr;
355 if (ParseStructDefinition(NameLoc, Name,
356 NamedTypes[Name], Result)) return true;
358 if (!isa<StructType>(Result)) {
359 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
361 return Error(NameLoc, "non-struct types may not be recursive");
362 Entry.first = Result;
363 Entry.second = SMLoc();
371 /// ::= 'declare' FunctionHeader
372 bool LLParser::ParseDeclare() {
373 assert(Lex.getKind() == lltok::kw_declare);
377 return ParseFunctionHeader(F, false);
381 /// ::= 'define' FunctionHeader '{' ...
382 bool LLParser::ParseDefine() {
383 assert(Lex.getKind() == lltok::kw_define);
387 return ParseFunctionHeader(F, true) ||
388 ParseFunctionBody(*F);
394 bool LLParser::ParseGlobalType(bool &IsConstant) {
395 if (Lex.getKind() == lltok::kw_constant)
397 else if (Lex.getKind() == lltok::kw_global)
401 return TokError("expected 'global' or 'constant'");
407 /// ParseUnnamedGlobal:
408 /// OptionalVisibility ALIAS ...
409 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
410 /// ... -> global variable
411 /// GlobalID '=' OptionalVisibility ALIAS ...
412 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
413 /// ... -> global variable
414 bool LLParser::ParseUnnamedGlobal() {
415 unsigned VarID = NumberedVals.size();
417 LocTy NameLoc = Lex.getLoc();
419 // Handle the GlobalID form.
420 if (Lex.getKind() == lltok::GlobalID) {
421 if (Lex.getUIntVal() != VarID)
422 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
424 Lex.Lex(); // eat GlobalID;
426 if (ParseToken(lltok::equal, "expected '=' after name"))
431 unsigned Linkage, Visibility, DLLStorageClass;
432 GlobalVariable::ThreadLocalMode TLM;
434 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
435 ParseOptionalVisibility(Visibility) ||
436 ParseOptionalDLLStorageClass(DLLStorageClass) ||
437 ParseOptionalThreadLocal(TLM) ||
438 parseOptionalUnnamedAddr(UnnamedAddr))
441 if (Lex.getKind() != lltok::kw_alias)
442 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
443 DLLStorageClass, TLM, UnnamedAddr);
444 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
448 /// ParseNamedGlobal:
449 /// GlobalVar '=' OptionalVisibility ALIAS ...
450 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
451 /// ... -> global variable
452 bool LLParser::ParseNamedGlobal() {
453 assert(Lex.getKind() == lltok::GlobalVar);
454 LocTy NameLoc = Lex.getLoc();
455 std::string Name = Lex.getStrVal();
459 unsigned Linkage, Visibility, DLLStorageClass;
460 GlobalVariable::ThreadLocalMode TLM;
462 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
463 ParseOptionalLinkage(Linkage, HasLinkage) ||
464 ParseOptionalVisibility(Visibility) ||
465 ParseOptionalDLLStorageClass(DLLStorageClass) ||
466 ParseOptionalThreadLocal(TLM) ||
467 parseOptionalUnnamedAddr(UnnamedAddr))
470 if (Lex.getKind() != lltok::kw_alias)
471 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
472 DLLStorageClass, TLM, UnnamedAddr);
474 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
478 bool LLParser::parseComdat() {
479 assert(Lex.getKind() == lltok::ComdatVar);
480 std::string Name = Lex.getStrVal();
481 LocTy NameLoc = Lex.getLoc();
484 if (ParseToken(lltok::equal, "expected '=' here"))
487 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
488 return TokError("expected comdat type");
490 Comdat::SelectionKind SK;
491 switch (Lex.getKind()) {
493 return TokError("unknown selection kind");
497 case lltok::kw_exactmatch:
498 SK = Comdat::ExactMatch;
500 case lltok::kw_largest:
501 SK = Comdat::Largest;
503 case lltok::kw_noduplicates:
504 SK = Comdat::NoDuplicates;
506 case lltok::kw_samesize:
507 SK = Comdat::SameSize;
512 // See if the comdat was forward referenced, if so, use the comdat.
513 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
514 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
515 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
516 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
519 if (I != ComdatSymTab.end())
522 C = M->getOrInsertComdat(Name);
523 C->setSelectionKind(SK);
529 // ::= '!' STRINGCONSTANT
530 bool LLParser::ParseMDString(MDString *&Result) {
532 if (ParseStringConstant(Str)) return true;
533 llvm::UpgradeMDStringConstant(Str);
534 Result = MDString::get(Context, Str);
539 // ::= '!' MDNodeNumber
541 /// This version of ParseMDNodeID returns the slot number and null in the case
542 /// of a forward reference.
543 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
544 // !{ ..., !42, ... }
545 if (ParseUInt32(SlotNo)) return true;
547 // Check existing MDNode.
548 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
549 Result = NumberedMetadata[SlotNo];
555 bool LLParser::ParseMDNodeID(MDNode *&Result) {
556 // !{ ..., !42, ... }
558 if (ParseMDNodeID(Result, MID)) return true;
560 // If not a forward reference, just return it now.
561 if (Result) return false;
563 // Otherwise, create MDNode forward reference.
564 MDNode *FwdNode = MDNode::getTemporary(Context, None);
565 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
567 if (NumberedMetadata.size() <= MID)
568 NumberedMetadata.resize(MID+1);
569 NumberedMetadata[MID] = FwdNode;
574 /// ParseNamedMetadata:
575 /// !foo = !{ !1, !2 }
576 bool LLParser::ParseNamedMetadata() {
577 assert(Lex.getKind() == lltok::MetadataVar);
578 std::string Name = Lex.getStrVal();
581 if (ParseToken(lltok::equal, "expected '=' here") ||
582 ParseToken(lltok::exclaim, "Expected '!' here") ||
583 ParseToken(lltok::lbrace, "Expected '{' here"))
586 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
587 if (Lex.getKind() != lltok::rbrace)
589 if (ParseToken(lltok::exclaim, "Expected '!' here"))
593 if (ParseMDNodeID(N)) return true;
595 } while (EatIfPresent(lltok::comma));
597 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
603 /// ParseStandaloneMetadata:
605 bool LLParser::ParseStandaloneMetadata() {
606 assert(Lex.getKind() == lltok::exclaim);
608 unsigned MetadataID = 0;
612 SmallVector<Value *, 16> Elts;
613 if (ParseUInt32(MetadataID) ||
614 ParseToken(lltok::equal, "expected '=' here") ||
615 ParseType(Ty, TyLoc) ||
616 ParseToken(lltok::exclaim, "Expected '!' here") ||
617 ParseToken(lltok::lbrace, "Expected '{' here") ||
618 ParseMDNodeVector(Elts, nullptr) ||
619 ParseToken(lltok::rbrace, "expected end of metadata node"))
622 MDNode *Init = MDNode::get(Context, Elts);
624 // See if this was forward referenced, if so, handle it.
625 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
626 FI = ForwardRefMDNodes.find(MetadataID);
627 if (FI != ForwardRefMDNodes.end()) {
628 MDNode *Temp = FI->second.first;
629 Temp->replaceAllUsesWith(Init);
630 MDNode::deleteTemporary(Temp);
631 ForwardRefMDNodes.erase(FI);
633 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
635 if (MetadataID >= NumberedMetadata.size())
636 NumberedMetadata.resize(MetadataID+1);
638 if (NumberedMetadata[MetadataID] != nullptr)
639 return TokError("Metadata id is already used");
640 NumberedMetadata[MetadataID] = Init;
646 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
647 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
648 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
652 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
653 /// OptionalDLLStorageClass OptionalThreadLocal
654 /// OptionalUnNammedAddr 'alias' Aliasee
659 /// Everything through OptionalUnNammedAddr has already been parsed.
661 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
662 unsigned Visibility, unsigned DLLStorageClass,
663 GlobalVariable::ThreadLocalMode TLM,
665 assert(Lex.getKind() == lltok::kw_alias);
668 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
670 if(!GlobalAlias::isValidLinkage(Linkage))
671 return Error(NameLoc, "invalid linkage type for alias");
673 if (!isValidVisibilityForLinkage(Visibility, L))
674 return Error(NameLoc,
675 "symbol with local linkage must have default visibility");
678 LocTy AliaseeLoc = Lex.getLoc();
679 if (Lex.getKind() != lltok::kw_bitcast &&
680 Lex.getKind() != lltok::kw_getelementptr &&
681 Lex.getKind() != lltok::kw_addrspacecast &&
682 Lex.getKind() != lltok::kw_inttoptr) {
683 if (ParseGlobalTypeAndValue(Aliasee))
686 // The bitcast dest type is not present, it is implied by the dest type.
690 if (ID.Kind != ValID::t_Constant)
691 return Error(AliaseeLoc, "invalid aliasee");
692 Aliasee = ID.ConstantVal;
695 Type *AliaseeType = Aliasee->getType();
696 auto *PTy = dyn_cast<PointerType>(AliaseeType);
698 return Error(AliaseeLoc, "An alias must have pointer type");
699 Type *Ty = PTy->getElementType();
700 unsigned AddrSpace = PTy->getAddressSpace();
702 // Okay, create the alias but do not insert it into the module yet.
703 std::unique_ptr<GlobalAlias> GA(
704 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
705 Name, Aliasee, /*Parent*/ nullptr));
706 GA->setThreadLocalMode(TLM);
707 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
708 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
709 GA->setUnnamedAddr(UnnamedAddr);
711 // See if this value already exists in the symbol table. If so, it is either
712 // a redefinition or a definition of a forward reference.
713 if (GlobalValue *Val = M->getNamedValue(Name)) {
714 // See if this was a redefinition. If so, there is no entry in
716 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
717 I = ForwardRefVals.find(Name);
718 if (I == ForwardRefVals.end())
719 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
721 // Otherwise, this was a definition of forward ref. Verify that types
723 if (Val->getType() != GA->getType())
724 return Error(NameLoc,
725 "forward reference and definition of alias have different types");
727 // If they agree, just RAUW the old value with the alias and remove the
729 Val->replaceAllUsesWith(GA.get());
730 Val->eraseFromParent();
731 ForwardRefVals.erase(I);
734 // Insert into the module, we know its name won't collide now.
735 M->getAliasList().push_back(GA.get());
736 assert(GA->getName() == Name && "Should not be a name conflict!");
738 // The module owns this now
745 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
746 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
747 /// OptionalExternallyInitialized GlobalType Type Const
748 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
749 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
750 /// OptionalExternallyInitialized GlobalType Type Const
752 /// Everything up to and including OptionalUnNammedAddr has been parsed
755 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
756 unsigned Linkage, bool HasLinkage,
757 unsigned Visibility, unsigned DLLStorageClass,
758 GlobalVariable::ThreadLocalMode TLM,
760 if (!isValidVisibilityForLinkage(Visibility, Linkage))
761 return Error(NameLoc,
762 "symbol with local linkage must have default visibility");
765 bool IsConstant, IsExternallyInitialized;
766 LocTy IsExternallyInitializedLoc;
770 if (ParseOptionalAddrSpace(AddrSpace) ||
771 ParseOptionalToken(lltok::kw_externally_initialized,
772 IsExternallyInitialized,
773 &IsExternallyInitializedLoc) ||
774 ParseGlobalType(IsConstant) ||
775 ParseType(Ty, TyLoc))
778 // If the linkage is specified and is external, then no initializer is
780 Constant *Init = nullptr;
781 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
782 Linkage != GlobalValue::ExternalLinkage)) {
783 if (ParseGlobalValue(Ty, Init))
787 if (Ty->isFunctionTy() || Ty->isLabelTy())
788 return Error(TyLoc, "invalid type for global variable");
790 GlobalValue *GVal = nullptr;
792 // See if the global was forward referenced, if so, use the global.
794 GVal = M->getNamedValue(Name);
796 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
797 return Error(NameLoc, "redefinition of global '@" + Name + "'");
800 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
801 I = ForwardRefValIDs.find(NumberedVals.size());
802 if (I != ForwardRefValIDs.end()) {
803 GVal = I->second.first;
804 ForwardRefValIDs.erase(I);
810 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
811 Name, nullptr, GlobalVariable::NotThreadLocal,
814 if (GVal->getType()->getElementType() != Ty)
816 "forward reference and definition of global have different types");
818 GV = cast<GlobalVariable>(GVal);
820 // Move the forward-reference to the correct spot in the module.
821 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
825 NumberedVals.push_back(GV);
827 // Set the parsed properties on the global.
829 GV->setInitializer(Init);
830 GV->setConstant(IsConstant);
831 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
832 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
833 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
834 GV->setExternallyInitialized(IsExternallyInitialized);
835 GV->setThreadLocalMode(TLM);
836 GV->setUnnamedAddr(UnnamedAddr);
838 // Parse attributes on the global.
839 while (Lex.getKind() == lltok::comma) {
842 if (Lex.getKind() == lltok::kw_section) {
844 GV->setSection(Lex.getStrVal());
845 if (ParseToken(lltok::StringConstant, "expected global section string"))
847 } else if (Lex.getKind() == lltok::kw_align) {
849 if (ParseOptionalAlignment(Alignment)) return true;
850 GV->setAlignment(Alignment);
853 if (parseOptionalComdat(C))
858 return TokError("unknown global variable property!");
865 /// ParseUnnamedAttrGrp
866 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
867 bool LLParser::ParseUnnamedAttrGrp() {
868 assert(Lex.getKind() == lltok::kw_attributes);
869 LocTy AttrGrpLoc = Lex.getLoc();
872 assert(Lex.getKind() == lltok::AttrGrpID);
873 unsigned VarID = Lex.getUIntVal();
874 std::vector<unsigned> unused;
878 if (ParseToken(lltok::equal, "expected '=' here") ||
879 ParseToken(lltok::lbrace, "expected '{' here") ||
880 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
882 ParseToken(lltok::rbrace, "expected end of attribute group"))
885 if (!NumberedAttrBuilders[VarID].hasAttributes())
886 return Error(AttrGrpLoc, "attribute group has no attributes");
891 /// ParseFnAttributeValuePairs
892 /// ::= <attr> | <attr> '=' <value>
893 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
894 std::vector<unsigned> &FwdRefAttrGrps,
895 bool inAttrGrp, LocTy &BuiltinLoc) {
896 bool HaveError = false;
901 lltok::Kind Token = Lex.getKind();
902 if (Token == lltok::kw_builtin)
903 BuiltinLoc = Lex.getLoc();
906 if (!inAttrGrp) return HaveError;
907 return Error(Lex.getLoc(), "unterminated attribute group");
912 case lltok::AttrGrpID: {
913 // Allow a function to reference an attribute group:
915 // define void @foo() #1 { ... }
919 "cannot have an attribute group reference in an attribute group");
921 unsigned AttrGrpNum = Lex.getUIntVal();
922 if (inAttrGrp) break;
924 // Save the reference to the attribute group. We'll fill it in later.
925 FwdRefAttrGrps.push_back(AttrGrpNum);
928 // Target-dependent attributes:
929 case lltok::StringConstant: {
930 std::string Attr = Lex.getStrVal();
933 if (EatIfPresent(lltok::equal) &&
934 ParseStringConstant(Val))
937 B.addAttribute(Attr, Val);
941 // Target-independent attributes:
942 case lltok::kw_align: {
943 // As a hack, we allow function alignment to be initially parsed as an
944 // attribute on a function declaration/definition or added to an attribute
945 // group and later moved to the alignment field.
949 if (ParseToken(lltok::equal, "expected '=' here") ||
950 ParseUInt32(Alignment))
953 if (ParseOptionalAlignment(Alignment))
956 B.addAlignmentAttr(Alignment);
959 case lltok::kw_alignstack: {
963 if (ParseToken(lltok::equal, "expected '=' here") ||
964 ParseUInt32(Alignment))
967 if (ParseOptionalStackAlignment(Alignment))
970 B.addStackAlignmentAttr(Alignment);
973 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
974 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
975 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
976 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
977 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
978 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
979 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
980 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
981 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
982 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
983 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
984 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
985 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
986 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
987 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
988 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
989 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
990 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
991 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
992 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
993 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
994 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
995 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
996 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
997 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
998 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
999 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1002 case lltok::kw_inreg:
1003 case lltok::kw_signext:
1004 case lltok::kw_zeroext:
1007 "invalid use of attribute on a function");
1009 case lltok::kw_byval:
1010 case lltok::kw_dereferenceable:
1011 case lltok::kw_inalloca:
1012 case lltok::kw_nest:
1013 case lltok::kw_noalias:
1014 case lltok::kw_nocapture:
1015 case lltok::kw_nonnull:
1016 case lltok::kw_returned:
1017 case lltok::kw_sret:
1020 "invalid use of parameter-only attribute on a function");
1028 //===----------------------------------------------------------------------===//
1029 // GlobalValue Reference/Resolution Routines.
1030 //===----------------------------------------------------------------------===//
1032 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1033 /// forward reference record if needed. This can return null if the value
1034 /// exists but does not have the right type.
1035 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1037 PointerType *PTy = dyn_cast<PointerType>(Ty);
1039 Error(Loc, "global variable reference must have pointer type");
1043 // Look this name up in the normal function symbol table.
1045 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1047 // If this is a forward reference for the value, see if we already created a
1048 // forward ref record.
1050 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1051 I = ForwardRefVals.find(Name);
1052 if (I != ForwardRefVals.end())
1053 Val = I->second.first;
1056 // If we have the value in the symbol table or fwd-ref table, return it.
1058 if (Val->getType() == Ty) return Val;
1059 Error(Loc, "'@" + Name + "' defined with type '" +
1060 getTypeString(Val->getType()) + "'");
1064 // Otherwise, create a new forward reference for this value and remember it.
1065 GlobalValue *FwdVal;
1066 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1067 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1069 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1070 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1071 nullptr, GlobalVariable::NotThreadLocal,
1072 PTy->getAddressSpace());
1074 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1078 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1079 PointerType *PTy = dyn_cast<PointerType>(Ty);
1081 Error(Loc, "global variable reference must have pointer type");
1085 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1087 // If this is a forward reference for the value, see if we already created a
1088 // forward ref record.
1090 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1091 I = ForwardRefValIDs.find(ID);
1092 if (I != ForwardRefValIDs.end())
1093 Val = I->second.first;
1096 // If we have the value in the symbol table or fwd-ref table, return it.
1098 if (Val->getType() == Ty) return Val;
1099 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1100 getTypeString(Val->getType()) + "'");
1104 // Otherwise, create a new forward reference for this value and remember it.
1105 GlobalValue *FwdVal;
1106 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1107 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1109 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1110 GlobalValue::ExternalWeakLinkage, nullptr, "");
1112 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1117 //===----------------------------------------------------------------------===//
1118 // Comdat Reference/Resolution Routines.
1119 //===----------------------------------------------------------------------===//
1121 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1122 // Look this name up in the comdat symbol table.
1123 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1124 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1125 if (I != ComdatSymTab.end())
1128 // Otherwise, create a new forward reference for this value and remember it.
1129 Comdat *C = M->getOrInsertComdat(Name);
1130 ForwardRefComdats[Name] = Loc;
1135 //===----------------------------------------------------------------------===//
1137 //===----------------------------------------------------------------------===//
1139 /// ParseToken - If the current token has the specified kind, eat it and return
1140 /// success. Otherwise, emit the specified error and return failure.
1141 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1142 if (Lex.getKind() != T)
1143 return TokError(ErrMsg);
1148 /// ParseStringConstant
1149 /// ::= StringConstant
1150 bool LLParser::ParseStringConstant(std::string &Result) {
1151 if (Lex.getKind() != lltok::StringConstant)
1152 return TokError("expected string constant");
1153 Result = Lex.getStrVal();
1160 bool LLParser::ParseUInt32(unsigned &Val) {
1161 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1162 return TokError("expected integer");
1163 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1164 if (Val64 != unsigned(Val64))
1165 return TokError("expected 32-bit integer (too large)");
1173 bool LLParser::ParseUInt64(uint64_t &Val) {
1174 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1175 return TokError("expected integer");
1176 Val = Lex.getAPSIntVal().getLimitedValue();
1182 /// := 'localdynamic'
1183 /// := 'initialexec'
1185 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1186 switch (Lex.getKind()) {
1188 return TokError("expected localdynamic, initialexec or localexec");
1189 case lltok::kw_localdynamic:
1190 TLM = GlobalVariable::LocalDynamicTLSModel;
1192 case lltok::kw_initialexec:
1193 TLM = GlobalVariable::InitialExecTLSModel;
1195 case lltok::kw_localexec:
1196 TLM = GlobalVariable::LocalExecTLSModel;
1204 /// ParseOptionalThreadLocal
1206 /// := 'thread_local'
1207 /// := 'thread_local' '(' tlsmodel ')'
1208 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1209 TLM = GlobalVariable::NotThreadLocal;
1210 if (!EatIfPresent(lltok::kw_thread_local))
1213 TLM = GlobalVariable::GeneralDynamicTLSModel;
1214 if (Lex.getKind() == lltok::lparen) {
1216 return ParseTLSModel(TLM) ||
1217 ParseToken(lltok::rparen, "expected ')' after thread local model");
1222 /// ParseOptionalAddrSpace
1224 /// := 'addrspace' '(' uint32 ')'
1225 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1227 if (!EatIfPresent(lltok::kw_addrspace))
1229 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1230 ParseUInt32(AddrSpace) ||
1231 ParseToken(lltok::rparen, "expected ')' in address space");
1234 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1235 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1236 bool HaveError = false;
1241 lltok::Kind Token = Lex.getKind();
1243 default: // End of attributes.
1245 case lltok::kw_align: {
1247 if (ParseOptionalAlignment(Alignment))
1249 B.addAlignmentAttr(Alignment);
1252 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1253 case lltok::kw_dereferenceable: {
1255 if (ParseOptionalDereferenceableBytes(Bytes))
1257 B.addDereferenceableAttr(Bytes);
1260 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1261 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1262 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1263 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1264 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1265 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1266 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1267 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1268 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1269 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1270 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1271 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1273 case lltok::kw_alignstack:
1274 case lltok::kw_alwaysinline:
1275 case lltok::kw_builtin:
1276 case lltok::kw_inlinehint:
1277 case lltok::kw_jumptable:
1278 case lltok::kw_minsize:
1279 case lltok::kw_naked:
1280 case lltok::kw_nobuiltin:
1281 case lltok::kw_noduplicate:
1282 case lltok::kw_noimplicitfloat:
1283 case lltok::kw_noinline:
1284 case lltok::kw_nonlazybind:
1285 case lltok::kw_noredzone:
1286 case lltok::kw_noreturn:
1287 case lltok::kw_nounwind:
1288 case lltok::kw_optnone:
1289 case lltok::kw_optsize:
1290 case lltok::kw_returns_twice:
1291 case lltok::kw_sanitize_address:
1292 case lltok::kw_sanitize_memory:
1293 case lltok::kw_sanitize_thread:
1295 case lltok::kw_sspreq:
1296 case lltok::kw_sspstrong:
1297 case lltok::kw_uwtable:
1298 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1306 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1307 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1308 bool HaveError = false;
1313 lltok::Kind Token = Lex.getKind();
1315 default: // End of attributes.
1317 case lltok::kw_dereferenceable: {
1319 if (ParseOptionalDereferenceableBytes(Bytes))
1321 B.addDereferenceableAttr(Bytes);
1324 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1325 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1326 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1327 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1328 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1331 case lltok::kw_align:
1332 case lltok::kw_byval:
1333 case lltok::kw_inalloca:
1334 case lltok::kw_nest:
1335 case lltok::kw_nocapture:
1336 case lltok::kw_returned:
1337 case lltok::kw_sret:
1338 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1341 case lltok::kw_alignstack:
1342 case lltok::kw_alwaysinline:
1343 case lltok::kw_builtin:
1344 case lltok::kw_cold:
1345 case lltok::kw_inlinehint:
1346 case lltok::kw_jumptable:
1347 case lltok::kw_minsize:
1348 case lltok::kw_naked:
1349 case lltok::kw_nobuiltin:
1350 case lltok::kw_noduplicate:
1351 case lltok::kw_noimplicitfloat:
1352 case lltok::kw_noinline:
1353 case lltok::kw_nonlazybind:
1354 case lltok::kw_noredzone:
1355 case lltok::kw_noreturn:
1356 case lltok::kw_nounwind:
1357 case lltok::kw_optnone:
1358 case lltok::kw_optsize:
1359 case lltok::kw_returns_twice:
1360 case lltok::kw_sanitize_address:
1361 case lltok::kw_sanitize_memory:
1362 case lltok::kw_sanitize_thread:
1364 case lltok::kw_sspreq:
1365 case lltok::kw_sspstrong:
1366 case lltok::kw_uwtable:
1367 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1370 case lltok::kw_readnone:
1371 case lltok::kw_readonly:
1372 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1379 /// ParseOptionalLinkage
1386 /// ::= 'linkonce_odr'
1387 /// ::= 'available_externally'
1390 /// ::= 'extern_weak'
1392 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1394 switch (Lex.getKind()) {
1395 default: Res=GlobalValue::ExternalLinkage; return false;
1396 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1397 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1398 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1399 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1400 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1401 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1402 case lltok::kw_available_externally:
1403 Res = GlobalValue::AvailableExternallyLinkage;
1405 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1406 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1407 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1408 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1415 /// ParseOptionalVisibility
1421 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1422 switch (Lex.getKind()) {
1423 default: Res = GlobalValue::DefaultVisibility; return false;
1424 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1425 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1426 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1432 /// ParseOptionalDLLStorageClass
1437 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1438 switch (Lex.getKind()) {
1439 default: Res = GlobalValue::DefaultStorageClass; return false;
1440 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1441 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1447 /// ParseOptionalCallingConv
1451 /// ::= 'intel_ocl_bicc'
1453 /// ::= 'x86_stdcallcc'
1454 /// ::= 'x86_fastcallcc'
1455 /// ::= 'x86_thiscallcc'
1456 /// ::= 'x86_vectorcallcc'
1457 /// ::= 'arm_apcscc'
1458 /// ::= 'arm_aapcscc'
1459 /// ::= 'arm_aapcs_vfpcc'
1460 /// ::= 'msp430_intrcc'
1461 /// ::= 'ptx_kernel'
1462 /// ::= 'ptx_device'
1464 /// ::= 'spir_kernel'
1465 /// ::= 'x86_64_sysvcc'
1466 /// ::= 'x86_64_win64cc'
1467 /// ::= 'webkit_jscc'
1469 /// ::= 'preserve_mostcc'
1470 /// ::= 'preserve_allcc'
1474 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1475 switch (Lex.getKind()) {
1476 default: CC = CallingConv::C; return false;
1477 case lltok::kw_ccc: CC = CallingConv::C; break;
1478 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1479 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1480 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1481 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1482 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1483 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1484 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1485 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1486 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1487 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1488 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1489 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1490 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1491 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1492 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1493 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1494 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1495 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1496 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1497 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1498 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1499 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1500 case lltok::kw_cc: {
1502 return ParseUInt32(CC);
1510 /// ParseInstructionMetadata
1511 /// ::= !dbg !42 (',' !dbg !57)*
1512 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1513 PerFunctionState *PFS) {
1515 if (Lex.getKind() != lltok::MetadataVar)
1516 return TokError("expected metadata after comma");
1518 std::string Name = Lex.getStrVal();
1519 unsigned MDK = M->getMDKindID(Name);
1523 SMLoc Loc = Lex.getLoc();
1525 if (ParseToken(lltok::exclaim, "expected '!' here"))
1528 // This code is similar to that of ParseMetadataValue, however it needs to
1529 // have special-case code for a forward reference; see the comments on
1530 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1531 // at the top level here.
1532 if (Lex.getKind() == lltok::lbrace) {
1534 if (ParseMetadataListValue(ID, PFS))
1536 assert(ID.Kind == ValID::t_MDNode);
1537 if (ID.MDNodeVal->isFunctionLocal())
1538 return Error(Loc, "unexpected function-local metadata");
1539 Inst->setMetadata(MDK, ID.MDNodeVal);
1541 unsigned NodeID = 0;
1542 if (ParseMDNodeID(Node, NodeID))
1545 // If we got the node, add it to the instruction.
1546 Inst->setMetadata(MDK, Node);
1548 MDRef R = { Loc, MDK, NodeID };
1549 // Otherwise, remember that this should be resolved later.
1550 ForwardRefInstMetadata[Inst].push_back(R);
1554 if (MDK == LLVMContext::MD_tbaa)
1555 InstsWithTBAATag.push_back(Inst);
1557 // If this is the end of the list, we're done.
1558 } while (EatIfPresent(lltok::comma));
1562 /// ParseOptionalAlignment
1565 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1567 if (!EatIfPresent(lltok::kw_align))
1569 LocTy AlignLoc = Lex.getLoc();
1570 if (ParseUInt32(Alignment)) return true;
1571 if (!isPowerOf2_32(Alignment))
1572 return Error(AlignLoc, "alignment is not a power of two");
1573 if (Alignment > Value::MaximumAlignment)
1574 return Error(AlignLoc, "huge alignments are not supported yet");
1578 /// ParseOptionalDereferenceableBytes
1580 /// ::= 'dereferenceable' '(' 4 ')'
1581 bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1583 if (!EatIfPresent(lltok::kw_dereferenceable))
1585 LocTy ParenLoc = Lex.getLoc();
1586 if (!EatIfPresent(lltok::lparen))
1587 return Error(ParenLoc, "expected '('");
1588 LocTy DerefLoc = Lex.getLoc();
1589 if (ParseUInt64(Bytes)) return true;
1590 ParenLoc = Lex.getLoc();
1591 if (!EatIfPresent(lltok::rparen))
1592 return Error(ParenLoc, "expected ')'");
1594 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1598 /// ParseOptionalCommaAlign
1602 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1604 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1605 bool &AteExtraComma) {
1606 AteExtraComma = false;
1607 while (EatIfPresent(lltok::comma)) {
1608 // Metadata at the end is an early exit.
1609 if (Lex.getKind() == lltok::MetadataVar) {
1610 AteExtraComma = true;
1614 if (Lex.getKind() != lltok::kw_align)
1615 return Error(Lex.getLoc(), "expected metadata or 'align'");
1617 if (ParseOptionalAlignment(Alignment)) return true;
1623 /// ParseScopeAndOrdering
1624 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1627 /// This sets Scope and Ordering to the parsed values.
1628 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1629 AtomicOrdering &Ordering) {
1633 Scope = CrossThread;
1634 if (EatIfPresent(lltok::kw_singlethread))
1635 Scope = SingleThread;
1637 return ParseOrdering(Ordering);
1641 /// ::= AtomicOrdering
1643 /// This sets Ordering to the parsed value.
1644 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1645 switch (Lex.getKind()) {
1646 default: return TokError("Expected ordering on atomic instruction");
1647 case lltok::kw_unordered: Ordering = Unordered; break;
1648 case lltok::kw_monotonic: Ordering = Monotonic; break;
1649 case lltok::kw_acquire: Ordering = Acquire; break;
1650 case lltok::kw_release: Ordering = Release; break;
1651 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1652 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1658 /// ParseOptionalStackAlignment
1660 /// ::= 'alignstack' '(' 4 ')'
1661 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1663 if (!EatIfPresent(lltok::kw_alignstack))
1665 LocTy ParenLoc = Lex.getLoc();
1666 if (!EatIfPresent(lltok::lparen))
1667 return Error(ParenLoc, "expected '('");
1668 LocTy AlignLoc = Lex.getLoc();
1669 if (ParseUInt32(Alignment)) return true;
1670 ParenLoc = Lex.getLoc();
1671 if (!EatIfPresent(lltok::rparen))
1672 return Error(ParenLoc, "expected ')'");
1673 if (!isPowerOf2_32(Alignment))
1674 return Error(AlignLoc, "stack alignment is not a power of two");
1678 /// ParseIndexList - This parses the index list for an insert/extractvalue
1679 /// instruction. This sets AteExtraComma in the case where we eat an extra
1680 /// comma at the end of the line and find that it is followed by metadata.
1681 /// Clients that don't allow metadata can call the version of this function that
1682 /// only takes one argument.
1685 /// ::= (',' uint32)+
1687 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1688 bool &AteExtraComma) {
1689 AteExtraComma = false;
1691 if (Lex.getKind() != lltok::comma)
1692 return TokError("expected ',' as start of index list");
1694 while (EatIfPresent(lltok::comma)) {
1695 if (Lex.getKind() == lltok::MetadataVar) {
1696 AteExtraComma = true;
1700 if (ParseUInt32(Idx)) return true;
1701 Indices.push_back(Idx);
1707 //===----------------------------------------------------------------------===//
1709 //===----------------------------------------------------------------------===//
1711 /// ParseType - Parse a type.
1712 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1713 SMLoc TypeLoc = Lex.getLoc();
1714 switch (Lex.getKind()) {
1716 return TokError("expected type");
1718 // Type ::= 'float' | 'void' (etc)
1719 Result = Lex.getTyVal();
1723 // Type ::= StructType
1724 if (ParseAnonStructType(Result, false))
1727 case lltok::lsquare:
1728 // Type ::= '[' ... ']'
1729 Lex.Lex(); // eat the lsquare.
1730 if (ParseArrayVectorType(Result, false))
1733 case lltok::less: // Either vector or packed struct.
1734 // Type ::= '<' ... '>'
1736 if (Lex.getKind() == lltok::lbrace) {
1737 if (ParseAnonStructType(Result, true) ||
1738 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1740 } else if (ParseArrayVectorType(Result, true))
1743 case lltok::LocalVar: {
1745 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1747 // If the type hasn't been defined yet, create a forward definition and
1748 // remember where that forward def'n was seen (in case it never is defined).
1750 Entry.first = StructType::create(Context, Lex.getStrVal());
1751 Entry.second = Lex.getLoc();
1753 Result = Entry.first;
1758 case lltok::LocalVarID: {
1760 if (Lex.getUIntVal() >= NumberedTypes.size())
1761 NumberedTypes.resize(Lex.getUIntVal()+1);
1762 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1764 // If the type hasn't been defined yet, create a forward definition and
1765 // remember where that forward def'n was seen (in case it never is defined).
1767 Entry.first = StructType::create(Context);
1768 Entry.second = Lex.getLoc();
1770 Result = Entry.first;
1776 // Parse the type suffixes.
1778 switch (Lex.getKind()) {
1781 if (!AllowVoid && Result->isVoidTy())
1782 return Error(TypeLoc, "void type only allowed for function results");
1785 // Type ::= Type '*'
1787 if (Result->isLabelTy())
1788 return TokError("basic block pointers are invalid");
1789 if (Result->isVoidTy())
1790 return TokError("pointers to void are invalid - use i8* instead");
1791 if (!PointerType::isValidElementType(Result))
1792 return TokError("pointer to this type is invalid");
1793 Result = PointerType::getUnqual(Result);
1797 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1798 case lltok::kw_addrspace: {
1799 if (Result->isLabelTy())
1800 return TokError("basic block pointers are invalid");
1801 if (Result->isVoidTy())
1802 return TokError("pointers to void are invalid; use i8* instead");
1803 if (!PointerType::isValidElementType(Result))
1804 return TokError("pointer to this type is invalid");
1806 if (ParseOptionalAddrSpace(AddrSpace) ||
1807 ParseToken(lltok::star, "expected '*' in address space"))
1810 Result = PointerType::get(Result, AddrSpace);
1814 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1816 if (ParseFunctionType(Result))
1823 /// ParseParameterList
1825 /// ::= '(' Arg (',' Arg)* ')'
1827 /// ::= Type OptionalAttributes Value OptionalAttributes
1828 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1829 PerFunctionState &PFS, bool IsMustTailCall,
1830 bool InVarArgsFunc) {
1831 if (ParseToken(lltok::lparen, "expected '(' in call"))
1834 unsigned AttrIndex = 1;
1835 while (Lex.getKind() != lltok::rparen) {
1836 // If this isn't the first argument, we need a comma.
1837 if (!ArgList.empty() &&
1838 ParseToken(lltok::comma, "expected ',' in argument list"))
1841 // Parse an ellipsis if this is a musttail call in a variadic function.
1842 if (Lex.getKind() == lltok::dotdotdot) {
1843 const char *Msg = "unexpected ellipsis in argument list for ";
1844 if (!IsMustTailCall)
1845 return TokError(Twine(Msg) + "non-musttail call");
1847 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1848 Lex.Lex(); // Lex the '...', it is purely for readability.
1849 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1852 // Parse the argument.
1854 Type *ArgTy = nullptr;
1855 AttrBuilder ArgAttrs;
1857 if (ParseType(ArgTy, ArgLoc))
1860 // Otherwise, handle normal operands.
1861 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1863 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1868 if (IsMustTailCall && InVarArgsFunc)
1869 return TokError("expected '...' at end of argument list for musttail call "
1870 "in varargs function");
1872 Lex.Lex(); // Lex the ')'.
1878 /// ParseArgumentList - Parse the argument list for a function type or function
1880 /// ::= '(' ArgTypeListI ')'
1884 /// ::= ArgTypeList ',' '...'
1885 /// ::= ArgType (',' ArgType)*
1887 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1890 assert(Lex.getKind() == lltok::lparen);
1891 Lex.Lex(); // eat the (.
1893 if (Lex.getKind() == lltok::rparen) {
1895 } else if (Lex.getKind() == lltok::dotdotdot) {
1899 LocTy TypeLoc = Lex.getLoc();
1900 Type *ArgTy = nullptr;
1904 if (ParseType(ArgTy) ||
1905 ParseOptionalParamAttrs(Attrs)) return true;
1907 if (ArgTy->isVoidTy())
1908 return Error(TypeLoc, "argument can not have void type");
1910 if (Lex.getKind() == lltok::LocalVar) {
1911 Name = Lex.getStrVal();
1915 if (!FunctionType::isValidArgumentType(ArgTy))
1916 return Error(TypeLoc, "invalid type for function argument");
1918 unsigned AttrIndex = 1;
1919 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1920 AttributeSet::get(ArgTy->getContext(),
1921 AttrIndex++, Attrs), Name));
1923 while (EatIfPresent(lltok::comma)) {
1924 // Handle ... at end of arg list.
1925 if (EatIfPresent(lltok::dotdotdot)) {
1930 // Otherwise must be an argument type.
1931 TypeLoc = Lex.getLoc();
1932 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1934 if (ArgTy->isVoidTy())
1935 return Error(TypeLoc, "argument can not have void type");
1937 if (Lex.getKind() == lltok::LocalVar) {
1938 Name = Lex.getStrVal();
1944 if (!ArgTy->isFirstClassType())
1945 return Error(TypeLoc, "invalid type for function argument");
1947 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1948 AttributeSet::get(ArgTy->getContext(),
1949 AttrIndex++, Attrs),
1954 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1957 /// ParseFunctionType
1958 /// ::= Type ArgumentList OptionalAttrs
1959 bool LLParser::ParseFunctionType(Type *&Result) {
1960 assert(Lex.getKind() == lltok::lparen);
1962 if (!FunctionType::isValidReturnType(Result))
1963 return TokError("invalid function return type");
1965 SmallVector<ArgInfo, 8> ArgList;
1967 if (ParseArgumentList(ArgList, isVarArg))
1970 // Reject names on the arguments lists.
1971 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1972 if (!ArgList[i].Name.empty())
1973 return Error(ArgList[i].Loc, "argument name invalid in function type");
1974 if (ArgList[i].Attrs.hasAttributes(i + 1))
1975 return Error(ArgList[i].Loc,
1976 "argument attributes invalid in function type");
1979 SmallVector<Type*, 16> ArgListTy;
1980 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1981 ArgListTy.push_back(ArgList[i].Ty);
1983 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1987 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1989 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1990 SmallVector<Type*, 8> Elts;
1991 if (ParseStructBody(Elts)) return true;
1993 Result = StructType::get(Context, Elts, Packed);
1997 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1998 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1999 std::pair<Type*, LocTy> &Entry,
2001 // If the type was already defined, diagnose the redefinition.
2002 if (Entry.first && !Entry.second.isValid())
2003 return Error(TypeLoc, "redefinition of type");
2005 // If we have opaque, just return without filling in the definition for the
2006 // struct. This counts as a definition as far as the .ll file goes.
2007 if (EatIfPresent(lltok::kw_opaque)) {
2008 // This type is being defined, so clear the location to indicate this.
2009 Entry.second = SMLoc();
2011 // If this type number has never been uttered, create it.
2013 Entry.first = StructType::create(Context, Name);
2014 ResultTy = Entry.first;
2018 // If the type starts with '<', then it is either a packed struct or a vector.
2019 bool isPacked = EatIfPresent(lltok::less);
2021 // If we don't have a struct, then we have a random type alias, which we
2022 // accept for compatibility with old files. These types are not allowed to be
2023 // forward referenced and not allowed to be recursive.
2024 if (Lex.getKind() != lltok::lbrace) {
2026 return Error(TypeLoc, "forward references to non-struct type");
2030 return ParseArrayVectorType(ResultTy, true);
2031 return ParseType(ResultTy);
2034 // This type is being defined, so clear the location to indicate this.
2035 Entry.second = SMLoc();
2037 // If this type number has never been uttered, create it.
2039 Entry.first = StructType::create(Context, Name);
2041 StructType *STy = cast<StructType>(Entry.first);
2043 SmallVector<Type*, 8> Body;
2044 if (ParseStructBody(Body) ||
2045 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2048 STy->setBody(Body, isPacked);
2054 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2057 /// ::= '{' Type (',' Type)* '}'
2058 /// ::= '<' '{' '}' '>'
2059 /// ::= '<' '{' Type (',' Type)* '}' '>'
2060 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2061 assert(Lex.getKind() == lltok::lbrace);
2062 Lex.Lex(); // Consume the '{'
2064 // Handle the empty struct.
2065 if (EatIfPresent(lltok::rbrace))
2068 LocTy EltTyLoc = Lex.getLoc();
2070 if (ParseType(Ty)) return true;
2073 if (!StructType::isValidElementType(Ty))
2074 return Error(EltTyLoc, "invalid element type for struct");
2076 while (EatIfPresent(lltok::comma)) {
2077 EltTyLoc = Lex.getLoc();
2078 if (ParseType(Ty)) return true;
2080 if (!StructType::isValidElementType(Ty))
2081 return Error(EltTyLoc, "invalid element type for struct");
2086 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2089 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2090 /// token has already been consumed.
2092 /// ::= '[' APSINTVAL 'x' Types ']'
2093 /// ::= '<' APSINTVAL 'x' Types '>'
2094 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2095 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2096 Lex.getAPSIntVal().getBitWidth() > 64)
2097 return TokError("expected number in address space");
2099 LocTy SizeLoc = Lex.getLoc();
2100 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2103 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2106 LocTy TypeLoc = Lex.getLoc();
2107 Type *EltTy = nullptr;
2108 if (ParseType(EltTy)) return true;
2110 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2111 "expected end of sequential type"))
2116 return Error(SizeLoc, "zero element vector is illegal");
2117 if ((unsigned)Size != Size)
2118 return Error(SizeLoc, "size too large for vector");
2119 if (!VectorType::isValidElementType(EltTy))
2120 return Error(TypeLoc, "invalid vector element type");
2121 Result = VectorType::get(EltTy, unsigned(Size));
2123 if (!ArrayType::isValidElementType(EltTy))
2124 return Error(TypeLoc, "invalid array element type");
2125 Result = ArrayType::get(EltTy, Size);
2130 //===----------------------------------------------------------------------===//
2131 // Function Semantic Analysis.
2132 //===----------------------------------------------------------------------===//
2134 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2136 : P(p), F(f), FunctionNumber(functionNumber) {
2138 // Insert unnamed arguments into the NumberedVals list.
2139 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2142 NumberedVals.push_back(AI);
2145 LLParser::PerFunctionState::~PerFunctionState() {
2146 // If there were any forward referenced non-basicblock values, delete them.
2147 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2148 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2149 if (!isa<BasicBlock>(I->second.first)) {
2150 I->second.first->replaceAllUsesWith(
2151 UndefValue::get(I->second.first->getType()));
2152 delete I->second.first;
2153 I->second.first = nullptr;
2156 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2157 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2158 if (!isa<BasicBlock>(I->second.first)) {
2159 I->second.first->replaceAllUsesWith(
2160 UndefValue::get(I->second.first->getType()));
2161 delete I->second.first;
2162 I->second.first = nullptr;
2166 bool LLParser::PerFunctionState::FinishFunction() {
2167 if (!ForwardRefVals.empty())
2168 return P.Error(ForwardRefVals.begin()->second.second,
2169 "use of undefined value '%" + ForwardRefVals.begin()->first +
2171 if (!ForwardRefValIDs.empty())
2172 return P.Error(ForwardRefValIDs.begin()->second.second,
2173 "use of undefined value '%" +
2174 Twine(ForwardRefValIDs.begin()->first) + "'");
2179 /// GetVal - Get a value with the specified name or ID, creating a
2180 /// forward reference record if needed. This can return null if the value
2181 /// exists but does not have the right type.
2182 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2183 Type *Ty, LocTy Loc) {
2184 // Look this name up in the normal function symbol table.
2185 Value *Val = F.getValueSymbolTable().lookup(Name);
2187 // If this is a forward reference for the value, see if we already created a
2188 // forward ref record.
2190 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2191 I = ForwardRefVals.find(Name);
2192 if (I != ForwardRefVals.end())
2193 Val = I->second.first;
2196 // If we have the value in the symbol table or fwd-ref table, return it.
2198 if (Val->getType() == Ty) return Val;
2199 if (Ty->isLabelTy())
2200 P.Error(Loc, "'%" + Name + "' is not a basic block");
2202 P.Error(Loc, "'%" + Name + "' defined with type '" +
2203 getTypeString(Val->getType()) + "'");
2207 // Don't make placeholders with invalid type.
2208 if (!Ty->isFirstClassType()) {
2209 P.Error(Loc, "invalid use of a non-first-class type");
2213 // Otherwise, create a new forward reference for this value and remember it.
2215 if (Ty->isLabelTy())
2216 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2218 FwdVal = new Argument(Ty, Name);
2220 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2224 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2226 // Look this name up in the normal function symbol table.
2227 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2229 // If this is a forward reference for the value, see if we already created a
2230 // forward ref record.
2232 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2233 I = ForwardRefValIDs.find(ID);
2234 if (I != ForwardRefValIDs.end())
2235 Val = I->second.first;
2238 // If we have the value in the symbol table or fwd-ref table, return it.
2240 if (Val->getType() == Ty) return Val;
2241 if (Ty->isLabelTy())
2242 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2244 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2245 getTypeString(Val->getType()) + "'");
2249 if (!Ty->isFirstClassType()) {
2250 P.Error(Loc, "invalid use of a non-first-class type");
2254 // Otherwise, create a new forward reference for this value and remember it.
2256 if (Ty->isLabelTy())
2257 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2259 FwdVal = new Argument(Ty);
2261 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2265 /// SetInstName - After an instruction is parsed and inserted into its
2266 /// basic block, this installs its name.
2267 bool LLParser::PerFunctionState::SetInstName(int NameID,
2268 const std::string &NameStr,
2269 LocTy NameLoc, Instruction *Inst) {
2270 // If this instruction has void type, it cannot have a name or ID specified.
2271 if (Inst->getType()->isVoidTy()) {
2272 if (NameID != -1 || !NameStr.empty())
2273 return P.Error(NameLoc, "instructions returning void cannot have a name");
2277 // If this was a numbered instruction, verify that the instruction is the
2278 // expected value and resolve any forward references.
2279 if (NameStr.empty()) {
2280 // If neither a name nor an ID was specified, just use the next ID.
2282 NameID = NumberedVals.size();
2284 if (unsigned(NameID) != NumberedVals.size())
2285 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2286 Twine(NumberedVals.size()) + "'");
2288 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2289 ForwardRefValIDs.find(NameID);
2290 if (FI != ForwardRefValIDs.end()) {
2291 if (FI->second.first->getType() != Inst->getType())
2292 return P.Error(NameLoc, "instruction forward referenced with type '" +
2293 getTypeString(FI->second.first->getType()) + "'");
2294 FI->second.first->replaceAllUsesWith(Inst);
2295 delete FI->second.first;
2296 ForwardRefValIDs.erase(FI);
2299 NumberedVals.push_back(Inst);
2303 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2304 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2305 FI = ForwardRefVals.find(NameStr);
2306 if (FI != ForwardRefVals.end()) {
2307 if (FI->second.first->getType() != Inst->getType())
2308 return P.Error(NameLoc, "instruction forward referenced with type '" +
2309 getTypeString(FI->second.first->getType()) + "'");
2310 FI->second.first->replaceAllUsesWith(Inst);
2311 delete FI->second.first;
2312 ForwardRefVals.erase(FI);
2315 // Set the name on the instruction.
2316 Inst->setName(NameStr);
2318 if (Inst->getName() != NameStr)
2319 return P.Error(NameLoc, "multiple definition of local value named '" +
2324 /// GetBB - Get a basic block with the specified name or ID, creating a
2325 /// forward reference record if needed.
2326 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2328 return cast_or_null<BasicBlock>(GetVal(Name,
2329 Type::getLabelTy(F.getContext()), Loc));
2332 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2333 return cast_or_null<BasicBlock>(GetVal(ID,
2334 Type::getLabelTy(F.getContext()), Loc));
2337 /// DefineBB - Define the specified basic block, which is either named or
2338 /// unnamed. If there is an error, this returns null otherwise it returns
2339 /// the block being defined.
2340 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2344 BB = GetBB(NumberedVals.size(), Loc);
2346 BB = GetBB(Name, Loc);
2347 if (!BB) return nullptr; // Already diagnosed error.
2349 // Move the block to the end of the function. Forward ref'd blocks are
2350 // inserted wherever they happen to be referenced.
2351 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2353 // Remove the block from forward ref sets.
2355 ForwardRefValIDs.erase(NumberedVals.size());
2356 NumberedVals.push_back(BB);
2358 // BB forward references are already in the function symbol table.
2359 ForwardRefVals.erase(Name);
2365 //===----------------------------------------------------------------------===//
2367 //===----------------------------------------------------------------------===//
2369 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2370 /// type implied. For example, if we parse "4" we don't know what integer type
2371 /// it has. The value will later be combined with its type and checked for
2372 /// sanity. PFS is used to convert function-local operands of metadata (since
2373 /// metadata operands are not just parsed here but also converted to values).
2374 /// PFS can be null when we are not parsing metadata values inside a function.
2375 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2376 ID.Loc = Lex.getLoc();
2377 switch (Lex.getKind()) {
2378 default: return TokError("expected value token");
2379 case lltok::GlobalID: // @42
2380 ID.UIntVal = Lex.getUIntVal();
2381 ID.Kind = ValID::t_GlobalID;
2383 case lltok::GlobalVar: // @foo
2384 ID.StrVal = Lex.getStrVal();
2385 ID.Kind = ValID::t_GlobalName;
2387 case lltok::LocalVarID: // %42
2388 ID.UIntVal = Lex.getUIntVal();
2389 ID.Kind = ValID::t_LocalID;
2391 case lltok::LocalVar: // %foo
2392 ID.StrVal = Lex.getStrVal();
2393 ID.Kind = ValID::t_LocalName;
2395 case lltok::exclaim: // !42, !{...}, or !"foo"
2396 return ParseMetadataValue(ID, PFS);
2398 ID.APSIntVal = Lex.getAPSIntVal();
2399 ID.Kind = ValID::t_APSInt;
2401 case lltok::APFloat:
2402 ID.APFloatVal = Lex.getAPFloatVal();
2403 ID.Kind = ValID::t_APFloat;
2405 case lltok::kw_true:
2406 ID.ConstantVal = ConstantInt::getTrue(Context);
2407 ID.Kind = ValID::t_Constant;
2409 case lltok::kw_false:
2410 ID.ConstantVal = ConstantInt::getFalse(Context);
2411 ID.Kind = ValID::t_Constant;
2413 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2414 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2415 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2417 case lltok::lbrace: {
2418 // ValID ::= '{' ConstVector '}'
2420 SmallVector<Constant*, 16> Elts;
2421 if (ParseGlobalValueVector(Elts) ||
2422 ParseToken(lltok::rbrace, "expected end of struct constant"))
2425 ID.ConstantStructElts = new Constant*[Elts.size()];
2426 ID.UIntVal = Elts.size();
2427 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2428 ID.Kind = ValID::t_ConstantStruct;
2432 // ValID ::= '<' ConstVector '>' --> Vector.
2433 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2435 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2437 SmallVector<Constant*, 16> Elts;
2438 LocTy FirstEltLoc = Lex.getLoc();
2439 if (ParseGlobalValueVector(Elts) ||
2441 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2442 ParseToken(lltok::greater, "expected end of constant"))
2445 if (isPackedStruct) {
2446 ID.ConstantStructElts = new Constant*[Elts.size()];
2447 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2448 ID.UIntVal = Elts.size();
2449 ID.Kind = ValID::t_PackedConstantStruct;
2454 return Error(ID.Loc, "constant vector must not be empty");
2456 if (!Elts[0]->getType()->isIntegerTy() &&
2457 !Elts[0]->getType()->isFloatingPointTy() &&
2458 !Elts[0]->getType()->isPointerTy())
2459 return Error(FirstEltLoc,
2460 "vector elements must have integer, pointer or floating point type");
2462 // Verify that all the vector elements have the same type.
2463 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2464 if (Elts[i]->getType() != Elts[0]->getType())
2465 return Error(FirstEltLoc,
2466 "vector element #" + Twine(i) +
2467 " is not of type '" + getTypeString(Elts[0]->getType()));
2469 ID.ConstantVal = ConstantVector::get(Elts);
2470 ID.Kind = ValID::t_Constant;
2473 case lltok::lsquare: { // Array Constant
2475 SmallVector<Constant*, 16> Elts;
2476 LocTy FirstEltLoc = Lex.getLoc();
2477 if (ParseGlobalValueVector(Elts) ||
2478 ParseToken(lltok::rsquare, "expected end of array constant"))
2481 // Handle empty element.
2483 // Use undef instead of an array because it's inconvenient to determine
2484 // the element type at this point, there being no elements to examine.
2485 ID.Kind = ValID::t_EmptyArray;
2489 if (!Elts[0]->getType()->isFirstClassType())
2490 return Error(FirstEltLoc, "invalid array element type: " +
2491 getTypeString(Elts[0]->getType()));
2493 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2495 // Verify all elements are correct type!
2496 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2497 if (Elts[i]->getType() != Elts[0]->getType())
2498 return Error(FirstEltLoc,
2499 "array element #" + Twine(i) +
2500 " is not of type '" + getTypeString(Elts[0]->getType()));
2503 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2504 ID.Kind = ValID::t_Constant;
2507 case lltok::kw_c: // c "foo"
2509 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2511 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2512 ID.Kind = ValID::t_Constant;
2515 case lltok::kw_asm: {
2516 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2518 bool HasSideEffect, AlignStack, AsmDialect;
2520 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2521 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2522 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2523 ParseStringConstant(ID.StrVal) ||
2524 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2525 ParseToken(lltok::StringConstant, "expected constraint string"))
2527 ID.StrVal2 = Lex.getStrVal();
2528 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2529 (unsigned(AsmDialect)<<2);
2530 ID.Kind = ValID::t_InlineAsm;
2534 case lltok::kw_blockaddress: {
2535 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2540 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2542 ParseToken(lltok::comma, "expected comma in block address expression")||
2543 ParseValID(Label) ||
2544 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2547 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2548 return Error(Fn.Loc, "expected function name in blockaddress");
2549 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2550 return Error(Label.Loc, "expected basic block name in blockaddress");
2552 // Try to find the function (but skip it if it's forward-referenced).
2553 GlobalValue *GV = nullptr;
2554 if (Fn.Kind == ValID::t_GlobalID) {
2555 if (Fn.UIntVal < NumberedVals.size())
2556 GV = NumberedVals[Fn.UIntVal];
2557 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2558 GV = M->getNamedValue(Fn.StrVal);
2560 Function *F = nullptr;
2562 // Confirm that it's actually a function with a definition.
2563 if (!isa<Function>(GV))
2564 return Error(Fn.Loc, "expected function name in blockaddress");
2565 F = cast<Function>(GV);
2566 if (F->isDeclaration())
2567 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2571 // Make a global variable as a placeholder for this reference.
2572 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2574 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2575 GlobalValue::InternalLinkage, nullptr, "");
2576 ID.ConstantVal = FwdRef;
2577 ID.Kind = ValID::t_Constant;
2581 // We found the function; now find the basic block. Don't use PFS, since we
2582 // might be inside a constant expression.
2584 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2585 if (Label.Kind == ValID::t_LocalID)
2586 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2588 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2590 return Error(Label.Loc, "referenced value is not a basic block");
2592 if (Label.Kind == ValID::t_LocalID)
2593 return Error(Label.Loc, "cannot take address of numeric label after "
2594 "the function is defined");
2595 BB = dyn_cast_or_null<BasicBlock>(
2596 F->getValueSymbolTable().lookup(Label.StrVal));
2598 return Error(Label.Loc, "referenced value is not a basic block");
2601 ID.ConstantVal = BlockAddress::get(F, BB);
2602 ID.Kind = ValID::t_Constant;
2606 case lltok::kw_trunc:
2607 case lltok::kw_zext:
2608 case lltok::kw_sext:
2609 case lltok::kw_fptrunc:
2610 case lltok::kw_fpext:
2611 case lltok::kw_bitcast:
2612 case lltok::kw_addrspacecast:
2613 case lltok::kw_uitofp:
2614 case lltok::kw_sitofp:
2615 case lltok::kw_fptoui:
2616 case lltok::kw_fptosi:
2617 case lltok::kw_inttoptr:
2618 case lltok::kw_ptrtoint: {
2619 unsigned Opc = Lex.getUIntVal();
2620 Type *DestTy = nullptr;
2623 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2624 ParseGlobalTypeAndValue(SrcVal) ||
2625 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2626 ParseType(DestTy) ||
2627 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2629 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2630 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2631 getTypeString(SrcVal->getType()) + "' to '" +
2632 getTypeString(DestTy) + "'");
2633 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2635 ID.Kind = ValID::t_Constant;
2638 case lltok::kw_extractvalue: {
2641 SmallVector<unsigned, 4> Indices;
2642 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2643 ParseGlobalTypeAndValue(Val) ||
2644 ParseIndexList(Indices) ||
2645 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2648 if (!Val->getType()->isAggregateType())
2649 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2650 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2651 return Error(ID.Loc, "invalid indices for extractvalue");
2652 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2653 ID.Kind = ValID::t_Constant;
2656 case lltok::kw_insertvalue: {
2658 Constant *Val0, *Val1;
2659 SmallVector<unsigned, 4> Indices;
2660 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2661 ParseGlobalTypeAndValue(Val0) ||
2662 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2663 ParseGlobalTypeAndValue(Val1) ||
2664 ParseIndexList(Indices) ||
2665 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2667 if (!Val0->getType()->isAggregateType())
2668 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2669 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2670 return Error(ID.Loc, "invalid indices for insertvalue");
2671 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2672 ID.Kind = ValID::t_Constant;
2675 case lltok::kw_icmp:
2676 case lltok::kw_fcmp: {
2677 unsigned PredVal, Opc = Lex.getUIntVal();
2678 Constant *Val0, *Val1;
2680 if (ParseCmpPredicate(PredVal, Opc) ||
2681 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2682 ParseGlobalTypeAndValue(Val0) ||
2683 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2684 ParseGlobalTypeAndValue(Val1) ||
2685 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2688 if (Val0->getType() != Val1->getType())
2689 return Error(ID.Loc, "compare operands must have the same type");
2691 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2693 if (Opc == Instruction::FCmp) {
2694 if (!Val0->getType()->isFPOrFPVectorTy())
2695 return Error(ID.Loc, "fcmp requires floating point operands");
2696 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2698 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2699 if (!Val0->getType()->isIntOrIntVectorTy() &&
2700 !Val0->getType()->getScalarType()->isPointerTy())
2701 return Error(ID.Loc, "icmp requires pointer or integer operands");
2702 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2704 ID.Kind = ValID::t_Constant;
2708 // Binary Operators.
2710 case lltok::kw_fadd:
2712 case lltok::kw_fsub:
2714 case lltok::kw_fmul:
2715 case lltok::kw_udiv:
2716 case lltok::kw_sdiv:
2717 case lltok::kw_fdiv:
2718 case lltok::kw_urem:
2719 case lltok::kw_srem:
2720 case lltok::kw_frem:
2722 case lltok::kw_lshr:
2723 case lltok::kw_ashr: {
2727 unsigned Opc = Lex.getUIntVal();
2728 Constant *Val0, *Val1;
2730 LocTy ModifierLoc = Lex.getLoc();
2731 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2732 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2733 if (EatIfPresent(lltok::kw_nuw))
2735 if (EatIfPresent(lltok::kw_nsw)) {
2737 if (EatIfPresent(lltok::kw_nuw))
2740 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2741 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2742 if (EatIfPresent(lltok::kw_exact))
2745 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2746 ParseGlobalTypeAndValue(Val0) ||
2747 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2748 ParseGlobalTypeAndValue(Val1) ||
2749 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2751 if (Val0->getType() != Val1->getType())
2752 return Error(ID.Loc, "operands of constexpr must have same type");
2753 if (!Val0->getType()->isIntOrIntVectorTy()) {
2755 return Error(ModifierLoc, "nuw only applies to integer operations");
2757 return Error(ModifierLoc, "nsw only applies to integer operations");
2759 // Check that the type is valid for the operator.
2761 case Instruction::Add:
2762 case Instruction::Sub:
2763 case Instruction::Mul:
2764 case Instruction::UDiv:
2765 case Instruction::SDiv:
2766 case Instruction::URem:
2767 case Instruction::SRem:
2768 case Instruction::Shl:
2769 case Instruction::AShr:
2770 case Instruction::LShr:
2771 if (!Val0->getType()->isIntOrIntVectorTy())
2772 return Error(ID.Loc, "constexpr requires integer operands");
2774 case Instruction::FAdd:
2775 case Instruction::FSub:
2776 case Instruction::FMul:
2777 case Instruction::FDiv:
2778 case Instruction::FRem:
2779 if (!Val0->getType()->isFPOrFPVectorTy())
2780 return Error(ID.Loc, "constexpr requires fp operands");
2782 default: llvm_unreachable("Unknown binary operator!");
2785 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2786 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2787 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2788 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2790 ID.Kind = ValID::t_Constant;
2794 // Logical Operations
2797 case lltok::kw_xor: {
2798 unsigned Opc = Lex.getUIntVal();
2799 Constant *Val0, *Val1;
2801 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2802 ParseGlobalTypeAndValue(Val0) ||
2803 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2804 ParseGlobalTypeAndValue(Val1) ||
2805 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2807 if (Val0->getType() != Val1->getType())
2808 return Error(ID.Loc, "operands of constexpr must have same type");
2809 if (!Val0->getType()->isIntOrIntVectorTy())
2810 return Error(ID.Loc,
2811 "constexpr requires integer or integer vector operands");
2812 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2813 ID.Kind = ValID::t_Constant;
2817 case lltok::kw_getelementptr:
2818 case lltok::kw_shufflevector:
2819 case lltok::kw_insertelement:
2820 case lltok::kw_extractelement:
2821 case lltok::kw_select: {
2822 unsigned Opc = Lex.getUIntVal();
2823 SmallVector<Constant*, 16> Elts;
2824 bool InBounds = false;
2826 if (Opc == Instruction::GetElementPtr)
2827 InBounds = EatIfPresent(lltok::kw_inbounds);
2828 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2829 ParseGlobalValueVector(Elts) ||
2830 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2833 if (Opc == Instruction::GetElementPtr) {
2834 if (Elts.size() == 0 ||
2835 !Elts[0]->getType()->getScalarType()->isPointerTy())
2836 return Error(ID.Loc, "getelementptr requires pointer operand");
2838 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2839 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2840 return Error(ID.Loc, "invalid indices for getelementptr");
2841 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2843 } else if (Opc == Instruction::Select) {
2844 if (Elts.size() != 3)
2845 return Error(ID.Loc, "expected three operands to select");
2846 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2848 return Error(ID.Loc, Reason);
2849 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2850 } else if (Opc == Instruction::ShuffleVector) {
2851 if (Elts.size() != 3)
2852 return Error(ID.Loc, "expected three operands to shufflevector");
2853 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2854 return Error(ID.Loc, "invalid operands to shufflevector");
2856 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2857 } else if (Opc == Instruction::ExtractElement) {
2858 if (Elts.size() != 2)
2859 return Error(ID.Loc, "expected two operands to extractelement");
2860 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2861 return Error(ID.Loc, "invalid extractelement operands");
2862 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2864 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2865 if (Elts.size() != 3)
2866 return Error(ID.Loc, "expected three operands to insertelement");
2867 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2868 return Error(ID.Loc, "invalid insertelement operands");
2870 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2873 ID.Kind = ValID::t_Constant;
2882 /// ParseGlobalValue - Parse a global value with the specified type.
2883 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2887 bool Parsed = ParseValID(ID) ||
2888 ConvertValIDToValue(Ty, ID, V, nullptr);
2889 if (V && !(C = dyn_cast<Constant>(V)))
2890 return Error(ID.Loc, "global values must be constants");
2894 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2896 return ParseType(Ty) ||
2897 ParseGlobalValue(Ty, V);
2900 bool LLParser::parseOptionalComdat(Comdat *&C) {
2902 if (!EatIfPresent(lltok::kw_comdat))
2904 if (Lex.getKind() != lltok::ComdatVar)
2905 return TokError("expected comdat variable");
2906 LocTy Loc = Lex.getLoc();
2907 StringRef Name = Lex.getStrVal();
2908 C = getComdat(Name, Loc);
2913 /// ParseGlobalValueVector
2915 /// ::= TypeAndValue (',' TypeAndValue)*
2916 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2918 if (Lex.getKind() == lltok::rbrace ||
2919 Lex.getKind() == lltok::rsquare ||
2920 Lex.getKind() == lltok::greater ||
2921 Lex.getKind() == lltok::rparen)
2925 if (ParseGlobalTypeAndValue(C)) return true;
2928 while (EatIfPresent(lltok::comma)) {
2929 if (ParseGlobalTypeAndValue(C)) return true;
2936 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2937 assert(Lex.getKind() == lltok::lbrace);
2940 SmallVector<Value*, 16> Elts;
2941 if (ParseMDNodeVector(Elts, PFS) ||
2942 ParseToken(lltok::rbrace, "expected end of metadata node"))
2945 ID.MDNodeVal = MDNode::get(Context, Elts);
2946 ID.Kind = ValID::t_MDNode;
2950 /// ParseMetadataValue
2954 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2955 assert(Lex.getKind() == lltok::exclaim);
2960 if (Lex.getKind() == lltok::lbrace)
2961 return ParseMetadataListValue(ID, PFS);
2963 // Standalone metadata reference
2965 if (Lex.getKind() == lltok::APSInt) {
2966 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2967 ID.Kind = ValID::t_MDNode;
2972 // ::= '!' STRINGCONSTANT
2973 if (ParseMDString(ID.MDStringVal)) return true;
2974 ID.Kind = ValID::t_MDString;
2979 //===----------------------------------------------------------------------===//
2980 // Function Parsing.
2981 //===----------------------------------------------------------------------===//
2983 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2984 PerFunctionState *PFS) {
2985 if (Ty->isFunctionTy())
2986 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2989 case ValID::t_LocalID:
2990 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2991 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2992 return V == nullptr;
2993 case ValID::t_LocalName:
2994 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2995 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2996 return V == nullptr;
2997 case ValID::t_InlineAsm: {
2998 PointerType *PTy = dyn_cast<PointerType>(Ty);
3000 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3001 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3002 return Error(ID.Loc, "invalid type for inline asm constraint string");
3003 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3004 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3007 case ValID::t_MDNode:
3008 if (!Ty->isMetadataTy())
3009 return Error(ID.Loc, "metadata value must have metadata type");
3012 case ValID::t_MDString:
3013 if (!Ty->isMetadataTy())
3014 return Error(ID.Loc, "metadata value must have metadata type");
3017 case ValID::t_GlobalName:
3018 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3019 return V == nullptr;
3020 case ValID::t_GlobalID:
3021 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3022 return V == nullptr;
3023 case ValID::t_APSInt:
3024 if (!Ty->isIntegerTy())
3025 return Error(ID.Loc, "integer constant must have integer type");
3026 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3027 V = ConstantInt::get(Context, ID.APSIntVal);
3029 case ValID::t_APFloat:
3030 if (!Ty->isFloatingPointTy() ||
3031 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3032 return Error(ID.Loc, "floating point constant invalid for type");
3034 // The lexer has no type info, so builds all half, float, and double FP
3035 // constants as double. Fix this here. Long double does not need this.
3036 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3039 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3041 else if (Ty->isFloatTy())
3042 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3045 V = ConstantFP::get(Context, ID.APFloatVal);
3047 if (V->getType() != Ty)
3048 return Error(ID.Loc, "floating point constant does not have type '" +
3049 getTypeString(Ty) + "'");
3053 if (!Ty->isPointerTy())
3054 return Error(ID.Loc, "null must be a pointer type");
3055 V = ConstantPointerNull::get(cast<PointerType>(Ty));
3057 case ValID::t_Undef:
3058 // FIXME: LabelTy should not be a first-class type.
3059 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3060 return Error(ID.Loc, "invalid type for undef constant");
3061 V = UndefValue::get(Ty);
3063 case ValID::t_EmptyArray:
3064 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3065 return Error(ID.Loc, "invalid empty array initializer");
3066 V = UndefValue::get(Ty);
3069 // FIXME: LabelTy should not be a first-class type.
3070 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3071 return Error(ID.Loc, "invalid type for null constant");
3072 V = Constant::getNullValue(Ty);
3074 case ValID::t_Constant:
3075 if (ID.ConstantVal->getType() != Ty)
3076 return Error(ID.Loc, "constant expression type mismatch");
3080 case ValID::t_ConstantStruct:
3081 case ValID::t_PackedConstantStruct:
3082 if (StructType *ST = dyn_cast<StructType>(Ty)) {
3083 if (ST->getNumElements() != ID.UIntVal)
3084 return Error(ID.Loc,
3085 "initializer with struct type has wrong # elements");
3086 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3087 return Error(ID.Loc, "packed'ness of initializer and type don't match");
3089 // Verify that the elements are compatible with the structtype.
3090 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3091 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3092 return Error(ID.Loc, "element " + Twine(i) +
3093 " of struct initializer doesn't match struct element type");
3095 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3098 return Error(ID.Loc, "constant expression type mismatch");
3101 llvm_unreachable("Invalid ValID");
3104 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
3107 return ParseValID(ID, PFS) ||
3108 ConvertValIDToValue(Ty, ID, V, PFS);
3111 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
3113 return ParseType(Ty) ||
3114 ParseValue(Ty, V, PFS);
3117 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3118 PerFunctionState &PFS) {
3121 if (ParseTypeAndValue(V, PFS)) return true;
3122 if (!isa<BasicBlock>(V))
3123 return Error(Loc, "expected a basic block");
3124 BB = cast<BasicBlock>(V);
3130 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3131 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3132 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue
3133 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3134 // Parse the linkage.
3135 LocTy LinkageLoc = Lex.getLoc();
3138 unsigned Visibility;
3139 unsigned DLLStorageClass;
3140 AttrBuilder RetAttrs;
3142 Type *RetType = nullptr;
3143 LocTy RetTypeLoc = Lex.getLoc();
3144 if (ParseOptionalLinkage(Linkage) ||
3145 ParseOptionalVisibility(Visibility) ||
3146 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3147 ParseOptionalCallingConv(CC) ||
3148 ParseOptionalReturnAttrs(RetAttrs) ||
3149 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3152 // Verify that the linkage is ok.
3153 switch ((GlobalValue::LinkageTypes)Linkage) {
3154 case GlobalValue::ExternalLinkage:
3155 break; // always ok.
3156 case GlobalValue::ExternalWeakLinkage:
3158 return Error(LinkageLoc, "invalid linkage for function definition");
3160 case GlobalValue::PrivateLinkage:
3161 case GlobalValue::InternalLinkage:
3162 case GlobalValue::AvailableExternallyLinkage:
3163 case GlobalValue::LinkOnceAnyLinkage:
3164 case GlobalValue::LinkOnceODRLinkage:
3165 case GlobalValue::WeakAnyLinkage:
3166 case GlobalValue::WeakODRLinkage:
3168 return Error(LinkageLoc, "invalid linkage for function declaration");
3170 case GlobalValue::AppendingLinkage:
3171 case GlobalValue::CommonLinkage:
3172 return Error(LinkageLoc, "invalid function linkage type");
3175 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3176 return Error(LinkageLoc,
3177 "symbol with local linkage must have default visibility");
3179 if (!FunctionType::isValidReturnType(RetType))
3180 return Error(RetTypeLoc, "invalid function return type");
3182 LocTy NameLoc = Lex.getLoc();
3184 std::string FunctionName;
3185 if (Lex.getKind() == lltok::GlobalVar) {
3186 FunctionName = Lex.getStrVal();
3187 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3188 unsigned NameID = Lex.getUIntVal();
3190 if (NameID != NumberedVals.size())
3191 return TokError("function expected to be numbered '%" +
3192 Twine(NumberedVals.size()) + "'");
3194 return TokError("expected function name");
3199 if (Lex.getKind() != lltok::lparen)
3200 return TokError("expected '(' in function argument list");
3202 SmallVector<ArgInfo, 8> ArgList;
3204 AttrBuilder FuncAttrs;
3205 std::vector<unsigned> FwdRefAttrGrps;
3207 std::string Section;
3211 LocTy UnnamedAddrLoc;
3212 Constant *Prefix = nullptr;
3213 Constant *Prologue = nullptr;
3216 if (ParseArgumentList(ArgList, isVarArg) ||
3217 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3219 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3221 (EatIfPresent(lltok::kw_section) &&
3222 ParseStringConstant(Section)) ||
3223 parseOptionalComdat(C) ||
3224 ParseOptionalAlignment(Alignment) ||
3225 (EatIfPresent(lltok::kw_gc) &&
3226 ParseStringConstant(GC)) ||
3227 (EatIfPresent(lltok::kw_prefix) &&
3228 ParseGlobalTypeAndValue(Prefix)) ||
3229 (EatIfPresent(lltok::kw_prologue) &&
3230 ParseGlobalTypeAndValue(Prologue)))
3233 if (FuncAttrs.contains(Attribute::Builtin))
3234 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3236 // If the alignment was parsed as an attribute, move to the alignment field.
3237 if (FuncAttrs.hasAlignmentAttr()) {
3238 Alignment = FuncAttrs.getAlignment();
3239 FuncAttrs.removeAttribute(Attribute::Alignment);
3242 // Okay, if we got here, the function is syntactically valid. Convert types
3243 // and do semantic checks.
3244 std::vector<Type*> ParamTypeList;
3245 SmallVector<AttributeSet, 8> Attrs;
3247 if (RetAttrs.hasAttributes())
3248 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3249 AttributeSet::ReturnIndex,
3252 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3253 ParamTypeList.push_back(ArgList[i].Ty);
3254 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3255 AttrBuilder B(ArgList[i].Attrs, i + 1);
3256 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3260 if (FuncAttrs.hasAttributes())
3261 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3262 AttributeSet::FunctionIndex,
3265 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3267 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3268 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3271 FunctionType::get(RetType, ParamTypeList, isVarArg);
3272 PointerType *PFT = PointerType::getUnqual(FT);
3275 if (!FunctionName.empty()) {
3276 // If this was a definition of a forward reference, remove the definition
3277 // from the forward reference table and fill in the forward ref.
3278 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3279 ForwardRefVals.find(FunctionName);
3280 if (FRVI != ForwardRefVals.end()) {
3281 Fn = M->getFunction(FunctionName);
3283 return Error(FRVI->second.second, "invalid forward reference to "
3284 "function as global value!");
3285 if (Fn->getType() != PFT)
3286 return Error(FRVI->second.second, "invalid forward reference to "
3287 "function '" + FunctionName + "' with wrong type!");
3289 ForwardRefVals.erase(FRVI);
3290 } else if ((Fn = M->getFunction(FunctionName))) {
3291 // Reject redefinitions.
3292 return Error(NameLoc, "invalid redefinition of function '" +
3293 FunctionName + "'");
3294 } else if (M->getNamedValue(FunctionName)) {
3295 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3299 // If this is a definition of a forward referenced function, make sure the
3301 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3302 = ForwardRefValIDs.find(NumberedVals.size());
3303 if (I != ForwardRefValIDs.end()) {
3304 Fn = cast<Function>(I->second.first);
3305 if (Fn->getType() != PFT)
3306 return Error(NameLoc, "type of definition and forward reference of '@" +
3307 Twine(NumberedVals.size()) + "' disagree");
3308 ForwardRefValIDs.erase(I);
3313 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3314 else // Move the forward-reference to the correct spot in the module.
3315 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3317 if (FunctionName.empty())
3318 NumberedVals.push_back(Fn);
3320 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3321 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3322 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3323 Fn->setCallingConv(CC);
3324 Fn->setAttributes(PAL);
3325 Fn->setUnnamedAddr(UnnamedAddr);
3326 Fn->setAlignment(Alignment);
3327 Fn->setSection(Section);
3329 if (!GC.empty()) Fn->setGC(GC.c_str());
3330 Fn->setPrefixData(Prefix);
3331 Fn->setPrologueData(Prologue);
3332 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3334 // Add all of the arguments we parsed to the function.
3335 Function::arg_iterator ArgIt = Fn->arg_begin();
3336 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3337 // If the argument has a name, insert it into the argument symbol table.
3338 if (ArgList[i].Name.empty()) continue;
3340 // Set the name, if it conflicted, it will be auto-renamed.
3341 ArgIt->setName(ArgList[i].Name);
3343 if (ArgIt->getName() != ArgList[i].Name)
3344 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3345 ArgList[i].Name + "'");
3351 // Check the declaration has no block address forward references.
3353 if (FunctionName.empty()) {
3354 ID.Kind = ValID::t_GlobalID;
3355 ID.UIntVal = NumberedVals.size() - 1;
3357 ID.Kind = ValID::t_GlobalName;
3358 ID.StrVal = FunctionName;
3360 auto Blocks = ForwardRefBlockAddresses.find(ID);
3361 if (Blocks != ForwardRefBlockAddresses.end())
3362 return Error(Blocks->first.Loc,
3363 "cannot take blockaddress inside a declaration");
3367 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
3369 if (FunctionNumber == -1) {
3370 ID.Kind = ValID::t_GlobalName;
3371 ID.StrVal = F.getName();
3373 ID.Kind = ValID::t_GlobalID;
3374 ID.UIntVal = FunctionNumber;
3377 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
3378 if (Blocks == P.ForwardRefBlockAddresses.end())
3381 for (const auto &I : Blocks->second) {
3382 const ValID &BBID = I.first;
3383 GlobalValue *GV = I.second;
3385 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
3386 "Expected local id or name");
3388 if (BBID.Kind == ValID::t_LocalName)
3389 BB = GetBB(BBID.StrVal, BBID.Loc);
3391 BB = GetBB(BBID.UIntVal, BBID.Loc);
3393 return P.Error(BBID.Loc, "referenced value is not a basic block");
3395 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
3396 GV->eraseFromParent();
3399 P.ForwardRefBlockAddresses.erase(Blocks);
3403 /// ParseFunctionBody
3404 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
3405 bool LLParser::ParseFunctionBody(Function &Fn) {
3406 if (Lex.getKind() != lltok::lbrace)
3407 return TokError("expected '{' in function body");
3408 Lex.Lex(); // eat the {.
3410 int FunctionNumber = -1;
3411 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3413 PerFunctionState PFS(*this, Fn, FunctionNumber);
3415 // Resolve block addresses and allow basic blocks to be forward-declared
3416 // within this function.
3417 if (PFS.resolveForwardRefBlockAddresses())
3419 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
3421 // We need at least one basic block.
3422 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
3423 return TokError("function body requires at least one basic block");
3425 while (Lex.getKind() != lltok::rbrace &&
3426 Lex.getKind() != lltok::kw_uselistorder)
3427 if (ParseBasicBlock(PFS)) return true;
3429 while (Lex.getKind() != lltok::rbrace)
3430 if (ParseUseListOrder(&PFS))
3436 // Verify function is ok.
3437 return PFS.FinishFunction();
3441 /// ::= LabelStr? Instruction*
3442 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3443 // If this basic block starts out with a name, remember it.
3445 LocTy NameLoc = Lex.getLoc();
3446 if (Lex.getKind() == lltok::LabelStr) {
3447 Name = Lex.getStrVal();
3451 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3452 if (!BB) return true;
3454 std::string NameStr;
3456 // Parse the instructions in this block until we get a terminator.
3459 // This instruction may have three possibilities for a name: a) none
3460 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3461 LocTy NameLoc = Lex.getLoc();
3465 if (Lex.getKind() == lltok::LocalVarID) {
3466 NameID = Lex.getUIntVal();
3468 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3470 } else if (Lex.getKind() == lltok::LocalVar) {
3471 NameStr = Lex.getStrVal();
3473 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3477 switch (ParseInstruction(Inst, BB, PFS)) {
3478 default: llvm_unreachable("Unknown ParseInstruction result!");
3479 case InstError: return true;
3481 BB->getInstList().push_back(Inst);
3483 // With a normal result, we check to see if the instruction is followed by
3484 // a comma and metadata.
3485 if (EatIfPresent(lltok::comma))
3486 if (ParseInstructionMetadata(Inst, &PFS))
3489 case InstExtraComma:
3490 BB->getInstList().push_back(Inst);
3492 // If the instruction parser ate an extra comma at the end of it, it
3493 // *must* be followed by metadata.
3494 if (ParseInstructionMetadata(Inst, &PFS))
3499 // Set the name on the instruction.
3500 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3501 } while (!isa<TerminatorInst>(Inst));
3506 //===----------------------------------------------------------------------===//
3507 // Instruction Parsing.
3508 //===----------------------------------------------------------------------===//
3510 /// ParseInstruction - Parse one of the many different instructions.
3512 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3513 PerFunctionState &PFS) {
3514 lltok::Kind Token = Lex.getKind();
3515 if (Token == lltok::Eof)
3516 return TokError("found end of file when expecting more instructions");
3517 LocTy Loc = Lex.getLoc();
3518 unsigned KeywordVal = Lex.getUIntVal();
3519 Lex.Lex(); // Eat the keyword.
3522 default: return Error(Loc, "expected instruction opcode");
3523 // Terminator Instructions.
3524 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3525 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3526 case lltok::kw_br: return ParseBr(Inst, PFS);
3527 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3528 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3529 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3530 case lltok::kw_resume: return ParseResume(Inst, PFS);
3531 // Binary Operators.
3535 case lltok::kw_shl: {
3536 bool NUW = EatIfPresent(lltok::kw_nuw);
3537 bool NSW = EatIfPresent(lltok::kw_nsw);
3538 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3540 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3542 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3543 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3546 case lltok::kw_fadd:
3547 case lltok::kw_fsub:
3548 case lltok::kw_fmul:
3549 case lltok::kw_fdiv:
3550 case lltok::kw_frem: {
3551 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3552 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3556 Inst->setFastMathFlags(FMF);
3560 case lltok::kw_sdiv:
3561 case lltok::kw_udiv:
3562 case lltok::kw_lshr:
3563 case lltok::kw_ashr: {
3564 bool Exact = EatIfPresent(lltok::kw_exact);
3566 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3567 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3571 case lltok::kw_urem:
3572 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3575 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3576 case lltok::kw_icmp:
3577 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3579 case lltok::kw_trunc:
3580 case lltok::kw_zext:
3581 case lltok::kw_sext:
3582 case lltok::kw_fptrunc:
3583 case lltok::kw_fpext:
3584 case lltok::kw_bitcast:
3585 case lltok::kw_addrspacecast:
3586 case lltok::kw_uitofp:
3587 case lltok::kw_sitofp:
3588 case lltok::kw_fptoui:
3589 case lltok::kw_fptosi:
3590 case lltok::kw_inttoptr:
3591 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3593 case lltok::kw_select: return ParseSelect(Inst, PFS);
3594 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3595 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3596 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3597 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3598 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3599 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3601 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3602 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3603 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3605 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3606 case lltok::kw_load: return ParseLoad(Inst, PFS);
3607 case lltok::kw_store: return ParseStore(Inst, PFS);
3608 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3609 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3610 case lltok::kw_fence: return ParseFence(Inst, PFS);
3611 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3612 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3613 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3617 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3618 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3619 if (Opc == Instruction::FCmp) {
3620 switch (Lex.getKind()) {
3621 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3622 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3623 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3624 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3625 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3626 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3627 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3628 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3629 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3630 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3631 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3632 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3633 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3634 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3635 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3636 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3637 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3640 switch (Lex.getKind()) {
3641 default: return TokError("expected icmp predicate (e.g. 'eq')");
3642 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3643 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3644 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3645 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3646 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3647 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3648 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3649 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3650 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3651 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3658 //===----------------------------------------------------------------------===//
3659 // Terminator Instructions.
3660 //===----------------------------------------------------------------------===//
3662 /// ParseRet - Parse a return instruction.
3663 /// ::= 'ret' void (',' !dbg, !1)*
3664 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3665 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3666 PerFunctionState &PFS) {
3667 SMLoc TypeLoc = Lex.getLoc();
3669 if (ParseType(Ty, true /*void allowed*/)) return true;
3671 Type *ResType = PFS.getFunction().getReturnType();
3673 if (Ty->isVoidTy()) {
3674 if (!ResType->isVoidTy())
3675 return Error(TypeLoc, "value doesn't match function result type '" +
3676 getTypeString(ResType) + "'");
3678 Inst = ReturnInst::Create(Context);
3683 if (ParseValue(Ty, RV, PFS)) return true;
3685 if (ResType != RV->getType())
3686 return Error(TypeLoc, "value doesn't match function result type '" +
3687 getTypeString(ResType) + "'");
3689 Inst = ReturnInst::Create(Context, RV);
3695 /// ::= 'br' TypeAndValue
3696 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3697 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3700 BasicBlock *Op1, *Op2;
3701 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3703 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3704 Inst = BranchInst::Create(BB);
3708 if (Op0->getType() != Type::getInt1Ty(Context))
3709 return Error(Loc, "branch condition must have 'i1' type");
3711 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3712 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3713 ParseToken(lltok::comma, "expected ',' after true destination") ||
3714 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3717 Inst = BranchInst::Create(Op1, Op2, Op0);
3723 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3725 /// ::= (TypeAndValue ',' TypeAndValue)*
3726 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3727 LocTy CondLoc, BBLoc;
3729 BasicBlock *DefaultBB;
3730 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3731 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3732 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3733 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3736 if (!Cond->getType()->isIntegerTy())
3737 return Error(CondLoc, "switch condition must have integer type");
3739 // Parse the jump table pairs.
3740 SmallPtrSet<Value*, 32> SeenCases;
3741 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3742 while (Lex.getKind() != lltok::rsquare) {
3746 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3747 ParseToken(lltok::comma, "expected ',' after case value") ||
3748 ParseTypeAndBasicBlock(DestBB, PFS))
3751 if (!SeenCases.insert(Constant).second)
3752 return Error(CondLoc, "duplicate case value in switch");
3753 if (!isa<ConstantInt>(Constant))
3754 return Error(CondLoc, "case value is not a constant integer");
3756 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3759 Lex.Lex(); // Eat the ']'.
3761 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3762 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3763 SI->addCase(Table[i].first, Table[i].second);
3770 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3771 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3774 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3775 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3776 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3779 if (!Address->getType()->isPointerTy())
3780 return Error(AddrLoc, "indirectbr address must have pointer type");
3782 // Parse the destination list.
3783 SmallVector<BasicBlock*, 16> DestList;
3785 if (Lex.getKind() != lltok::rsquare) {
3787 if (ParseTypeAndBasicBlock(DestBB, PFS))
3789 DestList.push_back(DestBB);
3791 while (EatIfPresent(lltok::comma)) {
3792 if (ParseTypeAndBasicBlock(DestBB, PFS))
3794 DestList.push_back(DestBB);
3798 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3801 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3802 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3803 IBI->addDestination(DestList[i]);
3810 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3811 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3812 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3813 LocTy CallLoc = Lex.getLoc();
3814 AttrBuilder RetAttrs, FnAttrs;
3815 std::vector<unsigned> FwdRefAttrGrps;
3818 Type *RetType = nullptr;
3821 SmallVector<ParamInfo, 16> ArgList;
3823 BasicBlock *NormalBB, *UnwindBB;
3824 if (ParseOptionalCallingConv(CC) ||
3825 ParseOptionalReturnAttrs(RetAttrs) ||
3826 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3827 ParseValID(CalleeID) ||
3828 ParseParameterList(ArgList, PFS) ||
3829 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3831 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3832 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3833 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3834 ParseTypeAndBasicBlock(UnwindBB, PFS))
3837 // If RetType is a non-function pointer type, then this is the short syntax
3838 // for the call, which means that RetType is just the return type. Infer the
3839 // rest of the function argument types from the arguments that are present.
3840 PointerType *PFTy = nullptr;
3841 FunctionType *Ty = nullptr;
3842 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3843 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3844 // Pull out the types of all of the arguments...
3845 std::vector<Type*> ParamTypes;
3846 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3847 ParamTypes.push_back(ArgList[i].V->getType());
3849 if (!FunctionType::isValidReturnType(RetType))
3850 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3852 Ty = FunctionType::get(RetType, ParamTypes, false);
3853 PFTy = PointerType::getUnqual(Ty);
3856 // Look up the callee.
3858 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3860 // Set up the Attribute for the function.
3861 SmallVector<AttributeSet, 8> Attrs;
3862 if (RetAttrs.hasAttributes())
3863 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3864 AttributeSet::ReturnIndex,
3867 SmallVector<Value*, 8> Args;
3869 // Loop through FunctionType's arguments and ensure they are specified
3870 // correctly. Also, gather any parameter attributes.
3871 FunctionType::param_iterator I = Ty->param_begin();
3872 FunctionType::param_iterator E = Ty->param_end();
3873 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3874 Type *ExpectedTy = nullptr;
3877 } else if (!Ty->isVarArg()) {
3878 return Error(ArgList[i].Loc, "too many arguments specified");
3881 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3882 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3883 getTypeString(ExpectedTy) + "'");
3884 Args.push_back(ArgList[i].V);
3885 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3886 AttrBuilder B(ArgList[i].Attrs, i + 1);
3887 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3892 return Error(CallLoc, "not enough parameters specified for call");
3894 if (FnAttrs.hasAttributes())
3895 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3896 AttributeSet::FunctionIndex,
3899 // Finish off the Attribute and check them
3900 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3902 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3903 II->setCallingConv(CC);
3904 II->setAttributes(PAL);
3905 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3911 /// ::= 'resume' TypeAndValue
3912 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3913 Value *Exn; LocTy ExnLoc;
3914 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3917 ResumeInst *RI = ResumeInst::Create(Exn);
3922 //===----------------------------------------------------------------------===//
3923 // Binary Operators.
3924 //===----------------------------------------------------------------------===//
3927 /// ::= ArithmeticOps TypeAndValue ',' Value
3929 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3930 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3931 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3932 unsigned Opc, unsigned OperandType) {
3933 LocTy Loc; Value *LHS, *RHS;
3934 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3935 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3936 ParseValue(LHS->getType(), RHS, PFS))
3940 switch (OperandType) {
3941 default: llvm_unreachable("Unknown operand type!");
3942 case 0: // int or FP.
3943 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3944 LHS->getType()->isFPOrFPVectorTy();
3946 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3947 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3951 return Error(Loc, "invalid operand type for instruction");
3953 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3958 /// ::= ArithmeticOps TypeAndValue ',' Value {
3959 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3961 LocTy Loc; Value *LHS, *RHS;
3962 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3963 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3964 ParseValue(LHS->getType(), RHS, PFS))
3967 if (!LHS->getType()->isIntOrIntVectorTy())
3968 return Error(Loc,"instruction requires integer or integer vector operands");
3970 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3976 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3977 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3978 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3980 // Parse the integer/fp comparison predicate.
3984 if (ParseCmpPredicate(Pred, Opc) ||
3985 ParseTypeAndValue(LHS, Loc, PFS) ||
3986 ParseToken(lltok::comma, "expected ',' after compare value") ||
3987 ParseValue(LHS->getType(), RHS, PFS))
3990 if (Opc == Instruction::FCmp) {
3991 if (!LHS->getType()->isFPOrFPVectorTy())
3992 return Error(Loc, "fcmp requires floating point operands");
3993 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3995 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3996 if (!LHS->getType()->isIntOrIntVectorTy() &&
3997 !LHS->getType()->getScalarType()->isPointerTy())
3998 return Error(Loc, "icmp requires integer operands");
3999 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4004 //===----------------------------------------------------------------------===//
4005 // Other Instructions.
4006 //===----------------------------------------------------------------------===//
4010 /// ::= CastOpc TypeAndValue 'to' Type
4011 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4015 Type *DestTy = nullptr;
4016 if (ParseTypeAndValue(Op, Loc, PFS) ||
4017 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4021 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4022 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
4023 return Error(Loc, "invalid cast opcode for cast from '" +
4024 getTypeString(Op->getType()) + "' to '" +
4025 getTypeString(DestTy) + "'");
4027 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4032 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4033 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4035 Value *Op0, *Op1, *Op2;
4036 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4037 ParseToken(lltok::comma, "expected ',' after select condition") ||
4038 ParseTypeAndValue(Op1, PFS) ||
4039 ParseToken(lltok::comma, "expected ',' after select value") ||
4040 ParseTypeAndValue(Op2, PFS))
4043 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4044 return Error(Loc, Reason);
4046 Inst = SelectInst::Create(Op0, Op1, Op2);
4051 /// ::= 'va_arg' TypeAndValue ',' Type
4052 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
4054 Type *EltTy = nullptr;
4056 if (ParseTypeAndValue(Op, PFS) ||
4057 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
4058 ParseType(EltTy, TypeLoc))
4061 if (!EltTy->isFirstClassType())
4062 return Error(TypeLoc, "va_arg requires operand with first class type");
4064 Inst = new VAArgInst(Op, EltTy);
4068 /// ParseExtractElement
4069 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4070 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4073 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4074 ParseToken(lltok::comma, "expected ',' after extract value") ||
4075 ParseTypeAndValue(Op1, PFS))
4078 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4079 return Error(Loc, "invalid extractelement operands");
4081 Inst = ExtractElementInst::Create(Op0, Op1);
4085 /// ParseInsertElement
4086 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4087 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4089 Value *Op0, *Op1, *Op2;
4090 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4091 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4092 ParseTypeAndValue(Op1, PFS) ||
4093 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4094 ParseTypeAndValue(Op2, PFS))
4097 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
4098 return Error(Loc, "invalid insertelement operands");
4100 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4104 /// ParseShuffleVector
4105 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4106 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4108 Value *Op0, *Op1, *Op2;
4109 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4110 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4111 ParseTypeAndValue(Op1, PFS) ||
4112 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4113 ParseTypeAndValue(Op2, PFS))
4116 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
4117 return Error(Loc, "invalid shufflevector operands");
4119 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4124 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
4125 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
4126 Type *Ty = nullptr; LocTy TypeLoc;
4129 if (ParseType(Ty, TypeLoc) ||
4130 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4131 ParseValue(Ty, Op0, PFS) ||
4132 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4133 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4134 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4137 bool AteExtraComma = false;
4138 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4140 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
4142 if (!EatIfPresent(lltok::comma))
4145 if (Lex.getKind() == lltok::MetadataVar) {
4146 AteExtraComma = true;
4150 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4151 ParseValue(Ty, Op0, PFS) ||
4152 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4153 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4154 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4158 if (!Ty->isFirstClassType())
4159 return Error(TypeLoc, "phi node must have first class type");
4161 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
4162 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4163 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4165 return AteExtraComma ? InstExtraComma : InstNormal;
4169 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4171 /// ::= 'catch' TypeAndValue
4173 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4174 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
4175 Type *Ty = nullptr; LocTy TyLoc;
4176 Value *PersFn; LocTy PersFnLoc;
4178 if (ParseType(Ty, TyLoc) ||
4179 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4180 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4183 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4184 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4186 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4187 LandingPadInst::ClauseType CT;
4188 if (EatIfPresent(lltok::kw_catch))
4189 CT = LandingPadInst::Catch;
4190 else if (EatIfPresent(lltok::kw_filter))
4191 CT = LandingPadInst::Filter;
4193 return TokError("expected 'catch' or 'filter' clause type");
4197 if (ParseTypeAndValue(V, VLoc, PFS)) {
4202 // A 'catch' type expects a non-array constant. A filter clause expects an
4204 if (CT == LandingPadInst::Catch) {
4205 if (isa<ArrayType>(V->getType()))
4206 Error(VLoc, "'catch' clause has an invalid type");
4208 if (!isa<ArrayType>(V->getType()))
4209 Error(VLoc, "'filter' clause has an invalid type");
4212 LP->addClause(cast<Constant>(V));
4220 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4221 /// ParameterList OptionalAttrs
4222 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4223 /// ParameterList OptionalAttrs
4224 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4225 /// ParameterList OptionalAttrs
4226 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4227 CallInst::TailCallKind TCK) {
4228 AttrBuilder RetAttrs, FnAttrs;
4229 std::vector<unsigned> FwdRefAttrGrps;
4232 Type *RetType = nullptr;
4235 SmallVector<ParamInfo, 16> ArgList;
4236 LocTy CallLoc = Lex.getLoc();
4238 if ((TCK != CallInst::TCK_None &&
4239 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4240 ParseOptionalCallingConv(CC) ||
4241 ParseOptionalReturnAttrs(RetAttrs) ||
4242 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4243 ParseValID(CalleeID) ||
4244 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
4245 PFS.getFunction().isVarArg()) ||
4246 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4250 // If RetType is a non-function pointer type, then this is the short syntax
4251 // for the call, which means that RetType is just the return type. Infer the
4252 // rest of the function argument types from the arguments that are present.
4253 PointerType *PFTy = nullptr;
4254 FunctionType *Ty = nullptr;
4255 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4256 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4257 // Pull out the types of all of the arguments...
4258 std::vector<Type*> ParamTypes;
4259 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4260 ParamTypes.push_back(ArgList[i].V->getType());
4262 if (!FunctionType::isValidReturnType(RetType))
4263 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4265 Ty = FunctionType::get(RetType, ParamTypes, false);
4266 PFTy = PointerType::getUnqual(Ty);
4269 // Look up the callee.
4271 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4273 // Set up the Attribute for the function.
4274 SmallVector<AttributeSet, 8> Attrs;
4275 if (RetAttrs.hasAttributes())
4276 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4277 AttributeSet::ReturnIndex,
4280 SmallVector<Value*, 8> Args;
4282 // Loop through FunctionType's arguments and ensure they are specified
4283 // correctly. Also, gather any parameter attributes.
4284 FunctionType::param_iterator I = Ty->param_begin();
4285 FunctionType::param_iterator E = Ty->param_end();
4286 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4287 Type *ExpectedTy = nullptr;
4290 } else if (!Ty->isVarArg()) {
4291 return Error(ArgList[i].Loc, "too many arguments specified");
4294 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4295 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4296 getTypeString(ExpectedTy) + "'");
4297 Args.push_back(ArgList[i].V);
4298 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4299 AttrBuilder B(ArgList[i].Attrs, i + 1);
4300 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4305 return Error(CallLoc, "not enough parameters specified for call");
4307 if (FnAttrs.hasAttributes())
4308 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4309 AttributeSet::FunctionIndex,
4312 // Finish off the Attribute and check them
4313 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4315 CallInst *CI = CallInst::Create(Callee, Args);
4316 CI->setTailCallKind(TCK);
4317 CI->setCallingConv(CC);
4318 CI->setAttributes(PAL);
4319 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4324 //===----------------------------------------------------------------------===//
4325 // Memory Instructions.
4326 //===----------------------------------------------------------------------===//
4329 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4330 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4331 Value *Size = nullptr;
4333 unsigned Alignment = 0;
4336 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4338 if (ParseType(Ty)) return true;
4340 bool AteExtraComma = false;
4341 if (EatIfPresent(lltok::comma)) {
4342 if (Lex.getKind() == lltok::kw_align) {
4343 if (ParseOptionalAlignment(Alignment)) return true;
4344 } else if (Lex.getKind() == lltok::MetadataVar) {
4345 AteExtraComma = true;
4347 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4348 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4353 if (Size && !Size->getType()->isIntegerTy())
4354 return Error(SizeLoc, "element count must have integer type");
4356 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4357 AI->setUsedWithInAlloca(IsInAlloca);
4359 return AteExtraComma ? InstExtraComma : InstNormal;
4363 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4364 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4365 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4366 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4367 Value *Val; LocTy Loc;
4368 unsigned Alignment = 0;
4369 bool AteExtraComma = false;
4370 bool isAtomic = false;
4371 AtomicOrdering Ordering = NotAtomic;
4372 SynchronizationScope Scope = CrossThread;
4374 if (Lex.getKind() == lltok::kw_atomic) {
4379 bool isVolatile = false;
4380 if (Lex.getKind() == lltok::kw_volatile) {
4385 if (ParseTypeAndValue(Val, Loc, PFS) ||
4386 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4387 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4390 if (!Val->getType()->isPointerTy() ||
4391 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4392 return Error(Loc, "load operand must be a pointer to a first class type");
4393 if (isAtomic && !Alignment)
4394 return Error(Loc, "atomic load must have explicit non-zero alignment");
4395 if (Ordering == Release || Ordering == AcquireRelease)
4396 return Error(Loc, "atomic load cannot use Release ordering");
4398 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4399 return AteExtraComma ? InstExtraComma : InstNormal;
4404 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4405 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4406 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4407 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4408 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4409 unsigned Alignment = 0;
4410 bool AteExtraComma = false;
4411 bool isAtomic = false;
4412 AtomicOrdering Ordering = NotAtomic;
4413 SynchronizationScope Scope = CrossThread;
4415 if (Lex.getKind() == lltok::kw_atomic) {
4420 bool isVolatile = false;
4421 if (Lex.getKind() == lltok::kw_volatile) {
4426 if (ParseTypeAndValue(Val, Loc, PFS) ||
4427 ParseToken(lltok::comma, "expected ',' after store operand") ||
4428 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4429 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4430 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4433 if (!Ptr->getType()->isPointerTy())
4434 return Error(PtrLoc, "store operand must be a pointer");
4435 if (!Val->getType()->isFirstClassType())
4436 return Error(Loc, "store operand must be a first class value");
4437 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4438 return Error(Loc, "stored value and pointer type do not match");
4439 if (isAtomic && !Alignment)
4440 return Error(Loc, "atomic store must have explicit non-zero alignment");
4441 if (Ordering == Acquire || Ordering == AcquireRelease)
4442 return Error(Loc, "atomic store cannot use Acquire ordering");
4444 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4445 return AteExtraComma ? InstExtraComma : InstNormal;
4449 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4450 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
4451 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4452 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4453 bool AteExtraComma = false;
4454 AtomicOrdering SuccessOrdering = NotAtomic;
4455 AtomicOrdering FailureOrdering = NotAtomic;
4456 SynchronizationScope Scope = CrossThread;
4457 bool isVolatile = false;
4458 bool isWeak = false;
4460 if (EatIfPresent(lltok::kw_weak))
4463 if (EatIfPresent(lltok::kw_volatile))
4466 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4467 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4468 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4469 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4470 ParseTypeAndValue(New, NewLoc, PFS) ||
4471 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4472 ParseOrdering(FailureOrdering))
4475 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4476 return TokError("cmpxchg cannot be unordered");
4477 if (SuccessOrdering < FailureOrdering)
4478 return TokError("cmpxchg must be at least as ordered on success as failure");
4479 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4480 return TokError("cmpxchg failure ordering cannot include release semantics");
4481 if (!Ptr->getType()->isPointerTy())
4482 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4483 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4484 return Error(CmpLoc, "compare value and pointer type do not match");
4485 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4486 return Error(NewLoc, "new value and pointer type do not match");
4487 if (!New->getType()->isIntegerTy())
4488 return Error(NewLoc, "cmpxchg operand must be an integer");
4489 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4490 if (Size < 8 || (Size & (Size - 1)))
4491 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4494 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4495 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
4496 CXI->setVolatile(isVolatile);
4497 CXI->setWeak(isWeak);
4499 return AteExtraComma ? InstExtraComma : InstNormal;
4503 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4504 /// 'singlethread'? AtomicOrdering
4505 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4506 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4507 bool AteExtraComma = false;
4508 AtomicOrdering Ordering = NotAtomic;
4509 SynchronizationScope Scope = CrossThread;
4510 bool isVolatile = false;
4511 AtomicRMWInst::BinOp Operation;
4513 if (EatIfPresent(lltok::kw_volatile))
4516 switch (Lex.getKind()) {
4517 default: return TokError("expected binary operation in atomicrmw");
4518 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4519 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4520 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4521 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4522 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4523 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4524 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4525 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4526 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4527 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4528 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4530 Lex.Lex(); // Eat the operation.
4532 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4533 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4534 ParseTypeAndValue(Val, ValLoc, PFS) ||
4535 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4538 if (Ordering == Unordered)
4539 return TokError("atomicrmw cannot be unordered");
4540 if (!Ptr->getType()->isPointerTy())
4541 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4542 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4543 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4544 if (!Val->getType()->isIntegerTy())
4545 return Error(ValLoc, "atomicrmw operand must be an integer");
4546 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4547 if (Size < 8 || (Size & (Size - 1)))
4548 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4551 AtomicRMWInst *RMWI =
4552 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4553 RMWI->setVolatile(isVolatile);
4555 return AteExtraComma ? InstExtraComma : InstNormal;
4559 /// ::= 'fence' 'singlethread'? AtomicOrdering
4560 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4561 AtomicOrdering Ordering = NotAtomic;
4562 SynchronizationScope Scope = CrossThread;
4563 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4566 if (Ordering == Unordered)
4567 return TokError("fence cannot be unordered");
4568 if (Ordering == Monotonic)
4569 return TokError("fence cannot be monotonic");
4571 Inst = new FenceInst(Context, Ordering, Scope);
4575 /// ParseGetElementPtr
4576 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4577 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4578 Value *Ptr = nullptr;
4579 Value *Val = nullptr;
4582 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4584 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4586 Type *BaseType = Ptr->getType();
4587 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4588 if (!BasePointerType)
4589 return Error(Loc, "base of getelementptr must be a pointer");
4591 SmallVector<Value*, 16> Indices;
4592 bool AteExtraComma = false;
4593 while (EatIfPresent(lltok::comma)) {
4594 if (Lex.getKind() == lltok::MetadataVar) {
4595 AteExtraComma = true;
4598 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4599 if (!Val->getType()->getScalarType()->isIntegerTy())
4600 return Error(EltLoc, "getelementptr index must be an integer");
4601 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4602 return Error(EltLoc, "getelementptr index type missmatch");
4603 if (Val->getType()->isVectorTy()) {
4604 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4605 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4606 if (ValNumEl != PtrNumEl)
4607 return Error(EltLoc,
4608 "getelementptr vector index has a wrong number of elements");
4610 Indices.push_back(Val);
4613 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4614 return Error(Loc, "base element of getelementptr must be sized");
4616 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4617 return Error(Loc, "invalid getelementptr indices");
4618 Inst = GetElementPtrInst::Create(Ptr, Indices);
4620 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4621 return AteExtraComma ? InstExtraComma : InstNormal;
4624 /// ParseExtractValue
4625 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4626 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4627 Value *Val; LocTy Loc;
4628 SmallVector<unsigned, 4> Indices;
4630 if (ParseTypeAndValue(Val, Loc, PFS) ||
4631 ParseIndexList(Indices, AteExtraComma))
4634 if (!Val->getType()->isAggregateType())
4635 return Error(Loc, "extractvalue operand must be aggregate type");
4637 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4638 return Error(Loc, "invalid indices for extractvalue");
4639 Inst = ExtractValueInst::Create(Val, Indices);
4640 return AteExtraComma ? InstExtraComma : InstNormal;
4643 /// ParseInsertValue
4644 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4645 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4646 Value *Val0, *Val1; LocTy Loc0, Loc1;
4647 SmallVector<unsigned, 4> Indices;
4649 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4650 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4651 ParseTypeAndValue(Val1, Loc1, PFS) ||
4652 ParseIndexList(Indices, AteExtraComma))
4655 if (!Val0->getType()->isAggregateType())
4656 return Error(Loc0, "insertvalue operand must be aggregate type");
4658 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4659 return Error(Loc0, "invalid indices for insertvalue");
4660 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4661 return AteExtraComma ? InstExtraComma : InstNormal;
4664 //===----------------------------------------------------------------------===//
4665 // Embedded metadata.
4666 //===----------------------------------------------------------------------===//
4668 /// ParseMDNodeVector
4669 /// ::= Element (',' Element)*
4671 /// ::= 'null' | TypeAndValue
4672 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4673 PerFunctionState *PFS) {
4674 // Check for an empty list.
4675 if (Lex.getKind() == lltok::rbrace)
4678 bool IsLocal = false;
4681 return TokError("unexpected operand after function-local metadata");
4683 // Null is a special case since it is typeless.
4684 if (EatIfPresent(lltok::kw_null)) {
4685 Elts.push_back(nullptr);
4690 if (ParseTypeAndValue(V, PFS)) return true;
4693 if (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal())
4694 return TokError("unexpected nested function-local metadata");
4695 if (!V->getType()->isMetadataTy() && !isa<Constant>(V)) {
4696 assert(PFS && "Unexpected function-local metadata without PFS");
4697 if (Elts.size() > 1)
4698 return TokError("unexpected function-local metadata");
4701 } while (EatIfPresent(lltok::comma));
4706 //===----------------------------------------------------------------------===//
4707 // Use-list order directives.
4708 //===----------------------------------------------------------------------===//
4709 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
4712 return Error(Loc, "value has no uses");
4714 unsigned NumUses = 0;
4715 SmallDenseMap<const Use *, unsigned, 16> Order;
4716 for (const Use &U : V->uses()) {
4717 if (++NumUses > Indexes.size())
4719 Order[&U] = Indexes[NumUses - 1];
4722 return Error(Loc, "value only has one use");
4723 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
4724 return Error(Loc, "wrong number of indexes, expected " +
4725 Twine(std::distance(V->use_begin(), V->use_end())));
4727 V->sortUseList([&](const Use &L, const Use &R) {
4728 return Order.lookup(&L) < Order.lookup(&R);
4733 /// ParseUseListOrderIndexes
4734 /// ::= '{' uint32 (',' uint32)+ '}'
4735 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
4736 SMLoc Loc = Lex.getLoc();
4737 if (ParseToken(lltok::lbrace, "expected '{' here"))
4739 if (Lex.getKind() == lltok::rbrace)
4740 return Lex.Error("expected non-empty list of uselistorder indexes");
4742 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
4743 // indexes should be distinct numbers in the range [0, size-1], and should
4745 unsigned Offset = 0;
4747 bool IsOrdered = true;
4748 assert(Indexes.empty() && "Expected empty order vector");
4751 if (ParseUInt32(Index))
4754 // Update consistency checks.
4755 Offset += Index - Indexes.size();
4756 Max = std::max(Max, Index);
4757 IsOrdered &= Index == Indexes.size();
4759 Indexes.push_back(Index);
4760 } while (EatIfPresent(lltok::comma));
4762 if (ParseToken(lltok::rbrace, "expected '}' here"))
4765 if (Indexes.size() < 2)
4766 return Error(Loc, "expected >= 2 uselistorder indexes");
4767 if (Offset != 0 || Max >= Indexes.size())
4768 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
4770 return Error(Loc, "expected uselistorder indexes to change the order");
4775 /// ParseUseListOrder
4776 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
4777 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
4778 SMLoc Loc = Lex.getLoc();
4779 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
4783 SmallVector<unsigned, 16> Indexes;
4784 if (ParseTypeAndValue(V, PFS) ||
4785 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
4786 ParseUseListOrderIndexes(Indexes))
4789 return sortUseListOrder(V, Indexes, Loc);
4792 /// ParseUseListOrderBB
4793 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
4794 bool LLParser::ParseUseListOrderBB() {
4795 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
4796 SMLoc Loc = Lex.getLoc();
4800 SmallVector<unsigned, 16> Indexes;
4801 if (ParseValID(Fn) ||
4802 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4803 ParseValID(Label) ||
4804 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4805 ParseUseListOrderIndexes(Indexes))
4808 // Check the function.
4810 if (Fn.Kind == ValID::t_GlobalName)
4811 GV = M->getNamedValue(Fn.StrVal);
4812 else if (Fn.Kind == ValID::t_GlobalID)
4813 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
4815 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4817 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
4818 auto *F = dyn_cast<Function>(GV);
4820 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4821 if (F->isDeclaration())
4822 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
4824 // Check the basic block.
4825 if (Label.Kind == ValID::t_LocalID)
4826 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
4827 if (Label.Kind != ValID::t_LocalName)
4828 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
4829 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
4831 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
4832 if (!isa<BasicBlock>(V))
4833 return Error(Label.Loc, "expected basic block in uselistorder_bb");
4835 return sortUseListOrder(V, Indexes, Loc);