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/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/Module.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/IR/ValueSymbolTable.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
29 static std::string getTypeString(Type *T) {
31 raw_string_ostream Tmp(Result);
36 /// Run: module ::= toplevelentity*
37 bool LLParser::Run() {
41 return ParseTopLevelEntities() ||
42 ValidateEndOfModule();
45 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
47 bool LLParser::ValidateEndOfModule() {
48 // Handle any instruction metadata forward references.
49 if (!ForwardRefInstMetadata.empty()) {
50 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
51 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
53 Instruction *Inst = I->first;
54 const std::vector<MDRef> &MDList = I->second;
56 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
59 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60 return Error(MDList[i].Loc, "use of undefined metadata '!" +
62 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
65 ForwardRefInstMetadata.clear();
69 // If there are entries in ForwardRefBlockAddresses at this point, they are
70 // references after the function was defined. Resolve those now.
71 while (!ForwardRefBlockAddresses.empty()) {
72 // Okay, we are referencing an already-parsed function, resolve them now.
74 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
75 if (Fn.Kind == ValID::t_GlobalName)
76 TheFn = M->getFunction(Fn.StrVal);
77 else if (Fn.UIntVal < NumberedVals.size())
78 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
81 return Error(Fn.Loc, "unknown function referenced by blockaddress");
83 // Resolve all these references.
84 if (ResolveForwardRefBlockAddresses(TheFn,
85 ForwardRefBlockAddresses.begin()->second,
89 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
92 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
93 if (NumberedTypes[i].second.isValid())
94 return Error(NumberedTypes[i].second,
95 "use of undefined type '%" + Twine(i) + "'");
97 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
98 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
99 if (I->second.second.isValid())
100 return Error(I->second.second,
101 "use of undefined type named '" + I->getKey() + "'");
103 if (!ForwardRefVals.empty())
104 return Error(ForwardRefVals.begin()->second.second,
105 "use of undefined value '@" + ForwardRefVals.begin()->first +
108 if (!ForwardRefValIDs.empty())
109 return Error(ForwardRefValIDs.begin()->second.second,
110 "use of undefined value '@" +
111 Twine(ForwardRefValIDs.begin()->first) + "'");
113 if (!ForwardRefMDNodes.empty())
114 return Error(ForwardRefMDNodes.begin()->second.second,
115 "use of undefined metadata '!" +
116 Twine(ForwardRefMDNodes.begin()->first) + "'");
119 // Look for intrinsic functions and CallInst that need to be upgraded
120 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
121 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
126 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
127 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
128 PerFunctionState *PFS) {
129 // Loop over all the references, resolving them.
130 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
133 if (Refs[i].first.Kind == ValID::t_LocalName)
134 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
136 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
137 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
138 return Error(Refs[i].first.Loc,
139 "cannot take address of numeric label after the function is defined");
141 Res = dyn_cast_or_null<BasicBlock>(
142 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
146 return Error(Refs[i].first.Loc,
147 "referenced value is not a basic block");
149 // Get the BlockAddress for this and update references to use it.
150 BlockAddress *BA = BlockAddress::get(TheFn, Res);
151 Refs[i].second->replaceAllUsesWith(BA);
152 Refs[i].second->eraseFromParent();
158 //===----------------------------------------------------------------------===//
159 // Top-Level Entities
160 //===----------------------------------------------------------------------===//
162 bool LLParser::ParseTopLevelEntities() {
164 switch (Lex.getKind()) {
165 default: return TokError("expected top-level entity");
166 case lltok::Eof: return false;
167 case lltok::kw_declare: if (ParseDeclare()) return true; break;
168 case lltok::kw_define: if (ParseDefine()) return true; break;
169 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
170 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
171 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
172 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
173 case lltok::LocalVar: if (ParseNamedType()) return true; break;
174 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
175 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
176 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
177 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
178 case lltok::AttrGrpID: if (ParseUnnamedAttrGrp()) return true; break;
180 // The Global variable production with no name can have many different
181 // optional leading prefixes, the production is:
182 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
183 // OptionalAddrSpace OptionalUnNammedAddr
184 // ('constant'|'global') ...
185 case lltok::kw_private: // OptionalLinkage
186 case lltok::kw_linker_private: // OptionalLinkage
187 case lltok::kw_linker_private_weak: // OptionalLinkage
188 case lltok::kw_linker_private_weak_def_auto: // FIXME: backwards compat.
189 case lltok::kw_internal: // OptionalLinkage
190 case lltok::kw_weak: // OptionalLinkage
191 case lltok::kw_weak_odr: // OptionalLinkage
192 case lltok::kw_linkonce: // OptionalLinkage
193 case lltok::kw_linkonce_odr: // OptionalLinkage
194 case lltok::kw_linkonce_odr_auto_hide: // OptionalLinkage
195 case lltok::kw_appending: // OptionalLinkage
196 case lltok::kw_dllexport: // OptionalLinkage
197 case lltok::kw_common: // OptionalLinkage
198 case lltok::kw_dllimport: // OptionalLinkage
199 case lltok::kw_extern_weak: // OptionalLinkage
200 case lltok::kw_external: { // OptionalLinkage
201 unsigned Linkage, Visibility;
202 if (ParseOptionalLinkage(Linkage) ||
203 ParseOptionalVisibility(Visibility) ||
204 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
208 case lltok::kw_default: // OptionalVisibility
209 case lltok::kw_hidden: // OptionalVisibility
210 case lltok::kw_protected: { // OptionalVisibility
212 if (ParseOptionalVisibility(Visibility) ||
213 ParseGlobal("", SMLoc(), 0, false, Visibility))
218 case lltok::kw_thread_local: // OptionalThreadLocal
219 case lltok::kw_addrspace: // OptionalAddrSpace
220 case lltok::kw_constant: // GlobalType
221 case lltok::kw_global: // GlobalType
222 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
230 /// ::= 'module' 'asm' STRINGCONSTANT
231 bool LLParser::ParseModuleAsm() {
232 assert(Lex.getKind() == lltok::kw_module);
236 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
237 ParseStringConstant(AsmStr)) return true;
239 M->appendModuleInlineAsm(AsmStr);
244 /// ::= 'target' 'triple' '=' STRINGCONSTANT
245 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
246 bool LLParser::ParseTargetDefinition() {
247 assert(Lex.getKind() == lltok::kw_target);
250 default: return TokError("unknown target property");
251 case lltok::kw_triple:
253 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
254 ParseStringConstant(Str))
256 M->setTargetTriple(Str);
258 case lltok::kw_datalayout:
260 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
261 ParseStringConstant(Str))
263 M->setDataLayout(Str);
269 /// ::= 'deplibs' '=' '[' ']'
270 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
271 /// FIXME: Remove in 4.0. Currently parse, but ignore.
272 bool LLParser::ParseDepLibs() {
273 assert(Lex.getKind() == lltok::kw_deplibs);
275 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
276 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
279 if (EatIfPresent(lltok::rsquare))
284 if (ParseStringConstant(Str)) return true;
285 } while (EatIfPresent(lltok::comma));
287 return ParseToken(lltok::rsquare, "expected ']' at end of list");
290 /// ParseUnnamedType:
291 /// ::= LocalVarID '=' 'type' type
292 bool LLParser::ParseUnnamedType() {
293 LocTy TypeLoc = Lex.getLoc();
294 unsigned TypeID = Lex.getUIntVal();
295 Lex.Lex(); // eat LocalVarID;
297 if (ParseToken(lltok::equal, "expected '=' after name") ||
298 ParseToken(lltok::kw_type, "expected 'type' after '='"))
301 if (TypeID >= NumberedTypes.size())
302 NumberedTypes.resize(TypeID+1);
305 if (ParseStructDefinition(TypeLoc, "",
306 NumberedTypes[TypeID], Result)) return true;
308 if (!isa<StructType>(Result)) {
309 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
311 return Error(TypeLoc, "non-struct types may not be recursive");
312 Entry.first = Result;
313 Entry.second = SMLoc();
321 /// ::= LocalVar '=' 'type' type
322 bool LLParser::ParseNamedType() {
323 std::string Name = Lex.getStrVal();
324 LocTy NameLoc = Lex.getLoc();
325 Lex.Lex(); // eat LocalVar.
327 if (ParseToken(lltok::equal, "expected '=' after name") ||
328 ParseToken(lltok::kw_type, "expected 'type' after name"))
332 if (ParseStructDefinition(NameLoc, Name,
333 NamedTypes[Name], Result)) return true;
335 if (!isa<StructType>(Result)) {
336 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
338 return Error(NameLoc, "non-struct types may not be recursive");
339 Entry.first = Result;
340 Entry.second = SMLoc();
348 /// ::= 'declare' FunctionHeader
349 bool LLParser::ParseDeclare() {
350 assert(Lex.getKind() == lltok::kw_declare);
354 return ParseFunctionHeader(F, false);
358 /// ::= 'define' FunctionHeader '{' ...
359 bool LLParser::ParseDefine() {
360 assert(Lex.getKind() == lltok::kw_define);
364 return ParseFunctionHeader(F, true) ||
365 ParseFunctionBody(*F);
371 bool LLParser::ParseGlobalType(bool &IsConstant) {
372 if (Lex.getKind() == lltok::kw_constant)
374 else if (Lex.getKind() == lltok::kw_global)
378 return TokError("expected 'global' or 'constant'");
384 /// ParseUnnamedGlobal:
385 /// OptionalVisibility ALIAS ...
386 /// OptionalLinkage OptionalVisibility ... -> global variable
387 /// GlobalID '=' OptionalVisibility ALIAS ...
388 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
389 bool LLParser::ParseUnnamedGlobal() {
390 unsigned VarID = NumberedVals.size();
392 LocTy NameLoc = Lex.getLoc();
394 // Handle the GlobalID form.
395 if (Lex.getKind() == lltok::GlobalID) {
396 if (Lex.getUIntVal() != VarID)
397 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
399 Lex.Lex(); // eat GlobalID;
401 if (ParseToken(lltok::equal, "expected '=' after name"))
406 unsigned Linkage, Visibility;
407 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
408 ParseOptionalVisibility(Visibility))
411 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
412 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
413 return ParseAlias(Name, NameLoc, Visibility);
416 /// ParseNamedGlobal:
417 /// GlobalVar '=' OptionalVisibility ALIAS ...
418 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
419 bool LLParser::ParseNamedGlobal() {
420 assert(Lex.getKind() == lltok::GlobalVar);
421 LocTy NameLoc = Lex.getLoc();
422 std::string Name = Lex.getStrVal();
426 unsigned Linkage, Visibility;
427 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
428 ParseOptionalLinkage(Linkage, HasLinkage) ||
429 ParseOptionalVisibility(Visibility))
432 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
433 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
434 return ParseAlias(Name, NameLoc, Visibility);
438 // ::= '!' STRINGCONSTANT
439 bool LLParser::ParseMDString(MDString *&Result) {
441 if (ParseStringConstant(Str)) return true;
442 Result = MDString::get(Context, Str);
447 // ::= '!' MDNodeNumber
449 /// This version of ParseMDNodeID returns the slot number and null in the case
450 /// of a forward reference.
451 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
452 // !{ ..., !42, ... }
453 if (ParseUInt32(SlotNo)) return true;
455 // Check existing MDNode.
456 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
457 Result = NumberedMetadata[SlotNo];
463 bool LLParser::ParseMDNodeID(MDNode *&Result) {
464 // !{ ..., !42, ... }
466 if (ParseMDNodeID(Result, MID)) return true;
468 // If not a forward reference, just return it now.
469 if (Result) return false;
471 // Otherwise, create MDNode forward reference.
472 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
473 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
475 if (NumberedMetadata.size() <= MID)
476 NumberedMetadata.resize(MID+1);
477 NumberedMetadata[MID] = FwdNode;
482 /// ParseNamedMetadata:
483 /// !foo = !{ !1, !2 }
484 bool LLParser::ParseNamedMetadata() {
485 assert(Lex.getKind() == lltok::MetadataVar);
486 std::string Name = Lex.getStrVal();
489 if (ParseToken(lltok::equal, "expected '=' here") ||
490 ParseToken(lltok::exclaim, "Expected '!' here") ||
491 ParseToken(lltok::lbrace, "Expected '{' here"))
494 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
495 if (Lex.getKind() != lltok::rbrace)
497 if (ParseToken(lltok::exclaim, "Expected '!' here"))
501 if (ParseMDNodeID(N)) return true;
503 } while (EatIfPresent(lltok::comma));
505 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
511 /// ParseStandaloneMetadata:
513 bool LLParser::ParseStandaloneMetadata() {
514 assert(Lex.getKind() == lltok::exclaim);
516 unsigned MetadataID = 0;
520 SmallVector<Value *, 16> Elts;
521 if (ParseUInt32(MetadataID) ||
522 ParseToken(lltok::equal, "expected '=' here") ||
523 ParseType(Ty, TyLoc) ||
524 ParseToken(lltok::exclaim, "Expected '!' here") ||
525 ParseToken(lltok::lbrace, "Expected '{' here") ||
526 ParseMDNodeVector(Elts, NULL) ||
527 ParseToken(lltok::rbrace, "expected end of metadata node"))
530 MDNode *Init = MDNode::get(Context, Elts);
532 // See if this was forward referenced, if so, handle it.
533 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
534 FI = ForwardRefMDNodes.find(MetadataID);
535 if (FI != ForwardRefMDNodes.end()) {
536 MDNode *Temp = FI->second.first;
537 Temp->replaceAllUsesWith(Init);
538 MDNode::deleteTemporary(Temp);
539 ForwardRefMDNodes.erase(FI);
541 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
543 if (MetadataID >= NumberedMetadata.size())
544 NumberedMetadata.resize(MetadataID+1);
546 if (NumberedMetadata[MetadataID] != 0)
547 return TokError("Metadata id is already used");
548 NumberedMetadata[MetadataID] = Init;
555 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
558 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
559 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
561 /// Everything through visibility has already been parsed.
563 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
564 unsigned Visibility) {
565 assert(Lex.getKind() == lltok::kw_alias);
568 LocTy LinkageLoc = Lex.getLoc();
569 if (ParseOptionalLinkage(Linkage))
572 if (Linkage != GlobalValue::ExternalLinkage &&
573 Linkage != GlobalValue::WeakAnyLinkage &&
574 Linkage != GlobalValue::WeakODRLinkage &&
575 Linkage != GlobalValue::InternalLinkage &&
576 Linkage != GlobalValue::PrivateLinkage &&
577 Linkage != GlobalValue::LinkerPrivateLinkage &&
578 Linkage != GlobalValue::LinkerPrivateWeakLinkage)
579 return Error(LinkageLoc, "invalid linkage type for alias");
582 LocTy AliaseeLoc = Lex.getLoc();
583 if (Lex.getKind() != lltok::kw_bitcast &&
584 Lex.getKind() != lltok::kw_getelementptr) {
585 if (ParseGlobalTypeAndValue(Aliasee)) return true;
587 // The bitcast dest type is not present, it is implied by the dest type.
589 if (ParseValID(ID)) return true;
590 if (ID.Kind != ValID::t_Constant)
591 return Error(AliaseeLoc, "invalid aliasee");
592 Aliasee = ID.ConstantVal;
595 if (!Aliasee->getType()->isPointerTy())
596 return Error(AliaseeLoc, "alias must have pointer type");
598 // Okay, create the alias but do not insert it into the module yet.
599 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
600 (GlobalValue::LinkageTypes)Linkage, Name,
602 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
604 // See if this value already exists in the symbol table. If so, it is either
605 // a redefinition or a definition of a forward reference.
606 if (GlobalValue *Val = M->getNamedValue(Name)) {
607 // See if this was a redefinition. If so, there is no entry in
609 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
610 I = ForwardRefVals.find(Name);
611 if (I == ForwardRefVals.end())
612 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
614 // Otherwise, this was a definition of forward ref. Verify that types
616 if (Val->getType() != GA->getType())
617 return Error(NameLoc,
618 "forward reference and definition of alias have different types");
620 // If they agree, just RAUW the old value with the alias and remove the
622 Val->replaceAllUsesWith(GA);
623 Val->eraseFromParent();
624 ForwardRefVals.erase(I);
627 // Insert into the module, we know its name won't collide now.
628 M->getAliasList().push_back(GA);
629 assert(GA->getName() == Name && "Should not be a name conflict!");
635 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
636 /// OptionalAddrSpace OptionalUnNammedAddr
637 /// OptionalExternallyInitialized GlobalType Type Const
638 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
639 /// OptionalAddrSpace OptionalUnNammedAddr
640 /// OptionalExternallyInitialized GlobalType Type Const
642 /// Everything through visibility has been parsed already.
644 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
645 unsigned Linkage, bool HasLinkage,
646 unsigned Visibility) {
648 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
649 GlobalVariable::ThreadLocalMode TLM;
650 LocTy UnnamedAddrLoc;
651 LocTy IsExternallyInitializedLoc;
655 if (ParseOptionalThreadLocal(TLM) ||
656 ParseOptionalAddrSpace(AddrSpace) ||
657 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
659 ParseOptionalToken(lltok::kw_externally_initialized,
660 IsExternallyInitialized,
661 &IsExternallyInitializedLoc) ||
662 ParseGlobalType(IsConstant) ||
663 ParseType(Ty, TyLoc))
666 // If the linkage is specified and is external, then no initializer is
669 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
670 Linkage != GlobalValue::ExternalWeakLinkage &&
671 Linkage != GlobalValue::ExternalLinkage)) {
672 if (ParseGlobalValue(Ty, Init))
676 if (Ty->isFunctionTy() || Ty->isLabelTy())
677 return Error(TyLoc, "invalid type for global variable");
679 GlobalVariable *GV = 0;
681 // See if the global was forward referenced, if so, use the global.
683 if (GlobalValue *GVal = M->getNamedValue(Name)) {
684 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
685 return Error(NameLoc, "redefinition of global '@" + Name + "'");
686 GV = cast<GlobalVariable>(GVal);
689 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
690 I = ForwardRefValIDs.find(NumberedVals.size());
691 if (I != ForwardRefValIDs.end()) {
692 GV = cast<GlobalVariable>(I->second.first);
693 ForwardRefValIDs.erase(I);
698 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
699 Name, 0, GlobalVariable::NotThreadLocal,
702 if (GV->getType()->getElementType() != Ty)
704 "forward reference and definition of global have different types");
706 // Move the forward-reference to the correct spot in the module.
707 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
711 NumberedVals.push_back(GV);
713 // Set the parsed properties on the global.
715 GV->setInitializer(Init);
716 GV->setConstant(IsConstant);
717 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
718 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
719 GV->setExternallyInitialized(IsExternallyInitialized);
720 GV->setThreadLocalMode(TLM);
721 GV->setUnnamedAddr(UnnamedAddr);
723 // Parse attributes on the global.
724 while (Lex.getKind() == lltok::comma) {
727 if (Lex.getKind() == lltok::kw_section) {
729 GV->setSection(Lex.getStrVal());
730 if (ParseToken(lltok::StringConstant, "expected global section string"))
732 } else if (Lex.getKind() == lltok::kw_align) {
734 if (ParseOptionalAlignment(Alignment)) return true;
735 GV->setAlignment(Alignment);
737 TokError("unknown global variable property!");
744 /// ParseUnnamedAttrGrp
745 /// ::= AttrGrpID '=' '{' AttrValPair+ '}'
746 bool LLParser::ParseUnnamedAttrGrp() {
747 assert(Lex.getKind() == lltok::AttrGrpID);
748 LocTy AttrGrpLoc = Lex.getLoc();
749 unsigned VarID = Lex.getUIntVal();
752 if (ParseToken(lltok::equal, "expected '=' here") ||
753 ParseToken(lltok::kw_attributes, "expected 'attributes' keyword here") ||
754 ParseToken(lltok::lbrace, "expected '{' here") ||
755 ParseAttributeValuePairs(ForwardRefAttrBuilder[VarID]) ||
756 ParseToken(lltok::rbrace, "expected end of attribute group"))
759 if (!ForwardRefAttrBuilder[VarID].hasAttributes())
760 return Error(AttrGrpLoc, "attribute group has no attributes");
765 /// ParseAttributeValuePairs
766 /// ::= <attr> | <attr> '=' <value>
767 bool LLParser::ParseAttributeValuePairs(AttrBuilder &B) {
769 lltok::Kind Token = Lex.getKind();
772 return Error(Lex.getLoc(), "unterminated attribute group");
777 // Target-dependent attributes:
778 case lltok::StringConstant: {
779 std::string Attr = Lex.getStrVal();
782 if (EatIfPresent(lltok::equal) &&
783 ParseStringConstant(Val))
786 B.addAttribute(Attr, Val);
790 // Target-independent attributes:
791 case lltok::kw_align: {
793 if (ParseToken(lltok::equal, "expected '=' here") ||
794 ParseUInt32(Alignment))
796 B.addAlignmentAttr(Alignment);
799 case lltok::kw_alignstack: {
801 if (ParseToken(lltok::equal, "expected '=' here") ||
802 ParseUInt32(Alignment))
804 B.addStackAlignmentAttr(Alignment);
807 case lltok::kw_address_safety: B.addAttribute(Attribute::AddressSafety); break;
808 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
809 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
810 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
811 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
812 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
813 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
814 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
815 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
816 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
817 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
818 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
819 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
820 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
821 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
822 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
823 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
824 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
825 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
826 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
827 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
828 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
829 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
830 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
831 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
832 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
833 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
834 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
841 //===----------------------------------------------------------------------===//
842 // GlobalValue Reference/Resolution Routines.
843 //===----------------------------------------------------------------------===//
845 /// GetGlobalVal - Get a value with the specified name or ID, creating a
846 /// forward reference record if needed. This can return null if the value
847 /// exists but does not have the right type.
848 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
850 PointerType *PTy = dyn_cast<PointerType>(Ty);
852 Error(Loc, "global variable reference must have pointer type");
856 // Look this name up in the normal function symbol table.
858 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
860 // If this is a forward reference for the value, see if we already created a
861 // forward ref record.
863 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
864 I = ForwardRefVals.find(Name);
865 if (I != ForwardRefVals.end())
866 Val = I->second.first;
869 // If we have the value in the symbol table or fwd-ref table, return it.
871 if (Val->getType() == Ty) return Val;
872 Error(Loc, "'@" + Name + "' defined with type '" +
873 getTypeString(Val->getType()) + "'");
877 // Otherwise, create a new forward reference for this value and remember it.
879 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
880 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
882 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
883 GlobalValue::ExternalWeakLinkage, 0, Name,
884 0, GlobalVariable::NotThreadLocal,
885 PTy->getAddressSpace());
887 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
891 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
892 PointerType *PTy = dyn_cast<PointerType>(Ty);
894 Error(Loc, "global variable reference must have pointer type");
898 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
900 // If this is a forward reference for the value, see if we already created a
901 // forward ref record.
903 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
904 I = ForwardRefValIDs.find(ID);
905 if (I != ForwardRefValIDs.end())
906 Val = I->second.first;
909 // If we have the value in the symbol table or fwd-ref table, return it.
911 if (Val->getType() == Ty) return Val;
912 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
913 getTypeString(Val->getType()) + "'");
917 // Otherwise, create a new forward reference for this value and remember it.
919 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
920 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
922 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
923 GlobalValue::ExternalWeakLinkage, 0, "");
925 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
930 //===----------------------------------------------------------------------===//
932 //===----------------------------------------------------------------------===//
934 /// ParseToken - If the current token has the specified kind, eat it and return
935 /// success. Otherwise, emit the specified error and return failure.
936 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
937 if (Lex.getKind() != T)
938 return TokError(ErrMsg);
943 /// ParseStringConstant
944 /// ::= StringConstant
945 bool LLParser::ParseStringConstant(std::string &Result) {
946 if (Lex.getKind() != lltok::StringConstant)
947 return TokError("expected string constant");
948 Result = Lex.getStrVal();
955 bool LLParser::ParseUInt32(unsigned &Val) {
956 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
957 return TokError("expected integer");
958 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
959 if (Val64 != unsigned(Val64))
960 return TokError("expected 32-bit integer (too large)");
967 /// := 'localdynamic'
970 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
971 switch (Lex.getKind()) {
973 return TokError("expected localdynamic, initialexec or localexec");
974 case lltok::kw_localdynamic:
975 TLM = GlobalVariable::LocalDynamicTLSModel;
977 case lltok::kw_initialexec:
978 TLM = GlobalVariable::InitialExecTLSModel;
980 case lltok::kw_localexec:
981 TLM = GlobalVariable::LocalExecTLSModel;
989 /// ParseOptionalThreadLocal
991 /// := 'thread_local'
992 /// := 'thread_local' '(' tlsmodel ')'
993 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
994 TLM = GlobalVariable::NotThreadLocal;
995 if (!EatIfPresent(lltok::kw_thread_local))
998 TLM = GlobalVariable::GeneralDynamicTLSModel;
999 if (Lex.getKind() == lltok::lparen) {
1001 return ParseTLSModel(TLM) ||
1002 ParseToken(lltok::rparen, "expected ')' after thread local model");
1007 /// ParseOptionalAddrSpace
1009 /// := 'addrspace' '(' uint32 ')'
1010 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1012 if (!EatIfPresent(lltok::kw_addrspace))
1014 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1015 ParseUInt32(AddrSpace) ||
1016 ParseToken(lltok::rparen, "expected ')' in address space");
1019 /// ParseOptionalFuncAttrs - Parse a potentially empty list of function attributes.
1020 bool LLParser::ParseOptionalFuncAttrs(AttrBuilder &B) {
1021 bool HaveError = false;
1026 lltok::Kind Token = Lex.getKind();
1028 default: // End of attributes.
1030 case lltok::kw_alignstack: {
1032 if (ParseOptionalStackAlignment(Alignment))
1034 B.addStackAlignmentAttr(Alignment);
1037 case lltok::kw_align: {
1038 // As a hack, we allow "align 2" on functions as a synonym for "alignstack
1041 if (ParseOptionalAlignment(Alignment))
1043 B.addAlignmentAttr(Alignment);
1046 case lltok::kw_address_safety: B.addAttribute(Attribute::AddressSafety); break;
1047 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1048 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1049 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1050 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1051 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1052 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1053 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1054 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
1055 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1056 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1057 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1058 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1059 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1060 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
1061 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1062 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1063 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
1064 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1065 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1068 case lltok::kw_zeroext:
1069 case lltok::kw_signext:
1070 case lltok::kw_inreg:
1071 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on a function");
1073 case lltok::kw_sret: case lltok::kw_noalias:
1074 case lltok::kw_nocapture: case lltok::kw_byval:
1075 case lltok::kw_nest:
1077 Error(Lex.getLoc(), "invalid use of parameter-only attribute on a function");
1085 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1086 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1087 bool HaveError = false;
1092 lltok::Kind Token = Lex.getKind();
1094 default: // End of attributes.
1096 case lltok::kw_align: {
1098 if (ParseOptionalAlignment(Alignment))
1100 B.addAlignmentAttr(Alignment);
1103 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1104 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1105 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1106 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1107 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1108 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1109 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1110 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1112 case lltok::kw_noreturn: case lltok::kw_nounwind:
1113 case lltok::kw_uwtable: case lltok::kw_returns_twice:
1114 case lltok::kw_noinline: case lltok::kw_readnone:
1115 case lltok::kw_readonly: case lltok::kw_inlinehint:
1116 case lltok::kw_alwaysinline: case lltok::kw_optsize:
1117 case lltok::kw_ssp: case lltok::kw_sspreq:
1118 case lltok::kw_noredzone: case lltok::kw_noimplicitfloat:
1119 case lltok::kw_naked: case lltok::kw_nonlazybind:
1120 case lltok::kw_address_safety: case lltok::kw_minsize:
1121 case lltok::kw_alignstack:
1122 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1130 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1131 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1132 bool HaveError = false;
1137 lltok::Kind Token = Lex.getKind();
1139 default: // End of attributes.
1141 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1142 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1143 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1144 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1147 case lltok::kw_sret: case lltok::kw_nocapture:
1148 case lltok::kw_byval: case lltok::kw_nest:
1149 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1152 case lltok::kw_noreturn: case lltok::kw_nounwind:
1153 case lltok::kw_uwtable: case lltok::kw_returns_twice:
1154 case lltok::kw_noinline: case lltok::kw_readnone:
1155 case lltok::kw_readonly: case lltok::kw_inlinehint:
1156 case lltok::kw_alwaysinline: case lltok::kw_optsize:
1157 case lltok::kw_ssp: case lltok::kw_sspreq:
1158 case lltok::kw_sspstrong: case lltok::kw_noimplicitfloat:
1159 case lltok::kw_noredzone: case lltok::kw_naked:
1160 case lltok::kw_nonlazybind: case lltok::kw_address_safety:
1161 case lltok::kw_minsize: case lltok::kw_alignstack:
1162 case lltok::kw_align: case lltok::kw_noduplicate:
1163 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1171 /// ParseOptionalLinkage
1174 /// ::= 'linker_private'
1175 /// ::= 'linker_private_weak'
1180 /// ::= 'linkonce_odr'
1181 /// ::= 'linkonce_odr_auto_hide'
1182 /// ::= 'available_externally'
1187 /// ::= 'extern_weak'
1189 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1191 switch (Lex.getKind()) {
1192 default: Res=GlobalValue::ExternalLinkage; return false;
1193 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1194 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1195 case lltok::kw_linker_private_weak:
1196 Res = GlobalValue::LinkerPrivateWeakLinkage;
1198 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1199 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1200 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1201 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1202 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1203 case lltok::kw_linkonce_odr_auto_hide:
1204 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1205 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1207 case lltok::kw_available_externally:
1208 Res = GlobalValue::AvailableExternallyLinkage;
1210 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1211 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1212 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1213 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1214 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1215 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1222 /// ParseOptionalVisibility
1228 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1229 switch (Lex.getKind()) {
1230 default: Res = GlobalValue::DefaultVisibility; return false;
1231 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1232 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1233 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1239 /// ParseOptionalCallingConv
1243 /// ::= 'kw_intel_ocl_bicc'
1245 /// ::= 'x86_stdcallcc'
1246 /// ::= 'x86_fastcallcc'
1247 /// ::= 'x86_thiscallcc'
1248 /// ::= 'arm_apcscc'
1249 /// ::= 'arm_aapcscc'
1250 /// ::= 'arm_aapcs_vfpcc'
1251 /// ::= 'msp430_intrcc'
1252 /// ::= 'ptx_kernel'
1253 /// ::= 'ptx_device'
1255 /// ::= 'spir_kernel'
1258 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1259 switch (Lex.getKind()) {
1260 default: CC = CallingConv::C; return false;
1261 case lltok::kw_ccc: CC = CallingConv::C; break;
1262 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1263 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1264 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1265 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1266 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1267 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1268 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1269 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1270 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1271 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1272 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1273 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1274 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1275 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1276 case lltok::kw_cc: {
1277 unsigned ArbitraryCC;
1279 if (ParseUInt32(ArbitraryCC))
1281 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1290 /// ParseInstructionMetadata
1291 /// ::= !dbg !42 (',' !dbg !57)*
1292 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1293 PerFunctionState *PFS) {
1295 if (Lex.getKind() != lltok::MetadataVar)
1296 return TokError("expected metadata after comma");
1298 std::string Name = Lex.getStrVal();
1299 unsigned MDK = M->getMDKindID(Name);
1303 SMLoc Loc = Lex.getLoc();
1305 if (ParseToken(lltok::exclaim, "expected '!' here"))
1308 // This code is similar to that of ParseMetadataValue, however it needs to
1309 // have special-case code for a forward reference; see the comments on
1310 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1311 // at the top level here.
1312 if (Lex.getKind() == lltok::lbrace) {
1314 if (ParseMetadataListValue(ID, PFS))
1316 assert(ID.Kind == ValID::t_MDNode);
1317 Inst->setMetadata(MDK, ID.MDNodeVal);
1319 unsigned NodeID = 0;
1320 if (ParseMDNodeID(Node, NodeID))
1323 // If we got the node, add it to the instruction.
1324 Inst->setMetadata(MDK, Node);
1326 MDRef R = { Loc, MDK, NodeID };
1327 // Otherwise, remember that this should be resolved later.
1328 ForwardRefInstMetadata[Inst].push_back(R);
1332 // If this is the end of the list, we're done.
1333 } while (EatIfPresent(lltok::comma));
1337 /// ParseOptionalAlignment
1340 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1342 if (!EatIfPresent(lltok::kw_align))
1344 LocTy AlignLoc = Lex.getLoc();
1345 if (ParseUInt32(Alignment)) return true;
1346 if (!isPowerOf2_32(Alignment))
1347 return Error(AlignLoc, "alignment is not a power of two");
1348 if (Alignment > Value::MaximumAlignment)
1349 return Error(AlignLoc, "huge alignments are not supported yet");
1353 /// ParseOptionalCommaAlign
1357 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1359 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1360 bool &AteExtraComma) {
1361 AteExtraComma = false;
1362 while (EatIfPresent(lltok::comma)) {
1363 // Metadata at the end is an early exit.
1364 if (Lex.getKind() == lltok::MetadataVar) {
1365 AteExtraComma = true;
1369 if (Lex.getKind() != lltok::kw_align)
1370 return Error(Lex.getLoc(), "expected metadata or 'align'");
1372 if (ParseOptionalAlignment(Alignment)) return true;
1378 /// ParseScopeAndOrdering
1379 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1382 /// This sets Scope and Ordering to the parsed values.
1383 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1384 AtomicOrdering &Ordering) {
1388 Scope = CrossThread;
1389 if (EatIfPresent(lltok::kw_singlethread))
1390 Scope = SingleThread;
1391 switch (Lex.getKind()) {
1392 default: return TokError("Expected ordering on atomic instruction");
1393 case lltok::kw_unordered: Ordering = Unordered; break;
1394 case lltok::kw_monotonic: Ordering = Monotonic; break;
1395 case lltok::kw_acquire: Ordering = Acquire; break;
1396 case lltok::kw_release: Ordering = Release; break;
1397 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1398 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1404 /// ParseOptionalStackAlignment
1406 /// ::= 'alignstack' '(' 4 ')'
1407 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1409 if (!EatIfPresent(lltok::kw_alignstack))
1411 LocTy ParenLoc = Lex.getLoc();
1412 if (!EatIfPresent(lltok::lparen))
1413 return Error(ParenLoc, "expected '('");
1414 LocTy AlignLoc = Lex.getLoc();
1415 if (ParseUInt32(Alignment)) return true;
1416 ParenLoc = Lex.getLoc();
1417 if (!EatIfPresent(lltok::rparen))
1418 return Error(ParenLoc, "expected ')'");
1419 if (!isPowerOf2_32(Alignment))
1420 return Error(AlignLoc, "stack alignment is not a power of two");
1424 /// ParseIndexList - This parses the index list for an insert/extractvalue
1425 /// instruction. This sets AteExtraComma in the case where we eat an extra
1426 /// comma at the end of the line and find that it is followed by metadata.
1427 /// Clients that don't allow metadata can call the version of this function that
1428 /// only takes one argument.
1431 /// ::= (',' uint32)+
1433 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1434 bool &AteExtraComma) {
1435 AteExtraComma = false;
1437 if (Lex.getKind() != lltok::comma)
1438 return TokError("expected ',' as start of index list");
1440 while (EatIfPresent(lltok::comma)) {
1441 if (Lex.getKind() == lltok::MetadataVar) {
1442 AteExtraComma = true;
1446 if (ParseUInt32(Idx)) return true;
1447 Indices.push_back(Idx);
1453 //===----------------------------------------------------------------------===//
1455 //===----------------------------------------------------------------------===//
1457 /// ParseType - Parse a type.
1458 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1459 SMLoc TypeLoc = Lex.getLoc();
1460 switch (Lex.getKind()) {
1462 return TokError("expected type");
1464 // Type ::= 'float' | 'void' (etc)
1465 Result = Lex.getTyVal();
1469 // Type ::= StructType
1470 if (ParseAnonStructType(Result, false))
1473 case lltok::lsquare:
1474 // Type ::= '[' ... ']'
1475 Lex.Lex(); // eat the lsquare.
1476 if (ParseArrayVectorType(Result, false))
1479 case lltok::less: // Either vector or packed struct.
1480 // Type ::= '<' ... '>'
1482 if (Lex.getKind() == lltok::lbrace) {
1483 if (ParseAnonStructType(Result, true) ||
1484 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1486 } else if (ParseArrayVectorType(Result, true))
1489 case lltok::LocalVar: {
1491 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1493 // If the type hasn't been defined yet, create a forward definition and
1494 // remember where that forward def'n was seen (in case it never is defined).
1495 if (Entry.first == 0) {
1496 Entry.first = StructType::create(Context, Lex.getStrVal());
1497 Entry.second = Lex.getLoc();
1499 Result = Entry.first;
1504 case lltok::LocalVarID: {
1506 if (Lex.getUIntVal() >= NumberedTypes.size())
1507 NumberedTypes.resize(Lex.getUIntVal()+1);
1508 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1510 // If the type hasn't been defined yet, create a forward definition and
1511 // remember where that forward def'n was seen (in case it never is defined).
1512 if (Entry.first == 0) {
1513 Entry.first = StructType::create(Context);
1514 Entry.second = Lex.getLoc();
1516 Result = Entry.first;
1522 // Parse the type suffixes.
1524 switch (Lex.getKind()) {
1527 if (!AllowVoid && Result->isVoidTy())
1528 return Error(TypeLoc, "void type only allowed for function results");
1531 // Type ::= Type '*'
1533 if (Result->isLabelTy())
1534 return TokError("basic block pointers are invalid");
1535 if (Result->isVoidTy())
1536 return TokError("pointers to void are invalid - use i8* instead");
1537 if (!PointerType::isValidElementType(Result))
1538 return TokError("pointer to this type is invalid");
1539 Result = PointerType::getUnqual(Result);
1543 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1544 case lltok::kw_addrspace: {
1545 if (Result->isLabelTy())
1546 return TokError("basic block pointers are invalid");
1547 if (Result->isVoidTy())
1548 return TokError("pointers to void are invalid; use i8* instead");
1549 if (!PointerType::isValidElementType(Result))
1550 return TokError("pointer to this type is invalid");
1552 if (ParseOptionalAddrSpace(AddrSpace) ||
1553 ParseToken(lltok::star, "expected '*' in address space"))
1556 Result = PointerType::get(Result, AddrSpace);
1560 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1562 if (ParseFunctionType(Result))
1569 /// ParseParameterList
1571 /// ::= '(' Arg (',' Arg)* ')'
1573 /// ::= Type OptionalAttributes Value OptionalAttributes
1574 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1575 PerFunctionState &PFS) {
1576 if (ParseToken(lltok::lparen, "expected '(' in call"))
1579 unsigned AttrIndex = 1;
1580 while (Lex.getKind() != lltok::rparen) {
1581 // If this isn't the first argument, we need a comma.
1582 if (!ArgList.empty() &&
1583 ParseToken(lltok::comma, "expected ',' in argument list"))
1586 // Parse the argument.
1589 AttrBuilder ArgAttrs;
1591 if (ParseType(ArgTy, ArgLoc))
1594 // Otherwise, handle normal operands.
1595 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1597 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1602 Lex.Lex(); // Lex the ')'.
1608 /// ParseArgumentList - Parse the argument list for a function type or function
1610 /// ::= '(' ArgTypeListI ')'
1614 /// ::= ArgTypeList ',' '...'
1615 /// ::= ArgType (',' ArgType)*
1617 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1620 assert(Lex.getKind() == lltok::lparen);
1621 Lex.Lex(); // eat the (.
1623 if (Lex.getKind() == lltok::rparen) {
1625 } else if (Lex.getKind() == lltok::dotdotdot) {
1629 LocTy TypeLoc = Lex.getLoc();
1634 if (ParseType(ArgTy) ||
1635 ParseOptionalParamAttrs(Attrs)) return true;
1637 if (ArgTy->isVoidTy())
1638 return Error(TypeLoc, "argument can not have void type");
1640 if (Lex.getKind() == lltok::LocalVar) {
1641 Name = Lex.getStrVal();
1645 if (!FunctionType::isValidArgumentType(ArgTy))
1646 return Error(TypeLoc, "invalid type for function argument");
1648 unsigned AttrIndex = 1;
1649 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1650 AttributeSet::get(ArgTy->getContext(),
1651 AttrIndex++, Attrs), Name));
1653 while (EatIfPresent(lltok::comma)) {
1654 // Handle ... at end of arg list.
1655 if (EatIfPresent(lltok::dotdotdot)) {
1660 // Otherwise must be an argument type.
1661 TypeLoc = Lex.getLoc();
1662 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1664 if (ArgTy->isVoidTy())
1665 return Error(TypeLoc, "argument can not have void type");
1667 if (Lex.getKind() == lltok::LocalVar) {
1668 Name = Lex.getStrVal();
1674 if (!ArgTy->isFirstClassType())
1675 return Error(TypeLoc, "invalid type for function argument");
1677 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1678 AttributeSet::get(ArgTy->getContext(),
1679 AttrIndex++, Attrs),
1684 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1687 /// ParseFunctionType
1688 /// ::= Type ArgumentList OptionalAttrs
1689 bool LLParser::ParseFunctionType(Type *&Result) {
1690 assert(Lex.getKind() == lltok::lparen);
1692 if (!FunctionType::isValidReturnType(Result))
1693 return TokError("invalid function return type");
1695 SmallVector<ArgInfo, 8> ArgList;
1697 if (ParseArgumentList(ArgList, isVarArg))
1700 // Reject names on the arguments lists.
1701 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1702 if (!ArgList[i].Name.empty())
1703 return Error(ArgList[i].Loc, "argument name invalid in function type");
1704 if (ArgList[i].Attrs.hasAttributes(i + 1))
1705 return Error(ArgList[i].Loc,
1706 "argument attributes invalid in function type");
1709 SmallVector<Type*, 16> ArgListTy;
1710 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1711 ArgListTy.push_back(ArgList[i].Ty);
1713 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1717 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1719 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1720 SmallVector<Type*, 8> Elts;
1721 if (ParseStructBody(Elts)) return true;
1723 Result = StructType::get(Context, Elts, Packed);
1727 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1728 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1729 std::pair<Type*, LocTy> &Entry,
1731 // If the type was already defined, diagnose the redefinition.
1732 if (Entry.first && !Entry.second.isValid())
1733 return Error(TypeLoc, "redefinition of type");
1735 // If we have opaque, just return without filling in the definition for the
1736 // struct. This counts as a definition as far as the .ll file goes.
1737 if (EatIfPresent(lltok::kw_opaque)) {
1738 // This type is being defined, so clear the location to indicate this.
1739 Entry.second = SMLoc();
1741 // If this type number has never been uttered, create it.
1742 if (Entry.first == 0)
1743 Entry.first = StructType::create(Context, Name);
1744 ResultTy = Entry.first;
1748 // If the type starts with '<', then it is either a packed struct or a vector.
1749 bool isPacked = EatIfPresent(lltok::less);
1751 // If we don't have a struct, then we have a random type alias, which we
1752 // accept for compatibility with old files. These types are not allowed to be
1753 // forward referenced and not allowed to be recursive.
1754 if (Lex.getKind() != lltok::lbrace) {
1756 return Error(TypeLoc, "forward references to non-struct type");
1760 return ParseArrayVectorType(ResultTy, true);
1761 return ParseType(ResultTy);
1764 // This type is being defined, so clear the location to indicate this.
1765 Entry.second = SMLoc();
1767 // If this type number has never been uttered, create it.
1768 if (Entry.first == 0)
1769 Entry.first = StructType::create(Context, Name);
1771 StructType *STy = cast<StructType>(Entry.first);
1773 SmallVector<Type*, 8> Body;
1774 if (ParseStructBody(Body) ||
1775 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1778 STy->setBody(Body, isPacked);
1784 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1787 /// ::= '{' Type (',' Type)* '}'
1788 /// ::= '<' '{' '}' '>'
1789 /// ::= '<' '{' Type (',' Type)* '}' '>'
1790 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1791 assert(Lex.getKind() == lltok::lbrace);
1792 Lex.Lex(); // Consume the '{'
1794 // Handle the empty struct.
1795 if (EatIfPresent(lltok::rbrace))
1798 LocTy EltTyLoc = Lex.getLoc();
1800 if (ParseType(Ty)) return true;
1803 if (!StructType::isValidElementType(Ty))
1804 return Error(EltTyLoc, "invalid element type for struct");
1806 while (EatIfPresent(lltok::comma)) {
1807 EltTyLoc = Lex.getLoc();
1808 if (ParseType(Ty)) return true;
1810 if (!StructType::isValidElementType(Ty))
1811 return Error(EltTyLoc, "invalid element type for struct");
1816 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1819 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1820 /// token has already been consumed.
1822 /// ::= '[' APSINTVAL 'x' Types ']'
1823 /// ::= '<' APSINTVAL 'x' Types '>'
1824 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1825 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1826 Lex.getAPSIntVal().getBitWidth() > 64)
1827 return TokError("expected number in address space");
1829 LocTy SizeLoc = Lex.getLoc();
1830 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1833 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1836 LocTy TypeLoc = Lex.getLoc();
1838 if (ParseType(EltTy)) return true;
1840 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1841 "expected end of sequential type"))
1846 return Error(SizeLoc, "zero element vector is illegal");
1847 if ((unsigned)Size != Size)
1848 return Error(SizeLoc, "size too large for vector");
1849 if (!VectorType::isValidElementType(EltTy))
1850 return Error(TypeLoc, "invalid vector element type");
1851 Result = VectorType::get(EltTy, unsigned(Size));
1853 if (!ArrayType::isValidElementType(EltTy))
1854 return Error(TypeLoc, "invalid array element type");
1855 Result = ArrayType::get(EltTy, Size);
1860 //===----------------------------------------------------------------------===//
1861 // Function Semantic Analysis.
1862 //===----------------------------------------------------------------------===//
1864 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1866 : P(p), F(f), FunctionNumber(functionNumber) {
1868 // Insert unnamed arguments into the NumberedVals list.
1869 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1872 NumberedVals.push_back(AI);
1875 LLParser::PerFunctionState::~PerFunctionState() {
1876 // If there were any forward referenced non-basicblock values, delete them.
1877 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1878 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1879 if (!isa<BasicBlock>(I->second.first)) {
1880 I->second.first->replaceAllUsesWith(
1881 UndefValue::get(I->second.first->getType()));
1882 delete I->second.first;
1883 I->second.first = 0;
1886 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1887 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1888 if (!isa<BasicBlock>(I->second.first)) {
1889 I->second.first->replaceAllUsesWith(
1890 UndefValue::get(I->second.first->getType()));
1891 delete I->second.first;
1892 I->second.first = 0;
1896 bool LLParser::PerFunctionState::FinishFunction() {
1897 // Check to see if someone took the address of labels in this block.
1898 if (!P.ForwardRefBlockAddresses.empty()) {
1900 if (!F.getName().empty()) {
1901 FunctionID.Kind = ValID::t_GlobalName;
1902 FunctionID.StrVal = F.getName();
1904 FunctionID.Kind = ValID::t_GlobalID;
1905 FunctionID.UIntVal = FunctionNumber;
1908 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1909 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1910 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1911 // Resolve all these references.
1912 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1915 P.ForwardRefBlockAddresses.erase(FRBAI);
1919 if (!ForwardRefVals.empty())
1920 return P.Error(ForwardRefVals.begin()->second.second,
1921 "use of undefined value '%" + ForwardRefVals.begin()->first +
1923 if (!ForwardRefValIDs.empty())
1924 return P.Error(ForwardRefValIDs.begin()->second.second,
1925 "use of undefined value '%" +
1926 Twine(ForwardRefValIDs.begin()->first) + "'");
1931 /// GetVal - Get a value with the specified name or ID, creating a
1932 /// forward reference record if needed. This can return null if the value
1933 /// exists but does not have the right type.
1934 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1935 Type *Ty, LocTy Loc) {
1936 // Look this name up in the normal function symbol table.
1937 Value *Val = F.getValueSymbolTable().lookup(Name);
1939 // If this is a forward reference for the value, see if we already created a
1940 // forward ref record.
1942 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1943 I = ForwardRefVals.find(Name);
1944 if (I != ForwardRefVals.end())
1945 Val = I->second.first;
1948 // If we have the value in the symbol table or fwd-ref table, return it.
1950 if (Val->getType() == Ty) return Val;
1951 if (Ty->isLabelTy())
1952 P.Error(Loc, "'%" + Name + "' is not a basic block");
1954 P.Error(Loc, "'%" + Name + "' defined with type '" +
1955 getTypeString(Val->getType()) + "'");
1959 // Don't make placeholders with invalid type.
1960 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1961 P.Error(Loc, "invalid use of a non-first-class type");
1965 // Otherwise, create a new forward reference for this value and remember it.
1967 if (Ty->isLabelTy())
1968 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1970 FwdVal = new Argument(Ty, Name);
1972 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1976 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
1978 // Look this name up in the normal function symbol table.
1979 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1981 // If this is a forward reference for the value, see if we already created a
1982 // forward ref record.
1984 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1985 I = ForwardRefValIDs.find(ID);
1986 if (I != ForwardRefValIDs.end())
1987 Val = I->second.first;
1990 // If we have the value in the symbol table or fwd-ref table, return it.
1992 if (Val->getType() == Ty) return Val;
1993 if (Ty->isLabelTy())
1994 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1996 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1997 getTypeString(Val->getType()) + "'");
2001 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2002 P.Error(Loc, "invalid use of a non-first-class type");
2006 // Otherwise, create a new forward reference for this value and remember it.
2008 if (Ty->isLabelTy())
2009 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2011 FwdVal = new Argument(Ty);
2013 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2017 /// SetInstName - After an instruction is parsed and inserted into its
2018 /// basic block, this installs its name.
2019 bool LLParser::PerFunctionState::SetInstName(int NameID,
2020 const std::string &NameStr,
2021 LocTy NameLoc, Instruction *Inst) {
2022 // If this instruction has void type, it cannot have a name or ID specified.
2023 if (Inst->getType()->isVoidTy()) {
2024 if (NameID != -1 || !NameStr.empty())
2025 return P.Error(NameLoc, "instructions returning void cannot have a name");
2029 // If this was a numbered instruction, verify that the instruction is the
2030 // expected value and resolve any forward references.
2031 if (NameStr.empty()) {
2032 // If neither a name nor an ID was specified, just use the next ID.
2034 NameID = NumberedVals.size();
2036 if (unsigned(NameID) != NumberedVals.size())
2037 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2038 Twine(NumberedVals.size()) + "'");
2040 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2041 ForwardRefValIDs.find(NameID);
2042 if (FI != ForwardRefValIDs.end()) {
2043 if (FI->second.first->getType() != Inst->getType())
2044 return P.Error(NameLoc, "instruction forward referenced with type '" +
2045 getTypeString(FI->second.first->getType()) + "'");
2046 FI->second.first->replaceAllUsesWith(Inst);
2047 delete FI->second.first;
2048 ForwardRefValIDs.erase(FI);
2051 NumberedVals.push_back(Inst);
2055 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2056 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2057 FI = ForwardRefVals.find(NameStr);
2058 if (FI != ForwardRefVals.end()) {
2059 if (FI->second.first->getType() != Inst->getType())
2060 return P.Error(NameLoc, "instruction forward referenced with type '" +
2061 getTypeString(FI->second.first->getType()) + "'");
2062 FI->second.first->replaceAllUsesWith(Inst);
2063 delete FI->second.first;
2064 ForwardRefVals.erase(FI);
2067 // Set the name on the instruction.
2068 Inst->setName(NameStr);
2070 if (Inst->getName() != NameStr)
2071 return P.Error(NameLoc, "multiple definition of local value named '" +
2076 /// GetBB - Get a basic block with the specified name or ID, creating a
2077 /// forward reference record if needed.
2078 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2080 return cast_or_null<BasicBlock>(GetVal(Name,
2081 Type::getLabelTy(F.getContext()), Loc));
2084 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2085 return cast_or_null<BasicBlock>(GetVal(ID,
2086 Type::getLabelTy(F.getContext()), Loc));
2089 /// DefineBB - Define the specified basic block, which is either named or
2090 /// unnamed. If there is an error, this returns null otherwise it returns
2091 /// the block being defined.
2092 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2096 BB = GetBB(NumberedVals.size(), Loc);
2098 BB = GetBB(Name, Loc);
2099 if (BB == 0) return 0; // Already diagnosed error.
2101 // Move the block to the end of the function. Forward ref'd blocks are
2102 // inserted wherever they happen to be referenced.
2103 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2105 // Remove the block from forward ref sets.
2107 ForwardRefValIDs.erase(NumberedVals.size());
2108 NumberedVals.push_back(BB);
2110 // BB forward references are already in the function symbol table.
2111 ForwardRefVals.erase(Name);
2117 //===----------------------------------------------------------------------===//
2119 //===----------------------------------------------------------------------===//
2121 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2122 /// type implied. For example, if we parse "4" we don't know what integer type
2123 /// it has. The value will later be combined with its type and checked for
2124 /// sanity. PFS is used to convert function-local operands of metadata (since
2125 /// metadata operands are not just parsed here but also converted to values).
2126 /// PFS can be null when we are not parsing metadata values inside a function.
2127 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2128 ID.Loc = Lex.getLoc();
2129 switch (Lex.getKind()) {
2130 default: return TokError("expected value token");
2131 case lltok::GlobalID: // @42
2132 ID.UIntVal = Lex.getUIntVal();
2133 ID.Kind = ValID::t_GlobalID;
2135 case lltok::GlobalVar: // @foo
2136 ID.StrVal = Lex.getStrVal();
2137 ID.Kind = ValID::t_GlobalName;
2139 case lltok::LocalVarID: // %42
2140 ID.UIntVal = Lex.getUIntVal();
2141 ID.Kind = ValID::t_LocalID;
2143 case lltok::LocalVar: // %foo
2144 ID.StrVal = Lex.getStrVal();
2145 ID.Kind = ValID::t_LocalName;
2147 case lltok::exclaim: // !42, !{...}, or !"foo"
2148 return ParseMetadataValue(ID, PFS);
2150 ID.APSIntVal = Lex.getAPSIntVal();
2151 ID.Kind = ValID::t_APSInt;
2153 case lltok::APFloat:
2154 ID.APFloatVal = Lex.getAPFloatVal();
2155 ID.Kind = ValID::t_APFloat;
2157 case lltok::kw_true:
2158 ID.ConstantVal = ConstantInt::getTrue(Context);
2159 ID.Kind = ValID::t_Constant;
2161 case lltok::kw_false:
2162 ID.ConstantVal = ConstantInt::getFalse(Context);
2163 ID.Kind = ValID::t_Constant;
2165 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2166 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2167 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2169 case lltok::lbrace: {
2170 // ValID ::= '{' ConstVector '}'
2172 SmallVector<Constant*, 16> Elts;
2173 if (ParseGlobalValueVector(Elts) ||
2174 ParseToken(lltok::rbrace, "expected end of struct constant"))
2177 ID.ConstantStructElts = new Constant*[Elts.size()];
2178 ID.UIntVal = Elts.size();
2179 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2180 ID.Kind = ValID::t_ConstantStruct;
2184 // ValID ::= '<' ConstVector '>' --> Vector.
2185 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2187 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2189 SmallVector<Constant*, 16> Elts;
2190 LocTy FirstEltLoc = Lex.getLoc();
2191 if (ParseGlobalValueVector(Elts) ||
2193 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2194 ParseToken(lltok::greater, "expected end of constant"))
2197 if (isPackedStruct) {
2198 ID.ConstantStructElts = new Constant*[Elts.size()];
2199 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2200 ID.UIntVal = Elts.size();
2201 ID.Kind = ValID::t_PackedConstantStruct;
2206 return Error(ID.Loc, "constant vector must not be empty");
2208 if (!Elts[0]->getType()->isIntegerTy() &&
2209 !Elts[0]->getType()->isFloatingPointTy() &&
2210 !Elts[0]->getType()->isPointerTy())
2211 return Error(FirstEltLoc,
2212 "vector elements must have integer, pointer or floating point type");
2214 // Verify that all the vector elements have the same type.
2215 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2216 if (Elts[i]->getType() != Elts[0]->getType())
2217 return Error(FirstEltLoc,
2218 "vector element #" + Twine(i) +
2219 " is not of type '" + getTypeString(Elts[0]->getType()));
2221 ID.ConstantVal = ConstantVector::get(Elts);
2222 ID.Kind = ValID::t_Constant;
2225 case lltok::lsquare: { // Array Constant
2227 SmallVector<Constant*, 16> Elts;
2228 LocTy FirstEltLoc = Lex.getLoc();
2229 if (ParseGlobalValueVector(Elts) ||
2230 ParseToken(lltok::rsquare, "expected end of array constant"))
2233 // Handle empty element.
2235 // Use undef instead of an array because it's inconvenient to determine
2236 // the element type at this point, there being no elements to examine.
2237 ID.Kind = ValID::t_EmptyArray;
2241 if (!Elts[0]->getType()->isFirstClassType())
2242 return Error(FirstEltLoc, "invalid array element type: " +
2243 getTypeString(Elts[0]->getType()));
2245 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2247 // Verify all elements are correct type!
2248 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2249 if (Elts[i]->getType() != Elts[0]->getType())
2250 return Error(FirstEltLoc,
2251 "array element #" + Twine(i) +
2252 " is not of type '" + getTypeString(Elts[0]->getType()));
2255 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2256 ID.Kind = ValID::t_Constant;
2259 case lltok::kw_c: // c "foo"
2261 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2263 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2264 ID.Kind = ValID::t_Constant;
2267 case lltok::kw_asm: {
2268 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2269 bool HasSideEffect, AlignStack, AsmDialect;
2271 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2272 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2273 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2274 ParseStringConstant(ID.StrVal) ||
2275 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2276 ParseToken(lltok::StringConstant, "expected constraint string"))
2278 ID.StrVal2 = Lex.getStrVal();
2279 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2280 (unsigned(AsmDialect)<<2);
2281 ID.Kind = ValID::t_InlineAsm;
2285 case lltok::kw_blockaddress: {
2286 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2290 LocTy FnLoc, LabelLoc;
2292 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2294 ParseToken(lltok::comma, "expected comma in block address expression")||
2295 ParseValID(Label) ||
2296 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2299 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2300 return Error(Fn.Loc, "expected function name in blockaddress");
2301 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2302 return Error(Label.Loc, "expected basic block name in blockaddress");
2304 // Make a global variable as a placeholder for this reference.
2305 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2306 false, GlobalValue::InternalLinkage,
2308 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2309 ID.ConstantVal = FwdRef;
2310 ID.Kind = ValID::t_Constant;
2314 case lltok::kw_trunc:
2315 case lltok::kw_zext:
2316 case lltok::kw_sext:
2317 case lltok::kw_fptrunc:
2318 case lltok::kw_fpext:
2319 case lltok::kw_bitcast:
2320 case lltok::kw_uitofp:
2321 case lltok::kw_sitofp:
2322 case lltok::kw_fptoui:
2323 case lltok::kw_fptosi:
2324 case lltok::kw_inttoptr:
2325 case lltok::kw_ptrtoint: {
2326 unsigned Opc = Lex.getUIntVal();
2330 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2331 ParseGlobalTypeAndValue(SrcVal) ||
2332 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2333 ParseType(DestTy) ||
2334 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2336 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2337 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2338 getTypeString(SrcVal->getType()) + "' to '" +
2339 getTypeString(DestTy) + "'");
2340 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2342 ID.Kind = ValID::t_Constant;
2345 case lltok::kw_extractvalue: {
2348 SmallVector<unsigned, 4> Indices;
2349 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2350 ParseGlobalTypeAndValue(Val) ||
2351 ParseIndexList(Indices) ||
2352 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2355 if (!Val->getType()->isAggregateType())
2356 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2357 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2358 return Error(ID.Loc, "invalid indices for extractvalue");
2359 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2360 ID.Kind = ValID::t_Constant;
2363 case lltok::kw_insertvalue: {
2365 Constant *Val0, *Val1;
2366 SmallVector<unsigned, 4> Indices;
2367 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2368 ParseGlobalTypeAndValue(Val0) ||
2369 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2370 ParseGlobalTypeAndValue(Val1) ||
2371 ParseIndexList(Indices) ||
2372 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2374 if (!Val0->getType()->isAggregateType())
2375 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2376 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2377 return Error(ID.Loc, "invalid indices for insertvalue");
2378 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2379 ID.Kind = ValID::t_Constant;
2382 case lltok::kw_icmp:
2383 case lltok::kw_fcmp: {
2384 unsigned PredVal, Opc = Lex.getUIntVal();
2385 Constant *Val0, *Val1;
2387 if (ParseCmpPredicate(PredVal, Opc) ||
2388 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2389 ParseGlobalTypeAndValue(Val0) ||
2390 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2391 ParseGlobalTypeAndValue(Val1) ||
2392 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2395 if (Val0->getType() != Val1->getType())
2396 return Error(ID.Loc, "compare operands must have the same type");
2398 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2400 if (Opc == Instruction::FCmp) {
2401 if (!Val0->getType()->isFPOrFPVectorTy())
2402 return Error(ID.Loc, "fcmp requires floating point operands");
2403 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2405 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2406 if (!Val0->getType()->isIntOrIntVectorTy() &&
2407 !Val0->getType()->getScalarType()->isPointerTy())
2408 return Error(ID.Loc, "icmp requires pointer or integer operands");
2409 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2411 ID.Kind = ValID::t_Constant;
2415 // Binary Operators.
2417 case lltok::kw_fadd:
2419 case lltok::kw_fsub:
2421 case lltok::kw_fmul:
2422 case lltok::kw_udiv:
2423 case lltok::kw_sdiv:
2424 case lltok::kw_fdiv:
2425 case lltok::kw_urem:
2426 case lltok::kw_srem:
2427 case lltok::kw_frem:
2429 case lltok::kw_lshr:
2430 case lltok::kw_ashr: {
2434 unsigned Opc = Lex.getUIntVal();
2435 Constant *Val0, *Val1;
2437 LocTy ModifierLoc = Lex.getLoc();
2438 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2439 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2440 if (EatIfPresent(lltok::kw_nuw))
2442 if (EatIfPresent(lltok::kw_nsw)) {
2444 if (EatIfPresent(lltok::kw_nuw))
2447 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2448 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2449 if (EatIfPresent(lltok::kw_exact))
2452 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2453 ParseGlobalTypeAndValue(Val0) ||
2454 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2455 ParseGlobalTypeAndValue(Val1) ||
2456 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2458 if (Val0->getType() != Val1->getType())
2459 return Error(ID.Loc, "operands of constexpr must have same type");
2460 if (!Val0->getType()->isIntOrIntVectorTy()) {
2462 return Error(ModifierLoc, "nuw only applies to integer operations");
2464 return Error(ModifierLoc, "nsw only applies to integer operations");
2466 // Check that the type is valid for the operator.
2468 case Instruction::Add:
2469 case Instruction::Sub:
2470 case Instruction::Mul:
2471 case Instruction::UDiv:
2472 case Instruction::SDiv:
2473 case Instruction::URem:
2474 case Instruction::SRem:
2475 case Instruction::Shl:
2476 case Instruction::AShr:
2477 case Instruction::LShr:
2478 if (!Val0->getType()->isIntOrIntVectorTy())
2479 return Error(ID.Loc, "constexpr requires integer operands");
2481 case Instruction::FAdd:
2482 case Instruction::FSub:
2483 case Instruction::FMul:
2484 case Instruction::FDiv:
2485 case Instruction::FRem:
2486 if (!Val0->getType()->isFPOrFPVectorTy())
2487 return Error(ID.Loc, "constexpr requires fp operands");
2489 default: llvm_unreachable("Unknown binary operator!");
2492 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2493 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2494 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2495 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2497 ID.Kind = ValID::t_Constant;
2501 // Logical Operations
2504 case lltok::kw_xor: {
2505 unsigned Opc = Lex.getUIntVal();
2506 Constant *Val0, *Val1;
2508 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2509 ParseGlobalTypeAndValue(Val0) ||
2510 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2511 ParseGlobalTypeAndValue(Val1) ||
2512 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2514 if (Val0->getType() != Val1->getType())
2515 return Error(ID.Loc, "operands of constexpr must have same type");
2516 if (!Val0->getType()->isIntOrIntVectorTy())
2517 return Error(ID.Loc,
2518 "constexpr requires integer or integer vector operands");
2519 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2520 ID.Kind = ValID::t_Constant;
2524 case lltok::kw_getelementptr:
2525 case lltok::kw_shufflevector:
2526 case lltok::kw_insertelement:
2527 case lltok::kw_extractelement:
2528 case lltok::kw_select: {
2529 unsigned Opc = Lex.getUIntVal();
2530 SmallVector<Constant*, 16> Elts;
2531 bool InBounds = false;
2533 if (Opc == Instruction::GetElementPtr)
2534 InBounds = EatIfPresent(lltok::kw_inbounds);
2535 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2536 ParseGlobalValueVector(Elts) ||
2537 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2540 if (Opc == Instruction::GetElementPtr) {
2541 if (Elts.size() == 0 ||
2542 !Elts[0]->getType()->getScalarType()->isPointerTy())
2543 return Error(ID.Loc, "getelementptr requires pointer operand");
2545 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2546 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2547 return Error(ID.Loc, "invalid indices for getelementptr");
2548 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2550 } else if (Opc == Instruction::Select) {
2551 if (Elts.size() != 3)
2552 return Error(ID.Loc, "expected three operands to select");
2553 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2555 return Error(ID.Loc, Reason);
2556 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2557 } else if (Opc == Instruction::ShuffleVector) {
2558 if (Elts.size() != 3)
2559 return Error(ID.Loc, "expected three operands to shufflevector");
2560 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2561 return Error(ID.Loc, "invalid operands to shufflevector");
2563 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2564 } else if (Opc == Instruction::ExtractElement) {
2565 if (Elts.size() != 2)
2566 return Error(ID.Loc, "expected two operands to extractelement");
2567 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2568 return Error(ID.Loc, "invalid extractelement operands");
2569 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2571 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2572 if (Elts.size() != 3)
2573 return Error(ID.Loc, "expected three operands to insertelement");
2574 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2575 return Error(ID.Loc, "invalid insertelement operands");
2577 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2580 ID.Kind = ValID::t_Constant;
2589 /// ParseGlobalValue - Parse a global value with the specified type.
2590 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2594 bool Parsed = ParseValID(ID) ||
2595 ConvertValIDToValue(Ty, ID, V, NULL);
2596 if (V && !(C = dyn_cast<Constant>(V)))
2597 return Error(ID.Loc, "global values must be constants");
2601 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2603 return ParseType(Ty) ||
2604 ParseGlobalValue(Ty, V);
2607 /// ParseGlobalValueVector
2609 /// ::= TypeAndValue (',' TypeAndValue)*
2610 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2612 if (Lex.getKind() == lltok::rbrace ||
2613 Lex.getKind() == lltok::rsquare ||
2614 Lex.getKind() == lltok::greater ||
2615 Lex.getKind() == lltok::rparen)
2619 if (ParseGlobalTypeAndValue(C)) return true;
2622 while (EatIfPresent(lltok::comma)) {
2623 if (ParseGlobalTypeAndValue(C)) return true;
2630 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2631 assert(Lex.getKind() == lltok::lbrace);
2634 SmallVector<Value*, 16> Elts;
2635 if (ParseMDNodeVector(Elts, PFS) ||
2636 ParseToken(lltok::rbrace, "expected end of metadata node"))
2639 ID.MDNodeVal = MDNode::get(Context, Elts);
2640 ID.Kind = ValID::t_MDNode;
2644 /// ParseMetadataValue
2648 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2649 assert(Lex.getKind() == lltok::exclaim);
2654 if (Lex.getKind() == lltok::lbrace)
2655 return ParseMetadataListValue(ID, PFS);
2657 // Standalone metadata reference
2659 if (Lex.getKind() == lltok::APSInt) {
2660 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2661 ID.Kind = ValID::t_MDNode;
2666 // ::= '!' STRINGCONSTANT
2667 if (ParseMDString(ID.MDStringVal)) return true;
2668 ID.Kind = ValID::t_MDString;
2673 //===----------------------------------------------------------------------===//
2674 // Function Parsing.
2675 //===----------------------------------------------------------------------===//
2677 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2678 PerFunctionState *PFS) {
2679 if (Ty->isFunctionTy())
2680 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2683 case ValID::t_LocalID:
2684 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2685 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2687 case ValID::t_LocalName:
2688 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2689 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2691 case ValID::t_InlineAsm: {
2692 PointerType *PTy = dyn_cast<PointerType>(Ty);
2694 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2695 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2696 return Error(ID.Loc, "invalid type for inline asm constraint string");
2697 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2698 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2701 case ValID::t_MDNode:
2702 if (!Ty->isMetadataTy())
2703 return Error(ID.Loc, "metadata value must have metadata type");
2706 case ValID::t_MDString:
2707 if (!Ty->isMetadataTy())
2708 return Error(ID.Loc, "metadata value must have metadata type");
2711 case ValID::t_GlobalName:
2712 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2714 case ValID::t_GlobalID:
2715 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2717 case ValID::t_APSInt:
2718 if (!Ty->isIntegerTy())
2719 return Error(ID.Loc, "integer constant must have integer type");
2720 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2721 V = ConstantInt::get(Context, ID.APSIntVal);
2723 case ValID::t_APFloat:
2724 if (!Ty->isFloatingPointTy() ||
2725 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2726 return Error(ID.Loc, "floating point constant invalid for type");
2728 // The lexer has no type info, so builds all half, float, and double FP
2729 // constants as double. Fix this here. Long double does not need this.
2730 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2733 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2735 else if (Ty->isFloatTy())
2736 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2739 V = ConstantFP::get(Context, ID.APFloatVal);
2741 if (V->getType() != Ty)
2742 return Error(ID.Loc, "floating point constant does not have type '" +
2743 getTypeString(Ty) + "'");
2747 if (!Ty->isPointerTy())
2748 return Error(ID.Loc, "null must be a pointer type");
2749 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2751 case ValID::t_Undef:
2752 // FIXME: LabelTy should not be a first-class type.
2753 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2754 return Error(ID.Loc, "invalid type for undef constant");
2755 V = UndefValue::get(Ty);
2757 case ValID::t_EmptyArray:
2758 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2759 return Error(ID.Loc, "invalid empty array initializer");
2760 V = UndefValue::get(Ty);
2763 // FIXME: LabelTy should not be a first-class type.
2764 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2765 return Error(ID.Loc, "invalid type for null constant");
2766 V = Constant::getNullValue(Ty);
2768 case ValID::t_Constant:
2769 if (ID.ConstantVal->getType() != Ty)
2770 return Error(ID.Loc, "constant expression type mismatch");
2774 case ValID::t_ConstantStruct:
2775 case ValID::t_PackedConstantStruct:
2776 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2777 if (ST->getNumElements() != ID.UIntVal)
2778 return Error(ID.Loc,
2779 "initializer with struct type has wrong # elements");
2780 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2781 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2783 // Verify that the elements are compatible with the structtype.
2784 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2785 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2786 return Error(ID.Loc, "element " + Twine(i) +
2787 " of struct initializer doesn't match struct element type");
2789 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2792 return Error(ID.Loc, "constant expression type mismatch");
2795 llvm_unreachable("Invalid ValID");
2798 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2801 return ParseValID(ID, PFS) ||
2802 ConvertValIDToValue(Ty, ID, V, PFS);
2805 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2807 return ParseType(Ty) ||
2808 ParseValue(Ty, V, PFS);
2811 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2812 PerFunctionState &PFS) {
2815 if (ParseTypeAndValue(V, PFS)) return true;
2816 if (!isa<BasicBlock>(V))
2817 return Error(Loc, "expected a basic block");
2818 BB = cast<BasicBlock>(V);
2824 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2825 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2826 /// OptionalAlign OptGC
2827 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2828 // Parse the linkage.
2829 LocTy LinkageLoc = Lex.getLoc();
2832 unsigned Visibility;
2833 AttrBuilder RetAttrs;
2836 LocTy RetTypeLoc = Lex.getLoc();
2837 if (ParseOptionalLinkage(Linkage) ||
2838 ParseOptionalVisibility(Visibility) ||
2839 ParseOptionalCallingConv(CC) ||
2840 ParseOptionalReturnAttrs(RetAttrs) ||
2841 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2844 // Verify that the linkage is ok.
2845 switch ((GlobalValue::LinkageTypes)Linkage) {
2846 case GlobalValue::ExternalLinkage:
2847 break; // always ok.
2848 case GlobalValue::DLLImportLinkage:
2849 case GlobalValue::ExternalWeakLinkage:
2851 return Error(LinkageLoc, "invalid linkage for function definition");
2853 case GlobalValue::PrivateLinkage:
2854 case GlobalValue::LinkerPrivateLinkage:
2855 case GlobalValue::LinkerPrivateWeakLinkage:
2856 case GlobalValue::InternalLinkage:
2857 case GlobalValue::AvailableExternallyLinkage:
2858 case GlobalValue::LinkOnceAnyLinkage:
2859 case GlobalValue::LinkOnceODRLinkage:
2860 case GlobalValue::LinkOnceODRAutoHideLinkage:
2861 case GlobalValue::WeakAnyLinkage:
2862 case GlobalValue::WeakODRLinkage:
2863 case GlobalValue::DLLExportLinkage:
2865 return Error(LinkageLoc, "invalid linkage for function declaration");
2867 case GlobalValue::AppendingLinkage:
2868 case GlobalValue::CommonLinkage:
2869 return Error(LinkageLoc, "invalid function linkage type");
2872 if (!FunctionType::isValidReturnType(RetType))
2873 return Error(RetTypeLoc, "invalid function return type");
2875 LocTy NameLoc = Lex.getLoc();
2877 std::string FunctionName;
2878 if (Lex.getKind() == lltok::GlobalVar) {
2879 FunctionName = Lex.getStrVal();
2880 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2881 unsigned NameID = Lex.getUIntVal();
2883 if (NameID != NumberedVals.size())
2884 return TokError("function expected to be numbered '%" +
2885 Twine(NumberedVals.size()) + "'");
2887 return TokError("expected function name");
2892 if (Lex.getKind() != lltok::lparen)
2893 return TokError("expected '(' in function argument list");
2895 SmallVector<ArgInfo, 8> ArgList;
2897 AttrBuilder FuncAttrs;
2898 std::string Section;
2902 LocTy UnnamedAddrLoc;
2904 if (ParseArgumentList(ArgList, isVarArg) ||
2905 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2907 ParseOptionalFuncAttrs(FuncAttrs) ||
2908 (EatIfPresent(lltok::kw_section) &&
2909 ParseStringConstant(Section)) ||
2910 ParseOptionalAlignment(Alignment) ||
2911 (EatIfPresent(lltok::kw_gc) &&
2912 ParseStringConstant(GC)))
2915 // If the alignment was parsed as an attribute, move to the alignment field.
2916 if (FuncAttrs.hasAlignmentAttr()) {
2917 Alignment = FuncAttrs.getAlignment();
2918 FuncAttrs.removeAttribute(Attribute::Alignment);
2921 // Okay, if we got here, the function is syntactically valid. Convert types
2922 // and do semantic checks.
2923 std::vector<Type*> ParamTypeList;
2924 SmallVector<AttributeSet, 8> Attrs;
2926 if (RetAttrs.hasAttributes())
2927 Attrs.push_back(AttributeSet::get(RetType->getContext(),
2928 AttributeSet::ReturnIndex,
2931 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2932 ParamTypeList.push_back(ArgList[i].Ty);
2933 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
2934 AttrBuilder B(ArgList[i].Attrs, i + 1);
2935 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
2939 if (FuncAttrs.hasAttributes())
2940 Attrs.push_back(AttributeSet::get(RetType->getContext(),
2941 AttributeSet::FunctionIndex,
2944 AttributeSet PAL = AttributeSet::get(Context, Attrs);
2946 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
2947 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2950 FunctionType::get(RetType, ParamTypeList, isVarArg);
2951 PointerType *PFT = PointerType::getUnqual(FT);
2954 if (!FunctionName.empty()) {
2955 // If this was a definition of a forward reference, remove the definition
2956 // from the forward reference table and fill in the forward ref.
2957 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2958 ForwardRefVals.find(FunctionName);
2959 if (FRVI != ForwardRefVals.end()) {
2960 Fn = M->getFunction(FunctionName);
2962 return Error(FRVI->second.second, "invalid forward reference to "
2963 "function as global value!");
2964 if (Fn->getType() != PFT)
2965 return Error(FRVI->second.second, "invalid forward reference to "
2966 "function '" + FunctionName + "' with wrong type!");
2968 ForwardRefVals.erase(FRVI);
2969 } else if ((Fn = M->getFunction(FunctionName))) {
2970 // Reject redefinitions.
2971 return Error(NameLoc, "invalid redefinition of function '" +
2972 FunctionName + "'");
2973 } else if (M->getNamedValue(FunctionName)) {
2974 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2978 // If this is a definition of a forward referenced function, make sure the
2980 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2981 = ForwardRefValIDs.find(NumberedVals.size());
2982 if (I != ForwardRefValIDs.end()) {
2983 Fn = cast<Function>(I->second.first);
2984 if (Fn->getType() != PFT)
2985 return Error(NameLoc, "type of definition and forward reference of '@" +
2986 Twine(NumberedVals.size()) + "' disagree");
2987 ForwardRefValIDs.erase(I);
2992 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2993 else // Move the forward-reference to the correct spot in the module.
2994 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2996 if (FunctionName.empty())
2997 NumberedVals.push_back(Fn);
2999 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3000 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3001 Fn->setCallingConv(CC);
3002 Fn->setAttributes(PAL);
3003 Fn->setUnnamedAddr(UnnamedAddr);
3004 Fn->setAlignment(Alignment);
3005 Fn->setSection(Section);
3006 if (!GC.empty()) Fn->setGC(GC.c_str());
3008 // Add all of the arguments we parsed to the function.
3009 Function::arg_iterator ArgIt = Fn->arg_begin();
3010 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3011 // If the argument has a name, insert it into the argument symbol table.
3012 if (ArgList[i].Name.empty()) continue;
3014 // Set the name, if it conflicted, it will be auto-renamed.
3015 ArgIt->setName(ArgList[i].Name);
3017 if (ArgIt->getName() != ArgList[i].Name)
3018 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3019 ArgList[i].Name + "'");
3026 /// ParseFunctionBody
3027 /// ::= '{' BasicBlock+ '}'
3029 bool LLParser::ParseFunctionBody(Function &Fn) {
3030 if (Lex.getKind() != lltok::lbrace)
3031 return TokError("expected '{' in function body");
3032 Lex.Lex(); // eat the {.
3034 int FunctionNumber = -1;
3035 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3037 PerFunctionState PFS(*this, Fn, FunctionNumber);
3039 // We need at least one basic block.
3040 if (Lex.getKind() == lltok::rbrace)
3041 return TokError("function body requires at least one basic block");
3043 while (Lex.getKind() != lltok::rbrace)
3044 if (ParseBasicBlock(PFS)) return true;
3049 // Verify function is ok.
3050 return PFS.FinishFunction();
3054 /// ::= LabelStr? Instruction*
3055 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3056 // If this basic block starts out with a name, remember it.
3058 LocTy NameLoc = Lex.getLoc();
3059 if (Lex.getKind() == lltok::LabelStr) {
3060 Name = Lex.getStrVal();
3064 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3065 if (BB == 0) return true;
3067 std::string NameStr;
3069 // Parse the instructions in this block until we get a terminator.
3071 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
3073 // This instruction may have three possibilities for a name: a) none
3074 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3075 LocTy NameLoc = Lex.getLoc();
3079 if (Lex.getKind() == lltok::LocalVarID) {
3080 NameID = Lex.getUIntVal();
3082 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3084 } else if (Lex.getKind() == lltok::LocalVar) {
3085 NameStr = Lex.getStrVal();
3087 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3091 switch (ParseInstruction(Inst, BB, PFS)) {
3092 default: llvm_unreachable("Unknown ParseInstruction result!");
3093 case InstError: return true;
3095 BB->getInstList().push_back(Inst);
3097 // With a normal result, we check to see if the instruction is followed by
3098 // a comma and metadata.
3099 if (EatIfPresent(lltok::comma))
3100 if (ParseInstructionMetadata(Inst, &PFS))
3103 case InstExtraComma:
3104 BB->getInstList().push_back(Inst);
3106 // If the instruction parser ate an extra comma at the end of it, it
3107 // *must* be followed by metadata.
3108 if (ParseInstructionMetadata(Inst, &PFS))
3113 // Set the name on the instruction.
3114 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3115 } while (!isa<TerminatorInst>(Inst));
3120 //===----------------------------------------------------------------------===//
3121 // Instruction Parsing.
3122 //===----------------------------------------------------------------------===//
3124 /// ParseInstruction - Parse one of the many different instructions.
3126 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3127 PerFunctionState &PFS) {
3128 lltok::Kind Token = Lex.getKind();
3129 if (Token == lltok::Eof)
3130 return TokError("found end of file when expecting more instructions");
3131 LocTy Loc = Lex.getLoc();
3132 unsigned KeywordVal = Lex.getUIntVal();
3133 Lex.Lex(); // Eat the keyword.
3136 default: return Error(Loc, "expected instruction opcode");
3137 // Terminator Instructions.
3138 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3139 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3140 case lltok::kw_br: return ParseBr(Inst, PFS);
3141 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3142 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3143 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3144 case lltok::kw_resume: return ParseResume(Inst, PFS);
3145 // Binary Operators.
3149 case lltok::kw_shl: {
3150 bool NUW = EatIfPresent(lltok::kw_nuw);
3151 bool NSW = EatIfPresent(lltok::kw_nsw);
3152 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3154 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3156 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3157 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3160 case lltok::kw_fadd:
3161 case lltok::kw_fsub:
3162 case lltok::kw_fmul:
3163 case lltok::kw_fdiv:
3164 case lltok::kw_frem: {
3165 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3166 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3170 Inst->setFastMathFlags(FMF);
3174 case lltok::kw_sdiv:
3175 case lltok::kw_udiv:
3176 case lltok::kw_lshr:
3177 case lltok::kw_ashr: {
3178 bool Exact = EatIfPresent(lltok::kw_exact);
3180 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3181 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3185 case lltok::kw_urem:
3186 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3189 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3190 case lltok::kw_icmp:
3191 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3193 case lltok::kw_trunc:
3194 case lltok::kw_zext:
3195 case lltok::kw_sext:
3196 case lltok::kw_fptrunc:
3197 case lltok::kw_fpext:
3198 case lltok::kw_bitcast:
3199 case lltok::kw_uitofp:
3200 case lltok::kw_sitofp:
3201 case lltok::kw_fptoui:
3202 case lltok::kw_fptosi:
3203 case lltok::kw_inttoptr:
3204 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3206 case lltok::kw_select: return ParseSelect(Inst, PFS);
3207 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3208 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3209 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3210 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3211 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3212 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3213 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3214 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3216 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3217 case lltok::kw_load: return ParseLoad(Inst, PFS);
3218 case lltok::kw_store: return ParseStore(Inst, PFS);
3219 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3220 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3221 case lltok::kw_fence: return ParseFence(Inst, PFS);
3222 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3223 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3224 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3228 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3229 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3230 if (Opc == Instruction::FCmp) {
3231 switch (Lex.getKind()) {
3232 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3233 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3234 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3235 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3236 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3237 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3238 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3239 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3240 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3241 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3242 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3243 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3244 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3245 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3246 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3247 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3248 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3251 switch (Lex.getKind()) {
3252 default: return TokError("expected icmp predicate (e.g. 'eq')");
3253 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3254 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3255 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3256 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3257 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3258 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3259 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3260 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3261 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3262 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3269 //===----------------------------------------------------------------------===//
3270 // Terminator Instructions.
3271 //===----------------------------------------------------------------------===//
3273 /// ParseRet - Parse a return instruction.
3274 /// ::= 'ret' void (',' !dbg, !1)*
3275 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3276 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3277 PerFunctionState &PFS) {
3278 SMLoc TypeLoc = Lex.getLoc();
3280 if (ParseType(Ty, true /*void allowed*/)) return true;
3282 Type *ResType = PFS.getFunction().getReturnType();
3284 if (Ty->isVoidTy()) {
3285 if (!ResType->isVoidTy())
3286 return Error(TypeLoc, "value doesn't match function result type '" +
3287 getTypeString(ResType) + "'");
3289 Inst = ReturnInst::Create(Context);
3294 if (ParseValue(Ty, RV, PFS)) return true;
3296 if (ResType != RV->getType())
3297 return Error(TypeLoc, "value doesn't match function result type '" +
3298 getTypeString(ResType) + "'");
3300 Inst = ReturnInst::Create(Context, RV);
3306 /// ::= 'br' TypeAndValue
3307 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3308 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3311 BasicBlock *Op1, *Op2;
3312 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3314 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3315 Inst = BranchInst::Create(BB);
3319 if (Op0->getType() != Type::getInt1Ty(Context))
3320 return Error(Loc, "branch condition must have 'i1' type");
3322 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3323 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3324 ParseToken(lltok::comma, "expected ',' after true destination") ||
3325 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3328 Inst = BranchInst::Create(Op1, Op2, Op0);
3334 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3336 /// ::= (TypeAndValue ',' TypeAndValue)*
3337 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3338 LocTy CondLoc, BBLoc;
3340 BasicBlock *DefaultBB;
3341 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3342 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3343 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3344 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3347 if (!Cond->getType()->isIntegerTy())
3348 return Error(CondLoc, "switch condition must have integer type");
3350 // Parse the jump table pairs.
3351 SmallPtrSet<Value*, 32> SeenCases;
3352 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3353 while (Lex.getKind() != lltok::rsquare) {
3357 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3358 ParseToken(lltok::comma, "expected ',' after case value") ||
3359 ParseTypeAndBasicBlock(DestBB, PFS))
3362 if (!SeenCases.insert(Constant))
3363 return Error(CondLoc, "duplicate case value in switch");
3364 if (!isa<ConstantInt>(Constant))
3365 return Error(CondLoc, "case value is not a constant integer");
3367 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3370 Lex.Lex(); // Eat the ']'.
3372 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3373 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3374 SI->addCase(Table[i].first, Table[i].second);
3381 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3382 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3385 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3386 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3387 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3390 if (!Address->getType()->isPointerTy())
3391 return Error(AddrLoc, "indirectbr address must have pointer type");
3393 // Parse the destination list.
3394 SmallVector<BasicBlock*, 16> DestList;
3396 if (Lex.getKind() != lltok::rsquare) {
3398 if (ParseTypeAndBasicBlock(DestBB, PFS))
3400 DestList.push_back(DestBB);
3402 while (EatIfPresent(lltok::comma)) {
3403 if (ParseTypeAndBasicBlock(DestBB, PFS))
3405 DestList.push_back(DestBB);
3409 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3412 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3413 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3414 IBI->addDestination(DestList[i]);
3421 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3422 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3423 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3424 LocTy CallLoc = Lex.getLoc();
3425 AttrBuilder RetAttrs, FnAttrs;
3430 SmallVector<ParamInfo, 16> ArgList;
3432 BasicBlock *NormalBB, *UnwindBB;
3433 if (ParseOptionalCallingConv(CC) ||
3434 ParseOptionalReturnAttrs(RetAttrs) ||
3435 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3436 ParseValID(CalleeID) ||
3437 ParseParameterList(ArgList, PFS) ||
3438 ParseOptionalFuncAttrs(FnAttrs) ||
3439 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3440 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3441 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3442 ParseTypeAndBasicBlock(UnwindBB, PFS))
3445 // If RetType is a non-function pointer type, then this is the short syntax
3446 // for the call, which means that RetType is just the return type. Infer the
3447 // rest of the function argument types from the arguments that are present.
3448 PointerType *PFTy = 0;
3449 FunctionType *Ty = 0;
3450 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3451 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3452 // Pull out the types of all of the arguments...
3453 std::vector<Type*> ParamTypes;
3454 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3455 ParamTypes.push_back(ArgList[i].V->getType());
3457 if (!FunctionType::isValidReturnType(RetType))
3458 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3460 Ty = FunctionType::get(RetType, ParamTypes, false);
3461 PFTy = PointerType::getUnqual(Ty);
3464 // Look up the callee.
3466 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3468 // Set up the Attribute for the function.
3469 SmallVector<AttributeSet, 8> Attrs;
3470 if (RetAttrs.hasAttributes())
3471 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3472 AttributeSet::ReturnIndex,
3475 SmallVector<Value*, 8> Args;
3477 // Loop through FunctionType's arguments and ensure they are specified
3478 // correctly. Also, gather any parameter attributes.
3479 FunctionType::param_iterator I = Ty->param_begin();
3480 FunctionType::param_iterator E = Ty->param_end();
3481 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3482 Type *ExpectedTy = 0;
3485 } else if (!Ty->isVarArg()) {
3486 return Error(ArgList[i].Loc, "too many arguments specified");
3489 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3490 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3491 getTypeString(ExpectedTy) + "'");
3492 Args.push_back(ArgList[i].V);
3493 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3494 AttrBuilder B(ArgList[i].Attrs, i + 1);
3495 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3500 return Error(CallLoc, "not enough parameters specified for call");
3502 if (FnAttrs.hasAttributes())
3503 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3504 AttributeSet::FunctionIndex,
3507 // Finish off the Attribute and check them
3508 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3510 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3511 II->setCallingConv(CC);
3512 II->setAttributes(PAL);
3518 /// ::= 'resume' TypeAndValue
3519 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3520 Value *Exn; LocTy ExnLoc;
3521 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3524 ResumeInst *RI = ResumeInst::Create(Exn);
3529 //===----------------------------------------------------------------------===//
3530 // Binary Operators.
3531 //===----------------------------------------------------------------------===//
3534 /// ::= ArithmeticOps TypeAndValue ',' Value
3536 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3537 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3538 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3539 unsigned Opc, unsigned OperandType) {
3540 LocTy Loc; Value *LHS, *RHS;
3541 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3542 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3543 ParseValue(LHS->getType(), RHS, PFS))
3547 switch (OperandType) {
3548 default: llvm_unreachable("Unknown operand type!");
3549 case 0: // int or FP.
3550 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3551 LHS->getType()->isFPOrFPVectorTy();
3553 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3554 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3558 return Error(Loc, "invalid operand type for instruction");
3560 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3565 /// ::= ArithmeticOps TypeAndValue ',' Value {
3566 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3568 LocTy Loc; Value *LHS, *RHS;
3569 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3570 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3571 ParseValue(LHS->getType(), RHS, PFS))
3574 if (!LHS->getType()->isIntOrIntVectorTy())
3575 return Error(Loc,"instruction requires integer or integer vector operands");
3577 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3583 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3584 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3585 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3587 // Parse the integer/fp comparison predicate.
3591 if (ParseCmpPredicate(Pred, Opc) ||
3592 ParseTypeAndValue(LHS, Loc, PFS) ||
3593 ParseToken(lltok::comma, "expected ',' after compare value") ||
3594 ParseValue(LHS->getType(), RHS, PFS))
3597 if (Opc == Instruction::FCmp) {
3598 if (!LHS->getType()->isFPOrFPVectorTy())
3599 return Error(Loc, "fcmp requires floating point operands");
3600 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3602 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3603 if (!LHS->getType()->isIntOrIntVectorTy() &&
3604 !LHS->getType()->getScalarType()->isPointerTy())
3605 return Error(Loc, "icmp requires integer operands");
3606 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3611 //===----------------------------------------------------------------------===//
3612 // Other Instructions.
3613 //===----------------------------------------------------------------------===//
3617 /// ::= CastOpc TypeAndValue 'to' Type
3618 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3623 if (ParseTypeAndValue(Op, Loc, PFS) ||
3624 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3628 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3629 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3630 return Error(Loc, "invalid cast opcode for cast from '" +
3631 getTypeString(Op->getType()) + "' to '" +
3632 getTypeString(DestTy) + "'");
3634 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3639 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3640 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3642 Value *Op0, *Op1, *Op2;
3643 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3644 ParseToken(lltok::comma, "expected ',' after select condition") ||
3645 ParseTypeAndValue(Op1, PFS) ||
3646 ParseToken(lltok::comma, "expected ',' after select value") ||
3647 ParseTypeAndValue(Op2, PFS))
3650 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3651 return Error(Loc, Reason);
3653 Inst = SelectInst::Create(Op0, Op1, Op2);
3658 /// ::= 'va_arg' TypeAndValue ',' Type
3659 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3663 if (ParseTypeAndValue(Op, PFS) ||
3664 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3665 ParseType(EltTy, TypeLoc))
3668 if (!EltTy->isFirstClassType())
3669 return Error(TypeLoc, "va_arg requires operand with first class type");
3671 Inst = new VAArgInst(Op, EltTy);
3675 /// ParseExtractElement
3676 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3677 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3680 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3681 ParseToken(lltok::comma, "expected ',' after extract value") ||
3682 ParseTypeAndValue(Op1, PFS))
3685 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3686 return Error(Loc, "invalid extractelement operands");
3688 Inst = ExtractElementInst::Create(Op0, Op1);
3692 /// ParseInsertElement
3693 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3694 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3696 Value *Op0, *Op1, *Op2;
3697 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3698 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3699 ParseTypeAndValue(Op1, PFS) ||
3700 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3701 ParseTypeAndValue(Op2, PFS))
3704 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3705 return Error(Loc, "invalid insertelement operands");
3707 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3711 /// ParseShuffleVector
3712 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3713 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3715 Value *Op0, *Op1, *Op2;
3716 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3717 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3718 ParseTypeAndValue(Op1, PFS) ||
3719 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3720 ParseTypeAndValue(Op2, PFS))
3723 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3724 return Error(Loc, "invalid shufflevector operands");
3726 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3731 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3732 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3733 Type *Ty = 0; LocTy TypeLoc;
3736 if (ParseType(Ty, TypeLoc) ||
3737 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3738 ParseValue(Ty, Op0, PFS) ||
3739 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3740 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3741 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3744 bool AteExtraComma = false;
3745 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3747 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3749 if (!EatIfPresent(lltok::comma))
3752 if (Lex.getKind() == lltok::MetadataVar) {
3753 AteExtraComma = true;
3757 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3758 ParseValue(Ty, Op0, PFS) ||
3759 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3760 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3761 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3765 if (!Ty->isFirstClassType())
3766 return Error(TypeLoc, "phi node must have first class type");
3768 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3769 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3770 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3772 return AteExtraComma ? InstExtraComma : InstNormal;
3776 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3778 /// ::= 'catch' TypeAndValue
3780 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3781 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3782 Type *Ty = 0; LocTy TyLoc;
3783 Value *PersFn; LocTy PersFnLoc;
3785 if (ParseType(Ty, TyLoc) ||
3786 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3787 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3790 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3791 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3793 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3794 LandingPadInst::ClauseType CT;
3795 if (EatIfPresent(lltok::kw_catch))
3796 CT = LandingPadInst::Catch;
3797 else if (EatIfPresent(lltok::kw_filter))
3798 CT = LandingPadInst::Filter;
3800 return TokError("expected 'catch' or 'filter' clause type");
3802 Value *V; LocTy VLoc;
3803 if (ParseTypeAndValue(V, VLoc, PFS)) {
3808 // A 'catch' type expects a non-array constant. A filter clause expects an
3810 if (CT == LandingPadInst::Catch) {
3811 if (isa<ArrayType>(V->getType()))
3812 Error(VLoc, "'catch' clause has an invalid type");
3814 if (!isa<ArrayType>(V->getType()))
3815 Error(VLoc, "'filter' clause has an invalid type");
3826 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3827 /// ParameterList OptionalAttrs
3828 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3830 AttrBuilder RetAttrs, FnAttrs;
3835 SmallVector<ParamInfo, 16> ArgList;
3836 LocTy CallLoc = Lex.getLoc();
3838 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3839 ParseOptionalCallingConv(CC) ||
3840 ParseOptionalReturnAttrs(RetAttrs) ||
3841 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3842 ParseValID(CalleeID) ||
3843 ParseParameterList(ArgList, PFS) ||
3844 ParseOptionalFuncAttrs(FnAttrs))
3847 // If RetType is a non-function pointer type, then this is the short syntax
3848 // for the call, which means that RetType is just the return type. Infer the
3849 // rest of the function argument types from the arguments that are present.
3850 PointerType *PFTy = 0;
3851 FunctionType *Ty = 0;
3852 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3853 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3854 // Pull out the types of all of the arguments...
3855 std::vector<Type*> ParamTypes;
3856 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3857 ParamTypes.push_back(ArgList[i].V->getType());
3859 if (!FunctionType::isValidReturnType(RetType))
3860 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3862 Ty = FunctionType::get(RetType, ParamTypes, false);
3863 PFTy = PointerType::getUnqual(Ty);
3866 // Look up the callee.
3868 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3870 // Set up the Attribute for the function.
3871 SmallVector<AttributeSet, 8> Attrs;
3872 if (RetAttrs.hasAttributes())
3873 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3874 AttributeSet::ReturnIndex,
3877 SmallVector<Value*, 8> Args;
3879 // Loop through FunctionType's arguments and ensure they are specified
3880 // correctly. Also, gather any parameter attributes.
3881 FunctionType::param_iterator I = Ty->param_begin();
3882 FunctionType::param_iterator E = Ty->param_end();
3883 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3884 Type *ExpectedTy = 0;
3887 } else if (!Ty->isVarArg()) {
3888 return Error(ArgList[i].Loc, "too many arguments specified");
3891 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3892 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3893 getTypeString(ExpectedTy) + "'");
3894 Args.push_back(ArgList[i].V);
3895 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3896 AttrBuilder B(ArgList[i].Attrs, i + 1);
3897 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3902 return Error(CallLoc, "not enough parameters specified for call");
3904 if (FnAttrs.hasAttributes())
3905 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3906 AttributeSet::FunctionIndex,
3909 // Finish off the Attribute and check them
3910 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3912 CallInst *CI = CallInst::Create(Callee, Args);
3913 CI->setTailCall(isTail);
3914 CI->setCallingConv(CC);
3915 CI->setAttributes(PAL);
3920 //===----------------------------------------------------------------------===//
3921 // Memory Instructions.
3922 //===----------------------------------------------------------------------===//
3925 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3926 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3929 unsigned Alignment = 0;
3931 if (ParseType(Ty)) return true;
3933 bool AteExtraComma = false;
3934 if (EatIfPresent(lltok::comma)) {
3935 if (Lex.getKind() == lltok::kw_align) {
3936 if (ParseOptionalAlignment(Alignment)) return true;
3937 } else if (Lex.getKind() == lltok::MetadataVar) {
3938 AteExtraComma = true;
3940 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3941 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3946 if (Size && !Size->getType()->isIntegerTy())
3947 return Error(SizeLoc, "element count must have integer type");
3949 Inst = new AllocaInst(Ty, Size, Alignment);
3950 return AteExtraComma ? InstExtraComma : InstNormal;
3954 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3955 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3956 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3957 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
3958 Value *Val; LocTy Loc;
3959 unsigned Alignment = 0;
3960 bool AteExtraComma = false;
3961 bool isAtomic = false;
3962 AtomicOrdering Ordering = NotAtomic;
3963 SynchronizationScope Scope = CrossThread;
3965 if (Lex.getKind() == lltok::kw_atomic) {
3970 bool isVolatile = false;
3971 if (Lex.getKind() == lltok::kw_volatile) {
3976 if (ParseTypeAndValue(Val, Loc, PFS) ||
3977 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3978 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3981 if (!Val->getType()->isPointerTy() ||
3982 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3983 return Error(Loc, "load operand must be a pointer to a first class type");
3984 if (isAtomic && !Alignment)
3985 return Error(Loc, "atomic load must have explicit non-zero alignment");
3986 if (Ordering == Release || Ordering == AcquireRelease)
3987 return Error(Loc, "atomic load cannot use Release ordering");
3989 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
3990 return AteExtraComma ? InstExtraComma : InstNormal;
3995 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3996 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
3997 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3998 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
3999 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4000 unsigned Alignment = 0;
4001 bool AteExtraComma = false;
4002 bool isAtomic = false;
4003 AtomicOrdering Ordering = NotAtomic;
4004 SynchronizationScope Scope = CrossThread;
4006 if (Lex.getKind() == lltok::kw_atomic) {
4011 bool isVolatile = false;
4012 if (Lex.getKind() == lltok::kw_volatile) {
4017 if (ParseTypeAndValue(Val, Loc, PFS) ||
4018 ParseToken(lltok::comma, "expected ',' after store operand") ||
4019 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4020 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4021 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4024 if (!Ptr->getType()->isPointerTy())
4025 return Error(PtrLoc, "store operand must be a pointer");
4026 if (!Val->getType()->isFirstClassType())
4027 return Error(Loc, "store operand must be a first class value");
4028 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4029 return Error(Loc, "stored value and pointer type do not match");
4030 if (isAtomic && !Alignment)
4031 return Error(Loc, "atomic store must have explicit non-zero alignment");
4032 if (Ordering == Acquire || Ordering == AcquireRelease)
4033 return Error(Loc, "atomic store cannot use Acquire ordering");
4035 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4036 return AteExtraComma ? InstExtraComma : InstNormal;
4040 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4041 /// 'singlethread'? AtomicOrdering
4042 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4043 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4044 bool AteExtraComma = false;
4045 AtomicOrdering Ordering = NotAtomic;
4046 SynchronizationScope Scope = CrossThread;
4047 bool isVolatile = false;
4049 if (EatIfPresent(lltok::kw_volatile))
4052 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4053 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4054 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4055 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4056 ParseTypeAndValue(New, NewLoc, PFS) ||
4057 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4060 if (Ordering == Unordered)
4061 return TokError("cmpxchg cannot be unordered");
4062 if (!Ptr->getType()->isPointerTy())
4063 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4064 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4065 return Error(CmpLoc, "compare value and pointer type do not match");
4066 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4067 return Error(NewLoc, "new value and pointer type do not match");
4068 if (!New->getType()->isIntegerTy())
4069 return Error(NewLoc, "cmpxchg operand must be an integer");
4070 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4071 if (Size < 8 || (Size & (Size - 1)))
4072 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4075 AtomicCmpXchgInst *CXI =
4076 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
4077 CXI->setVolatile(isVolatile);
4079 return AteExtraComma ? InstExtraComma : InstNormal;
4083 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4084 /// 'singlethread'? AtomicOrdering
4085 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4086 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4087 bool AteExtraComma = false;
4088 AtomicOrdering Ordering = NotAtomic;
4089 SynchronizationScope Scope = CrossThread;
4090 bool isVolatile = false;
4091 AtomicRMWInst::BinOp Operation;
4093 if (EatIfPresent(lltok::kw_volatile))
4096 switch (Lex.getKind()) {
4097 default: return TokError("expected binary operation in atomicrmw");
4098 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4099 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4100 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4101 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4102 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4103 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4104 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4105 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4106 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4107 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4108 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4110 Lex.Lex(); // Eat the operation.
4112 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4113 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4114 ParseTypeAndValue(Val, ValLoc, PFS) ||
4115 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4118 if (Ordering == Unordered)
4119 return TokError("atomicrmw cannot be unordered");
4120 if (!Ptr->getType()->isPointerTy())
4121 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4122 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4123 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4124 if (!Val->getType()->isIntegerTy())
4125 return Error(ValLoc, "atomicrmw operand must be an integer");
4126 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4127 if (Size < 8 || (Size & (Size - 1)))
4128 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4131 AtomicRMWInst *RMWI =
4132 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4133 RMWI->setVolatile(isVolatile);
4135 return AteExtraComma ? InstExtraComma : InstNormal;
4139 /// ::= 'fence' 'singlethread'? AtomicOrdering
4140 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4141 AtomicOrdering Ordering = NotAtomic;
4142 SynchronizationScope Scope = CrossThread;
4143 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4146 if (Ordering == Unordered)
4147 return TokError("fence cannot be unordered");
4148 if (Ordering == Monotonic)
4149 return TokError("fence cannot be monotonic");
4151 Inst = new FenceInst(Context, Ordering, Scope);
4155 /// ParseGetElementPtr
4156 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4157 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4162 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4164 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4166 if (!Ptr->getType()->getScalarType()->isPointerTy())
4167 return Error(Loc, "base of getelementptr must be a pointer");
4169 SmallVector<Value*, 16> Indices;
4170 bool AteExtraComma = false;
4171 while (EatIfPresent(lltok::comma)) {
4172 if (Lex.getKind() == lltok::MetadataVar) {
4173 AteExtraComma = true;
4176 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4177 if (!Val->getType()->getScalarType()->isIntegerTy())
4178 return Error(EltLoc, "getelementptr index must be an integer");
4179 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4180 return Error(EltLoc, "getelementptr index type missmatch");
4181 if (Val->getType()->isVectorTy()) {
4182 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4183 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4184 if (ValNumEl != PtrNumEl)
4185 return Error(EltLoc,
4186 "getelementptr vector index has a wrong number of elements");
4188 Indices.push_back(Val);
4191 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
4192 return Error(Loc, "invalid getelementptr indices");
4193 Inst = GetElementPtrInst::Create(Ptr, Indices);
4195 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4196 return AteExtraComma ? InstExtraComma : InstNormal;
4199 /// ParseExtractValue
4200 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4201 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4202 Value *Val; LocTy Loc;
4203 SmallVector<unsigned, 4> Indices;
4205 if (ParseTypeAndValue(Val, Loc, PFS) ||
4206 ParseIndexList(Indices, AteExtraComma))
4209 if (!Val->getType()->isAggregateType())
4210 return Error(Loc, "extractvalue operand must be aggregate type");
4212 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4213 return Error(Loc, "invalid indices for extractvalue");
4214 Inst = ExtractValueInst::Create(Val, Indices);
4215 return AteExtraComma ? InstExtraComma : InstNormal;
4218 /// ParseInsertValue
4219 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4220 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4221 Value *Val0, *Val1; LocTy Loc0, Loc1;
4222 SmallVector<unsigned, 4> Indices;
4224 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4225 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4226 ParseTypeAndValue(Val1, Loc1, PFS) ||
4227 ParseIndexList(Indices, AteExtraComma))
4230 if (!Val0->getType()->isAggregateType())
4231 return Error(Loc0, "insertvalue operand must be aggregate type");
4233 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4234 return Error(Loc0, "invalid indices for insertvalue");
4235 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4236 return AteExtraComma ? InstExtraComma : InstNormal;
4239 //===----------------------------------------------------------------------===//
4240 // Embedded metadata.
4241 //===----------------------------------------------------------------------===//
4243 /// ParseMDNodeVector
4244 /// ::= Element (',' Element)*
4246 /// ::= 'null' | TypeAndValue
4247 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4248 PerFunctionState *PFS) {
4249 // Check for an empty list.
4250 if (Lex.getKind() == lltok::rbrace)
4254 // Null is a special case since it is typeless.
4255 if (EatIfPresent(lltok::kw_null)) {
4261 if (ParseTypeAndValue(V, PFS)) return true;
4263 } while (EatIfPresent(lltok::comma));