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/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
29 /// Run: module ::= toplevelentity*
30 bool LLParser::Run() {
34 return ParseTopLevelEntities() ||
35 ValidateEndOfModule();
38 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
40 bool LLParser::ValidateEndOfModule() {
41 // Handle any instruction metadata forward references.
42 if (!ForwardRefInstMetadata.empty()) {
43 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
44 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
46 Instruction *Inst = I->first;
47 const std::vector<MDRef> &MDList = I->second;
49 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
50 unsigned SlotNo = MDList[i].MDSlot;
52 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
53 return Error(MDList[i].Loc, "use of undefined metadata '!" +
55 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
58 ForwardRefInstMetadata.clear();
62 // If there are entries in ForwardRefBlockAddresses at this point, they are
63 // references after the function was defined. Resolve those now.
64 while (!ForwardRefBlockAddresses.empty()) {
65 // Okay, we are referencing an already-parsed function, resolve them now.
67 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
68 if (Fn.Kind == ValID::t_GlobalName)
69 TheFn = M->getFunction(Fn.StrVal);
70 else if (Fn.UIntVal < NumberedVals.size())
71 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
74 return Error(Fn.Loc, "unknown function referenced by blockaddress");
76 // Resolve all these references.
77 if (ResolveForwardRefBlockAddresses(TheFn,
78 ForwardRefBlockAddresses.begin()->second,
82 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
86 if (!ForwardRefTypes.empty())
87 return Error(ForwardRefTypes.begin()->second.second,
88 "use of undefined type named '" +
89 ForwardRefTypes.begin()->first + "'");
90 if (!ForwardRefTypeIDs.empty())
91 return Error(ForwardRefTypeIDs.begin()->second.second,
92 "use of undefined type '%" +
93 Twine(ForwardRefTypeIDs.begin()->first) + "'");
95 if (!ForwardRefVals.empty())
96 return Error(ForwardRefVals.begin()->second.second,
97 "use of undefined value '@" + ForwardRefVals.begin()->first +
100 if (!ForwardRefValIDs.empty())
101 return Error(ForwardRefValIDs.begin()->second.second,
102 "use of undefined value '@" +
103 Twine(ForwardRefValIDs.begin()->first) + "'");
105 if (!ForwardRefMDNodes.empty())
106 return Error(ForwardRefMDNodes.begin()->second.second,
107 "use of undefined metadata '!" +
108 Twine(ForwardRefMDNodes.begin()->first) + "'");
111 // Look for intrinsic functions and CallInst that need to be upgraded
112 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
113 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
115 // Check debug info intrinsics.
116 CheckDebugInfoIntrinsics(M);
120 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
121 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
122 PerFunctionState *PFS) {
123 // Loop over all the references, resolving them.
124 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
127 if (Refs[i].first.Kind == ValID::t_LocalName)
128 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
130 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
131 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
132 return Error(Refs[i].first.Loc,
133 "cannot take address of numeric label after the function is defined");
135 Res = dyn_cast_or_null<BasicBlock>(
136 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
140 return Error(Refs[i].first.Loc,
141 "referenced value is not a basic block");
143 // Get the BlockAddress for this and update references to use it.
144 BlockAddress *BA = BlockAddress::get(TheFn, Res);
145 Refs[i].second->replaceAllUsesWith(BA);
146 Refs[i].second->eraseFromParent();
152 //===----------------------------------------------------------------------===//
153 // Top-Level Entities
154 //===----------------------------------------------------------------------===//
156 bool LLParser::ParseTopLevelEntities() {
158 switch (Lex.getKind()) {
159 default: return TokError("expected top-level entity");
160 case lltok::Eof: return false;
161 case lltok::kw_declare: if (ParseDeclare()) return true; break;
162 case lltok::kw_define: if (ParseDefine()) return true; break;
163 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
164 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
165 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
166 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
167 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
168 case lltok::LocalVar: if (ParseNamedType()) return true; break;
169 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
170 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
171 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
172 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
174 // The Global variable production with no name can have many different
175 // optional leading prefixes, the production is:
176 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
177 // OptionalAddrSpace OptionalUnNammedAddr
178 // ('constant'|'global') ...
179 case lltok::kw_private: // OptionalLinkage
180 case lltok::kw_linker_private: // OptionalLinkage
181 case lltok::kw_linker_private_weak: // OptionalLinkage
182 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
183 case lltok::kw_internal: // OptionalLinkage
184 case lltok::kw_weak: // OptionalLinkage
185 case lltok::kw_weak_odr: // OptionalLinkage
186 case lltok::kw_linkonce: // OptionalLinkage
187 case lltok::kw_linkonce_odr: // OptionalLinkage
188 case lltok::kw_appending: // OptionalLinkage
189 case lltok::kw_dllexport: // OptionalLinkage
190 case lltok::kw_common: // OptionalLinkage
191 case lltok::kw_dllimport: // OptionalLinkage
192 case lltok::kw_extern_weak: // OptionalLinkage
193 case lltok::kw_external: { // OptionalLinkage
194 unsigned Linkage, Visibility;
195 if (ParseOptionalLinkage(Linkage) ||
196 ParseOptionalVisibility(Visibility) ||
197 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
201 case lltok::kw_default: // OptionalVisibility
202 case lltok::kw_hidden: // OptionalVisibility
203 case lltok::kw_protected: { // OptionalVisibility
205 if (ParseOptionalVisibility(Visibility) ||
206 ParseGlobal("", SMLoc(), 0, false, Visibility))
211 case lltok::kw_thread_local: // OptionalThreadLocal
212 case lltok::kw_addrspace: // OptionalAddrSpace
213 case lltok::kw_constant: // GlobalType
214 case lltok::kw_global: // GlobalType
215 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
223 /// ::= 'module' 'asm' STRINGCONSTANT
224 bool LLParser::ParseModuleAsm() {
225 assert(Lex.getKind() == lltok::kw_module);
229 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
230 ParseStringConstant(AsmStr)) return true;
232 M->appendModuleInlineAsm(AsmStr);
237 /// ::= 'target' 'triple' '=' STRINGCONSTANT
238 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
239 bool LLParser::ParseTargetDefinition() {
240 assert(Lex.getKind() == lltok::kw_target);
243 default: return TokError("unknown target property");
244 case lltok::kw_triple:
246 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
247 ParseStringConstant(Str))
249 M->setTargetTriple(Str);
251 case lltok::kw_datalayout:
253 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
254 ParseStringConstant(Str))
256 M->setDataLayout(Str);
262 /// ::= 'deplibs' '=' '[' ']'
263 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
264 bool LLParser::ParseDepLibs() {
265 assert(Lex.getKind() == lltok::kw_deplibs);
267 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
268 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
271 if (EatIfPresent(lltok::rsquare))
275 if (ParseStringConstant(Str)) return true;
278 while (EatIfPresent(lltok::comma)) {
279 if (ParseStringConstant(Str)) return true;
283 return ParseToken(lltok::rsquare, "expected ']' at end of list");
286 /// ParseUnnamedType:
288 /// ::= LocalVarID '=' 'type' type
289 bool LLParser::ParseUnnamedType() {
290 unsigned TypeID = NumberedTypes.size();
292 // Handle the LocalVarID form.
293 if (Lex.getKind() == lltok::LocalVarID) {
294 if (Lex.getUIntVal() != TypeID)
295 return Error(Lex.getLoc(), "type expected to be numbered '%" +
296 Twine(TypeID) + "'");
297 Lex.Lex(); // eat LocalVarID;
299 if (ParseToken(lltok::equal, "expected '=' after name"))
303 LocTy TypeLoc = Lex.getLoc();
304 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
306 PATypeHolder Ty(Type::getVoidTy(Context));
307 if (ParseType(Ty)) return true;
309 // See if this type was previously referenced.
310 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
311 FI = ForwardRefTypeIDs.find(TypeID);
312 if (FI != ForwardRefTypeIDs.end()) {
313 if (FI->second.first.get() == Ty)
314 return Error(TypeLoc, "self referential type is invalid");
316 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
317 Ty = FI->second.first.get();
318 ForwardRefTypeIDs.erase(FI);
321 NumberedTypes.push_back(Ty);
327 /// ::= LocalVar '=' 'type' type
328 bool LLParser::ParseNamedType() {
329 std::string Name = Lex.getStrVal();
330 LocTy NameLoc = Lex.getLoc();
331 Lex.Lex(); // eat LocalVar.
333 PATypeHolder Ty(Type::getVoidTy(Context));
335 if (ParseToken(lltok::equal, "expected '=' after name") ||
336 ParseToken(lltok::kw_type, "expected 'type' after name") ||
340 // Set the type name, checking for conflicts as we do so.
341 bool AlreadyExists = M->addTypeName(Name, Ty);
342 if (!AlreadyExists) return false;
344 // See if this type is a forward reference. We need to eagerly resolve
345 // types to allow recursive type redefinitions below.
346 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
347 FI = ForwardRefTypes.find(Name);
348 if (FI != ForwardRefTypes.end()) {
349 if (FI->second.first.get() == Ty)
350 return Error(NameLoc, "self referential type is invalid");
352 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
353 Ty = FI->second.first.get();
354 ForwardRefTypes.erase(FI);
357 // Inserting a name that is already defined, get the existing name.
358 const Type *Existing = M->getTypeByName(Name);
359 assert(Existing && "Conflict but no matching type?!");
361 // Otherwise, this is an attempt to redefine a type. That's okay if
362 // the redefinition is identical to the original.
363 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
364 if (Existing == Ty) return false;
366 // Any other kind of (non-equivalent) redefinition is an error.
367 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
368 Ty->getDescription() + "'");
373 /// ::= 'declare' FunctionHeader
374 bool LLParser::ParseDeclare() {
375 assert(Lex.getKind() == lltok::kw_declare);
379 return ParseFunctionHeader(F, false);
383 /// ::= 'define' FunctionHeader '{' ...
384 bool LLParser::ParseDefine() {
385 assert(Lex.getKind() == lltok::kw_define);
389 return ParseFunctionHeader(F, true) ||
390 ParseFunctionBody(*F);
396 bool LLParser::ParseGlobalType(bool &IsConstant) {
397 if (Lex.getKind() == lltok::kw_constant)
399 else if (Lex.getKind() == lltok::kw_global)
403 return TokError("expected 'global' or 'constant'");
409 /// ParseUnnamedGlobal:
410 /// OptionalVisibility ALIAS ...
411 /// OptionalLinkage OptionalVisibility ... -> global variable
412 /// GlobalID '=' OptionalVisibility ALIAS ...
413 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
414 bool LLParser::ParseUnnamedGlobal() {
415 unsigned VarID = NumberedVals.size();
417 LocTy NameLoc = Lex.getLoc();
419 // Handle the GlobalID form.
420 if (Lex.getKind() == lltok::GlobalID) {
421 if (Lex.getUIntVal() != VarID)
422 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
424 Lex.Lex(); // eat GlobalID;
426 if (ParseToken(lltok::equal, "expected '=' after name"))
431 unsigned Linkage, Visibility;
432 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
433 ParseOptionalVisibility(Visibility))
436 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
437 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
438 return ParseAlias(Name, NameLoc, Visibility);
441 /// ParseNamedGlobal:
442 /// GlobalVar '=' OptionalVisibility ALIAS ...
443 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
444 bool LLParser::ParseNamedGlobal() {
445 assert(Lex.getKind() == lltok::GlobalVar);
446 LocTy NameLoc = Lex.getLoc();
447 std::string Name = Lex.getStrVal();
451 unsigned Linkage, Visibility;
452 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
453 ParseOptionalLinkage(Linkage, HasLinkage) ||
454 ParseOptionalVisibility(Visibility))
457 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
458 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
459 return ParseAlias(Name, NameLoc, Visibility);
463 // ::= '!' STRINGCONSTANT
464 bool LLParser::ParseMDString(MDString *&Result) {
466 if (ParseStringConstant(Str)) return true;
467 Result = MDString::get(Context, Str);
472 // ::= '!' MDNodeNumber
474 /// This version of ParseMDNodeID returns the slot number and null in the case
475 /// of a forward reference.
476 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
477 // !{ ..., !42, ... }
478 if (ParseUInt32(SlotNo)) return true;
480 // Check existing MDNode.
481 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
482 Result = NumberedMetadata[SlotNo];
488 bool LLParser::ParseMDNodeID(MDNode *&Result) {
489 // !{ ..., !42, ... }
491 if (ParseMDNodeID(Result, MID)) return true;
493 // If not a forward reference, just return it now.
494 if (Result) return false;
496 // Otherwise, create MDNode forward reference.
497 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
498 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
500 if (NumberedMetadata.size() <= MID)
501 NumberedMetadata.resize(MID+1);
502 NumberedMetadata[MID] = FwdNode;
507 /// ParseNamedMetadata:
508 /// !foo = !{ !1, !2 }
509 bool LLParser::ParseNamedMetadata() {
510 assert(Lex.getKind() == lltok::MetadataVar);
511 std::string Name = Lex.getStrVal();
514 if (ParseToken(lltok::equal, "expected '=' here") ||
515 ParseToken(lltok::exclaim, "Expected '!' here") ||
516 ParseToken(lltok::lbrace, "Expected '{' here"))
519 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
520 if (Lex.getKind() != lltok::rbrace)
522 if (ParseToken(lltok::exclaim, "Expected '!' here"))
526 if (ParseMDNodeID(N)) return true;
528 } while (EatIfPresent(lltok::comma));
530 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
536 /// ParseStandaloneMetadata:
538 bool LLParser::ParseStandaloneMetadata() {
539 assert(Lex.getKind() == lltok::exclaim);
541 unsigned MetadataID = 0;
544 PATypeHolder Ty(Type::getVoidTy(Context));
545 SmallVector<Value *, 16> Elts;
546 if (ParseUInt32(MetadataID) ||
547 ParseToken(lltok::equal, "expected '=' here") ||
548 ParseType(Ty, TyLoc) ||
549 ParseToken(lltok::exclaim, "Expected '!' here") ||
550 ParseToken(lltok::lbrace, "Expected '{' here") ||
551 ParseMDNodeVector(Elts, NULL) ||
552 ParseToken(lltok::rbrace, "expected end of metadata node"))
555 MDNode *Init = MDNode::get(Context, Elts);
557 // See if this was forward referenced, if so, handle it.
558 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
559 FI = ForwardRefMDNodes.find(MetadataID);
560 if (FI != ForwardRefMDNodes.end()) {
561 MDNode *Temp = FI->second.first;
562 Temp->replaceAllUsesWith(Init);
563 MDNode::deleteTemporary(Temp);
564 ForwardRefMDNodes.erase(FI);
566 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
568 if (MetadataID >= NumberedMetadata.size())
569 NumberedMetadata.resize(MetadataID+1);
571 if (NumberedMetadata[MetadataID] != 0)
572 return TokError("Metadata id is already used");
573 NumberedMetadata[MetadataID] = Init;
580 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
583 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
584 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
586 /// Everything through visibility has already been parsed.
588 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
589 unsigned Visibility) {
590 assert(Lex.getKind() == lltok::kw_alias);
593 LocTy LinkageLoc = Lex.getLoc();
594 if (ParseOptionalLinkage(Linkage))
597 if (Linkage != GlobalValue::ExternalLinkage &&
598 Linkage != GlobalValue::WeakAnyLinkage &&
599 Linkage != GlobalValue::WeakODRLinkage &&
600 Linkage != GlobalValue::InternalLinkage &&
601 Linkage != GlobalValue::PrivateLinkage &&
602 Linkage != GlobalValue::LinkerPrivateLinkage &&
603 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
604 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
605 return Error(LinkageLoc, "invalid linkage type for alias");
608 LocTy AliaseeLoc = Lex.getLoc();
609 if (Lex.getKind() != lltok::kw_bitcast &&
610 Lex.getKind() != lltok::kw_getelementptr) {
611 if (ParseGlobalTypeAndValue(Aliasee)) return true;
613 // The bitcast dest type is not present, it is implied by the dest type.
615 if (ParseValID(ID)) return true;
616 if (ID.Kind != ValID::t_Constant)
617 return Error(AliaseeLoc, "invalid aliasee");
618 Aliasee = ID.ConstantVal;
621 if (!Aliasee->getType()->isPointerTy())
622 return Error(AliaseeLoc, "alias must have pointer type");
624 // Okay, create the alias but do not insert it into the module yet.
625 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
626 (GlobalValue::LinkageTypes)Linkage, Name,
628 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
630 // See if this value already exists in the symbol table. If so, it is either
631 // a redefinition or a definition of a forward reference.
632 if (GlobalValue *Val = M->getNamedValue(Name)) {
633 // See if this was a redefinition. If so, there is no entry in
635 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
636 I = ForwardRefVals.find(Name);
637 if (I == ForwardRefVals.end())
638 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
640 // Otherwise, this was a definition of forward ref. Verify that types
642 if (Val->getType() != GA->getType())
643 return Error(NameLoc,
644 "forward reference and definition of alias have different types");
646 // If they agree, just RAUW the old value with the alias and remove the
648 Val->replaceAllUsesWith(GA);
649 Val->eraseFromParent();
650 ForwardRefVals.erase(I);
653 // Insert into the module, we know its name won't collide now.
654 M->getAliasList().push_back(GA);
655 assert(GA->getName() == Name && "Should not be a name conflict!");
661 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
662 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
663 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
664 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
666 /// Everything through visibility has been parsed already.
668 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
669 unsigned Linkage, bool HasLinkage,
670 unsigned Visibility) {
672 bool ThreadLocal, IsConstant, UnnamedAddr;
673 LocTy UnnamedAddrLoc;
676 PATypeHolder Ty(Type::getVoidTy(Context));
677 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
678 ParseOptionalAddrSpace(AddrSpace) ||
679 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
681 ParseGlobalType(IsConstant) ||
682 ParseType(Ty, TyLoc))
685 // If the linkage is specified and is external, then no initializer is
688 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
689 Linkage != GlobalValue::ExternalWeakLinkage &&
690 Linkage != GlobalValue::ExternalLinkage)) {
691 if (ParseGlobalValue(Ty, Init))
695 if (Ty->isFunctionTy() || Ty->isLabelTy())
696 return Error(TyLoc, "invalid type for global variable");
698 GlobalVariable *GV = 0;
700 // See if the global was forward referenced, if so, use the global.
702 if (GlobalValue *GVal = M->getNamedValue(Name)) {
703 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
704 return Error(NameLoc, "redefinition of global '@" + Name + "'");
705 GV = cast<GlobalVariable>(GVal);
708 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
709 I = ForwardRefValIDs.find(NumberedVals.size());
710 if (I != ForwardRefValIDs.end()) {
711 GV = cast<GlobalVariable>(I->second.first);
712 ForwardRefValIDs.erase(I);
717 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
718 Name, 0, false, AddrSpace);
720 if (GV->getType()->getElementType() != Ty)
722 "forward reference and definition of global have different types");
724 // Move the forward-reference to the correct spot in the module.
725 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
729 NumberedVals.push_back(GV);
731 // Set the parsed properties on the global.
733 GV->setInitializer(Init);
734 GV->setConstant(IsConstant);
735 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
736 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
737 GV->setThreadLocal(ThreadLocal);
738 GV->setUnnamedAddr(UnnamedAddr);
740 // Parse attributes on the global.
741 while (Lex.getKind() == lltok::comma) {
744 if (Lex.getKind() == lltok::kw_section) {
746 GV->setSection(Lex.getStrVal());
747 if (ParseToken(lltok::StringConstant, "expected global section string"))
749 } else if (Lex.getKind() == lltok::kw_align) {
751 if (ParseOptionalAlignment(Alignment)) return true;
752 GV->setAlignment(Alignment);
754 TokError("unknown global variable property!");
762 //===----------------------------------------------------------------------===//
763 // GlobalValue Reference/Resolution Routines.
764 //===----------------------------------------------------------------------===//
766 /// GetGlobalVal - Get a value with the specified name or ID, creating a
767 /// forward reference record if needed. This can return null if the value
768 /// exists but does not have the right type.
769 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
771 const PointerType *PTy = dyn_cast<PointerType>(Ty);
773 Error(Loc, "global variable reference must have pointer type");
777 // Look this name up in the normal function symbol table.
779 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
781 // If this is a forward reference for the value, see if we already created a
782 // forward ref record.
784 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
785 I = ForwardRefVals.find(Name);
786 if (I != ForwardRefVals.end())
787 Val = I->second.first;
790 // If we have the value in the symbol table or fwd-ref table, return it.
792 if (Val->getType() == Ty) return Val;
793 Error(Loc, "'@" + Name + "' defined with type '" +
794 Val->getType()->getDescription() + "'");
798 // Otherwise, create a new forward reference for this value and remember it.
800 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
801 // Function types can return opaque but functions can't.
802 if (FT->getReturnType()->isOpaqueTy()) {
803 Error(Loc, "function may not return opaque type");
807 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
809 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
810 GlobalValue::ExternalWeakLinkage, 0, Name);
813 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
817 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
818 const PointerType *PTy = dyn_cast<PointerType>(Ty);
820 Error(Loc, "global variable reference must have pointer type");
824 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
826 // If this is a forward reference for the value, see if we already created a
827 // forward ref record.
829 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
830 I = ForwardRefValIDs.find(ID);
831 if (I != ForwardRefValIDs.end())
832 Val = I->second.first;
835 // If we have the value in the symbol table or fwd-ref table, return it.
837 if (Val->getType() == Ty) return Val;
838 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
839 Val->getType()->getDescription() + "'");
843 // Otherwise, create a new forward reference for this value and remember it.
845 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
846 // Function types can return opaque but functions can't.
847 if (FT->getReturnType()->isOpaqueTy()) {
848 Error(Loc, "function may not return opaque type");
851 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
853 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
854 GlobalValue::ExternalWeakLinkage, 0, "");
857 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
862 //===----------------------------------------------------------------------===//
864 //===----------------------------------------------------------------------===//
866 /// ParseToken - If the current token has the specified kind, eat it and return
867 /// success. Otherwise, emit the specified error and return failure.
868 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
869 if (Lex.getKind() != T)
870 return TokError(ErrMsg);
875 /// ParseStringConstant
876 /// ::= StringConstant
877 bool LLParser::ParseStringConstant(std::string &Result) {
878 if (Lex.getKind() != lltok::StringConstant)
879 return TokError("expected string constant");
880 Result = Lex.getStrVal();
887 bool LLParser::ParseUInt32(unsigned &Val) {
888 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
889 return TokError("expected integer");
890 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
891 if (Val64 != unsigned(Val64))
892 return TokError("expected 32-bit integer (too large)");
899 /// ParseOptionalAddrSpace
901 /// := 'addrspace' '(' uint32 ')'
902 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
904 if (!EatIfPresent(lltok::kw_addrspace))
906 return ParseToken(lltok::lparen, "expected '(' in address space") ||
907 ParseUInt32(AddrSpace) ||
908 ParseToken(lltok::rparen, "expected ')' in address space");
911 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
912 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
913 /// 2: function attr.
914 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
915 Attrs = Attribute::None;
916 LocTy AttrLoc = Lex.getLoc();
919 switch (Lex.getKind()) {
920 default: // End of attributes.
921 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
922 return Error(AttrLoc, "invalid use of function-only attribute");
924 // As a hack, we allow "align 2" on functions as a synonym for
927 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
928 return Error(AttrLoc, "invalid use of attribute on a function");
930 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
931 return Error(AttrLoc, "invalid use of parameter-only attribute");
934 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
935 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
936 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
937 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
938 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
939 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
940 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
941 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
943 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
944 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
945 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
946 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
947 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
948 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
949 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
950 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
951 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
952 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
953 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
954 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
955 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
956 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
957 case lltok::kw_hotpatch: Attrs |= Attribute::Hotpatch; break;
958 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
960 case lltok::kw_alignstack: {
962 if (ParseOptionalStackAlignment(Alignment))
964 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
968 case lltok::kw_align: {
970 if (ParseOptionalAlignment(Alignment))
972 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
981 /// ParseOptionalLinkage
984 /// ::= 'linker_private'
985 /// ::= 'linker_private_weak'
986 /// ::= 'linker_private_weak_def_auto'
991 /// ::= 'linkonce_odr'
992 /// ::= 'available_externally'
997 /// ::= 'extern_weak'
999 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1001 switch (Lex.getKind()) {
1002 default: Res=GlobalValue::ExternalLinkage; return false;
1003 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1004 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1005 case lltok::kw_linker_private_weak:
1006 Res = GlobalValue::LinkerPrivateWeakLinkage;
1008 case lltok::kw_linker_private_weak_def_auto:
1009 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1011 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1012 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1013 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1014 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1015 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1016 case lltok::kw_available_externally:
1017 Res = GlobalValue::AvailableExternallyLinkage;
1019 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1020 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1021 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1022 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1023 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1024 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1031 /// ParseOptionalVisibility
1037 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1038 switch (Lex.getKind()) {
1039 default: Res = GlobalValue::DefaultVisibility; return false;
1040 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1041 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1042 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1048 /// ParseOptionalCallingConv
1053 /// ::= 'x86_stdcallcc'
1054 /// ::= 'x86_fastcallcc'
1055 /// ::= 'x86_thiscallcc'
1056 /// ::= 'arm_apcscc'
1057 /// ::= 'arm_aapcscc'
1058 /// ::= 'arm_aapcs_vfpcc'
1059 /// ::= 'msp430_intrcc'
1060 /// ::= 'ptx_kernel'
1061 /// ::= 'ptx_device'
1064 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1065 switch (Lex.getKind()) {
1066 default: CC = CallingConv::C; return false;
1067 case lltok::kw_ccc: CC = CallingConv::C; break;
1068 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1069 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1070 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1071 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1072 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1073 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1074 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1075 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1076 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1077 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1078 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1079 case lltok::kw_cc: {
1080 unsigned ArbitraryCC;
1082 if (ParseUInt32(ArbitraryCC)) {
1085 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1095 /// ParseInstructionMetadata
1096 /// ::= !dbg !42 (',' !dbg !57)*
1097 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1098 PerFunctionState *PFS) {
1100 if (Lex.getKind() != lltok::MetadataVar)
1101 return TokError("expected metadata after comma");
1103 std::string Name = Lex.getStrVal();
1104 unsigned MDK = M->getMDKindID(Name.c_str());
1108 SMLoc Loc = Lex.getLoc();
1110 if (ParseToken(lltok::exclaim, "expected '!' here"))
1113 // This code is similar to that of ParseMetadataValue, however it needs to
1114 // have special-case code for a forward reference; see the comments on
1115 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1116 // at the top level here.
1117 if (Lex.getKind() == lltok::lbrace) {
1119 if (ParseMetadataListValue(ID, PFS))
1121 assert(ID.Kind == ValID::t_MDNode);
1122 Inst->setMetadata(MDK, ID.MDNodeVal);
1124 unsigned NodeID = 0;
1125 if (ParseMDNodeID(Node, NodeID))
1128 // If we got the node, add it to the instruction.
1129 Inst->setMetadata(MDK, Node);
1131 MDRef R = { Loc, MDK, NodeID };
1132 // Otherwise, remember that this should be resolved later.
1133 ForwardRefInstMetadata[Inst].push_back(R);
1137 // If this is the end of the list, we're done.
1138 } while (EatIfPresent(lltok::comma));
1142 /// ParseOptionalAlignment
1145 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1147 if (!EatIfPresent(lltok::kw_align))
1149 LocTy AlignLoc = Lex.getLoc();
1150 if (ParseUInt32(Alignment)) return true;
1151 if (!isPowerOf2_32(Alignment))
1152 return Error(AlignLoc, "alignment is not a power of two");
1153 if (Alignment > Value::MaximumAlignment)
1154 return Error(AlignLoc, "huge alignments are not supported yet");
1158 /// ParseOptionalCommaAlign
1162 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1164 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1165 bool &AteExtraComma) {
1166 AteExtraComma = false;
1167 while (EatIfPresent(lltok::comma)) {
1168 // Metadata at the end is an early exit.
1169 if (Lex.getKind() == lltok::MetadataVar) {
1170 AteExtraComma = true;
1174 if (Lex.getKind() != lltok::kw_align)
1175 return Error(Lex.getLoc(), "expected metadata or 'align'");
1177 if (ParseOptionalAlignment(Alignment)) return true;
1183 /// ParseOptionalStackAlignment
1185 /// ::= 'alignstack' '(' 4 ')'
1186 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1188 if (!EatIfPresent(lltok::kw_alignstack))
1190 LocTy ParenLoc = Lex.getLoc();
1191 if (!EatIfPresent(lltok::lparen))
1192 return Error(ParenLoc, "expected '('");
1193 LocTy AlignLoc = Lex.getLoc();
1194 if (ParseUInt32(Alignment)) return true;
1195 ParenLoc = Lex.getLoc();
1196 if (!EatIfPresent(lltok::rparen))
1197 return Error(ParenLoc, "expected ')'");
1198 if (!isPowerOf2_32(Alignment))
1199 return Error(AlignLoc, "stack alignment is not a power of two");
1203 /// ParseIndexList - This parses the index list for an insert/extractvalue
1204 /// instruction. This sets AteExtraComma in the case where we eat an extra
1205 /// comma at the end of the line and find that it is followed by metadata.
1206 /// Clients that don't allow metadata can call the version of this function that
1207 /// only takes one argument.
1210 /// ::= (',' uint32)+
1212 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1213 bool &AteExtraComma) {
1214 AteExtraComma = false;
1216 if (Lex.getKind() != lltok::comma)
1217 return TokError("expected ',' as start of index list");
1219 while (EatIfPresent(lltok::comma)) {
1220 if (Lex.getKind() == lltok::MetadataVar) {
1221 AteExtraComma = true;
1225 if (ParseUInt32(Idx)) return true;
1226 Indices.push_back(Idx);
1232 //===----------------------------------------------------------------------===//
1234 //===----------------------------------------------------------------------===//
1236 /// ParseType - Parse and resolve a full type.
1237 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1238 LocTy TypeLoc = Lex.getLoc();
1239 if (ParseTypeRec(Result)) return true;
1241 // Verify no unresolved uprefs.
1242 if (!UpRefs.empty())
1243 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1245 if (!AllowVoid && Result.get()->isVoidTy())
1246 return Error(TypeLoc, "void type only allowed for function results");
1251 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1252 /// called. It loops through the UpRefs vector, which is a list of the
1253 /// currently active types. For each type, if the up-reference is contained in
1254 /// the newly completed type, we decrement the level count. When the level
1255 /// count reaches zero, the up-referenced type is the type that is passed in:
1256 /// thus we can complete the cycle.
1258 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1259 // If Ty isn't abstract, or if there are no up-references in it, then there is
1260 // nothing to resolve here.
1261 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1263 PATypeHolder Ty(ty);
1265 dbgs() << "Type '" << Ty->getDescription()
1266 << "' newly formed. Resolving upreferences.\n"
1267 << UpRefs.size() << " upreferences active!\n";
1270 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1271 // to zero), we resolve them all together before we resolve them to Ty. At
1272 // the end of the loop, if there is anything to resolve to Ty, it will be in
1274 OpaqueType *TypeToResolve = 0;
1276 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1277 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1279 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1280 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1283 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1284 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1285 << (ContainsType ? "true" : "false")
1286 << " level=" << UpRefs[i].NestingLevel << "\n";
1291 // Decrement level of upreference
1292 unsigned Level = --UpRefs[i].NestingLevel;
1293 UpRefs[i].LastContainedTy = Ty;
1295 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1300 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1303 TypeToResolve = UpRefs[i].UpRefTy;
1305 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1306 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1307 --i; // Do not skip the next element.
1311 TypeToResolve->refineAbstractTypeTo(Ty);
1317 /// ParseTypeRec - The recursive function used to process the internal
1318 /// implementation details of types.
1319 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1320 switch (Lex.getKind()) {
1322 return TokError("expected type");
1324 // TypeRec ::= 'float' | 'void' (etc)
1325 Result = Lex.getTyVal();
1328 case lltok::kw_opaque:
1329 // TypeRec ::= 'opaque'
1330 Result = OpaqueType::get(Context);
1334 // TypeRec ::= '{' ... '}'
1335 if (ParseStructType(Result, false))
1338 case lltok::lsquare:
1339 // TypeRec ::= '[' ... ']'
1340 Lex.Lex(); // eat the lsquare.
1341 if (ParseArrayVectorType(Result, false))
1344 case lltok::less: // Either vector or packed struct.
1345 // TypeRec ::= '<' ... '>'
1347 if (Lex.getKind() == lltok::lbrace) {
1348 if (ParseStructType(Result, true) ||
1349 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1351 } else if (ParseArrayVectorType(Result, true))
1354 case lltok::LocalVar:
1356 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1359 Result = OpaqueType::get(Context);
1360 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1361 std::make_pair(Result,
1363 M->addTypeName(Lex.getStrVal(), Result.get());
1368 case lltok::LocalVarID:
1370 if (Lex.getUIntVal() < NumberedTypes.size())
1371 Result = NumberedTypes[Lex.getUIntVal()];
1373 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1374 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1375 if (I != ForwardRefTypeIDs.end())
1376 Result = I->second.first;
1378 Result = OpaqueType::get(Context);
1379 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1380 std::make_pair(Result,
1386 case lltok::backslash: {
1387 // TypeRec ::= '\' 4
1390 if (ParseUInt32(Val)) return true;
1391 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1392 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1398 // Parse the type suffixes.
1400 switch (Lex.getKind()) {
1402 default: return false;
1404 // TypeRec ::= TypeRec '*'
1406 if (Result.get()->isLabelTy())
1407 return TokError("basic block pointers are invalid");
1408 if (Result.get()->isVoidTy())
1409 return TokError("pointers to void are invalid; use i8* instead");
1410 if (!PointerType::isValidElementType(Result.get()))
1411 return TokError("pointer to this type is invalid");
1412 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1416 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1417 case lltok::kw_addrspace: {
1418 if (Result.get()->isLabelTy())
1419 return TokError("basic block pointers are invalid");
1420 if (Result.get()->isVoidTy())
1421 return TokError("pointers to void are invalid; use i8* instead");
1422 if (!PointerType::isValidElementType(Result.get()))
1423 return TokError("pointer to this type is invalid");
1425 if (ParseOptionalAddrSpace(AddrSpace) ||
1426 ParseToken(lltok::star, "expected '*' in address space"))
1429 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1433 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1435 if (ParseFunctionType(Result))
1442 /// ParseParameterList
1444 /// ::= '(' Arg (',' Arg)* ')'
1446 /// ::= Type OptionalAttributes Value OptionalAttributes
1447 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1448 PerFunctionState &PFS) {
1449 if (ParseToken(lltok::lparen, "expected '(' in call"))
1452 while (Lex.getKind() != lltok::rparen) {
1453 // If this isn't the first argument, we need a comma.
1454 if (!ArgList.empty() &&
1455 ParseToken(lltok::comma, "expected ',' in argument list"))
1458 // Parse the argument.
1460 PATypeHolder ArgTy(Type::getVoidTy(Context));
1461 unsigned ArgAttrs1 = Attribute::None;
1462 unsigned ArgAttrs2 = Attribute::None;
1464 if (ParseType(ArgTy, ArgLoc))
1467 // Otherwise, handle normal operands.
1468 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
1470 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1473 Lex.Lex(); // Lex the ')'.
1479 /// ParseArgumentList - Parse the argument list for a function type or function
1480 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1481 /// ::= '(' ArgTypeListI ')'
1485 /// ::= ArgTypeList ',' '...'
1486 /// ::= ArgType (',' ArgType)*
1488 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1489 bool &isVarArg, bool inType) {
1491 assert(Lex.getKind() == lltok::lparen);
1492 Lex.Lex(); // eat the (.
1494 if (Lex.getKind() == lltok::rparen) {
1496 } else if (Lex.getKind() == lltok::dotdotdot) {
1500 LocTy TypeLoc = Lex.getLoc();
1501 PATypeHolder ArgTy(Type::getVoidTy(Context));
1505 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1506 // types (such as a function returning a pointer to itself). If parsing a
1507 // function prototype, we require fully resolved types.
1508 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1509 ParseOptionalAttrs(Attrs, 0)) return true;
1511 if (ArgTy->isVoidTy())
1512 return Error(TypeLoc, "argument can not have void type");
1514 if (Lex.getKind() == lltok::LocalVar) {
1515 Name = Lex.getStrVal();
1519 if (!FunctionType::isValidArgumentType(ArgTy))
1520 return Error(TypeLoc, "invalid type for function argument");
1522 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1524 while (EatIfPresent(lltok::comma)) {
1525 // Handle ... at end of arg list.
1526 if (EatIfPresent(lltok::dotdotdot)) {
1531 // Otherwise must be an argument type.
1532 TypeLoc = Lex.getLoc();
1533 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1534 ParseOptionalAttrs(Attrs, 0)) return true;
1536 if (ArgTy->isVoidTy())
1537 return Error(TypeLoc, "argument can not have void type");
1539 if (Lex.getKind() == lltok::LocalVar) {
1540 Name = Lex.getStrVal();
1546 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
1547 return Error(TypeLoc, "invalid type for function argument");
1549 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1553 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1556 /// ParseFunctionType
1557 /// ::= Type ArgumentList OptionalAttrs
1558 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1559 assert(Lex.getKind() == lltok::lparen);
1561 if (!FunctionType::isValidReturnType(Result))
1562 return TokError("invalid function return type");
1564 std::vector<ArgInfo> ArgList;
1567 if (ParseArgumentList(ArgList, isVarArg, true) ||
1568 // FIXME: Allow, but ignore attributes on function types!
1569 // FIXME: Remove in LLVM 3.0
1570 ParseOptionalAttrs(Attrs, 2))
1573 // Reject names on the arguments lists.
1574 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1575 if (!ArgList[i].Name.empty())
1576 return Error(ArgList[i].Loc, "argument name invalid in function type");
1577 if (!ArgList[i].Attrs != 0) {
1578 // Allow but ignore attributes on function types; this permits
1580 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1584 std::vector<const Type*> ArgListTy;
1585 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1586 ArgListTy.push_back(ArgList[i].Type);
1588 Result = HandleUpRefs(FunctionType::get(Result.get(),
1589 ArgListTy, isVarArg));
1593 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1596 /// ::= '{' TypeRec (',' TypeRec)* '}'
1597 /// ::= '<' '{' '}' '>'
1598 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1599 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1600 assert(Lex.getKind() == lltok::lbrace);
1601 Lex.Lex(); // Consume the '{'
1603 if (EatIfPresent(lltok::rbrace)) {
1604 Result = StructType::get(Context, Packed);
1608 std::vector<PATypeHolder> ParamsList;
1609 LocTy EltTyLoc = Lex.getLoc();
1610 if (ParseTypeRec(Result)) return true;
1611 ParamsList.push_back(Result);
1613 if (Result->isVoidTy())
1614 return Error(EltTyLoc, "struct element can not have void type");
1615 if (!StructType::isValidElementType(Result))
1616 return Error(EltTyLoc, "invalid element type for struct");
1618 while (EatIfPresent(lltok::comma)) {
1619 EltTyLoc = Lex.getLoc();
1620 if (ParseTypeRec(Result)) return true;
1622 if (Result->isVoidTy())
1623 return Error(EltTyLoc, "struct element can not have void type");
1624 if (!StructType::isValidElementType(Result))
1625 return Error(EltTyLoc, "invalid element type for struct");
1627 ParamsList.push_back(Result);
1630 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1633 std::vector<const Type*> ParamsListTy;
1634 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1635 ParamsListTy.push_back(ParamsList[i].get());
1636 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1640 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1641 /// token has already been consumed.
1643 /// ::= '[' APSINTVAL 'x' Types ']'
1644 /// ::= '<' APSINTVAL 'x' Types '>'
1645 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1646 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1647 Lex.getAPSIntVal().getBitWidth() > 64)
1648 return TokError("expected number in address space");
1650 LocTy SizeLoc = Lex.getLoc();
1651 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1654 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1657 LocTy TypeLoc = Lex.getLoc();
1658 PATypeHolder EltTy(Type::getVoidTy(Context));
1659 if (ParseTypeRec(EltTy)) return true;
1661 if (EltTy->isVoidTy())
1662 return Error(TypeLoc, "array and vector element type cannot be void");
1664 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1665 "expected end of sequential type"))
1670 return Error(SizeLoc, "zero element vector is illegal");
1671 if ((unsigned)Size != Size)
1672 return Error(SizeLoc, "size too large for vector");
1673 if (!VectorType::isValidElementType(EltTy))
1674 return Error(TypeLoc, "vector element type must be fp or integer");
1675 Result = VectorType::get(EltTy, unsigned(Size));
1677 if (!ArrayType::isValidElementType(EltTy))
1678 return Error(TypeLoc, "invalid array element type");
1679 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1684 //===----------------------------------------------------------------------===//
1685 // Function Semantic Analysis.
1686 //===----------------------------------------------------------------------===//
1688 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1690 : P(p), F(f), FunctionNumber(functionNumber) {
1692 // Insert unnamed arguments into the NumberedVals list.
1693 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1696 NumberedVals.push_back(AI);
1699 LLParser::PerFunctionState::~PerFunctionState() {
1700 // If there were any forward referenced non-basicblock values, delete them.
1701 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1702 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1703 if (!isa<BasicBlock>(I->second.first)) {
1704 I->second.first->replaceAllUsesWith(
1705 UndefValue::get(I->second.first->getType()));
1706 delete I->second.first;
1707 I->second.first = 0;
1710 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1711 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1712 if (!isa<BasicBlock>(I->second.first)) {
1713 I->second.first->replaceAllUsesWith(
1714 UndefValue::get(I->second.first->getType()));
1715 delete I->second.first;
1716 I->second.first = 0;
1720 bool LLParser::PerFunctionState::FinishFunction() {
1721 // Check to see if someone took the address of labels in this block.
1722 if (!P.ForwardRefBlockAddresses.empty()) {
1724 if (!F.getName().empty()) {
1725 FunctionID.Kind = ValID::t_GlobalName;
1726 FunctionID.StrVal = F.getName();
1728 FunctionID.Kind = ValID::t_GlobalID;
1729 FunctionID.UIntVal = FunctionNumber;
1732 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1733 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1734 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1735 // Resolve all these references.
1736 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1739 P.ForwardRefBlockAddresses.erase(FRBAI);
1743 if (!ForwardRefVals.empty())
1744 return P.Error(ForwardRefVals.begin()->second.second,
1745 "use of undefined value '%" + ForwardRefVals.begin()->first +
1747 if (!ForwardRefValIDs.empty())
1748 return P.Error(ForwardRefValIDs.begin()->second.second,
1749 "use of undefined value '%" +
1750 Twine(ForwardRefValIDs.begin()->first) + "'");
1755 /// GetVal - Get a value with the specified name or ID, creating a
1756 /// forward reference record if needed. This can return null if the value
1757 /// exists but does not have the right type.
1758 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1759 const Type *Ty, LocTy Loc) {
1760 // Look this name up in the normal function symbol table.
1761 Value *Val = F.getValueSymbolTable().lookup(Name);
1763 // If this is a forward reference for the value, see if we already created a
1764 // forward ref record.
1766 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1767 I = ForwardRefVals.find(Name);
1768 if (I != ForwardRefVals.end())
1769 Val = I->second.first;
1772 // If we have the value in the symbol table or fwd-ref table, return it.
1774 if (Val->getType() == Ty) return Val;
1775 if (Ty->isLabelTy())
1776 P.Error(Loc, "'%" + Name + "' is not a basic block");
1778 P.Error(Loc, "'%" + Name + "' defined with type '" +
1779 Val->getType()->getDescription() + "'");
1783 // Don't make placeholders with invalid type.
1784 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1785 P.Error(Loc, "invalid use of a non-first-class type");
1789 // Otherwise, create a new forward reference for this value and remember it.
1791 if (Ty->isLabelTy())
1792 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1794 FwdVal = new Argument(Ty, Name);
1796 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1800 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1802 // Look this name up in the normal function symbol table.
1803 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1805 // If this is a forward reference for the value, see if we already created a
1806 // forward ref record.
1808 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1809 I = ForwardRefValIDs.find(ID);
1810 if (I != ForwardRefValIDs.end())
1811 Val = I->second.first;
1814 // If we have the value in the symbol table or fwd-ref table, return it.
1816 if (Val->getType() == Ty) return Val;
1817 if (Ty->isLabelTy())
1818 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1820 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1821 Val->getType()->getDescription() + "'");
1825 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1826 P.Error(Loc, "invalid use of a non-first-class type");
1830 // Otherwise, create a new forward reference for this value and remember it.
1832 if (Ty->isLabelTy())
1833 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1835 FwdVal = new Argument(Ty);
1837 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1841 /// SetInstName - After an instruction is parsed and inserted into its
1842 /// basic block, this installs its name.
1843 bool LLParser::PerFunctionState::SetInstName(int NameID,
1844 const std::string &NameStr,
1845 LocTy NameLoc, Instruction *Inst) {
1846 // If this instruction has void type, it cannot have a name or ID specified.
1847 if (Inst->getType()->isVoidTy()) {
1848 if (NameID != -1 || !NameStr.empty())
1849 return P.Error(NameLoc, "instructions returning void cannot have a name");
1853 // If this was a numbered instruction, verify that the instruction is the
1854 // expected value and resolve any forward references.
1855 if (NameStr.empty()) {
1856 // If neither a name nor an ID was specified, just use the next ID.
1858 NameID = NumberedVals.size();
1860 if (unsigned(NameID) != NumberedVals.size())
1861 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1862 Twine(NumberedVals.size()) + "'");
1864 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1865 ForwardRefValIDs.find(NameID);
1866 if (FI != ForwardRefValIDs.end()) {
1867 if (FI->second.first->getType() != Inst->getType())
1868 return P.Error(NameLoc, "instruction forward referenced with type '" +
1869 FI->second.first->getType()->getDescription() + "'");
1870 FI->second.first->replaceAllUsesWith(Inst);
1871 delete FI->second.first;
1872 ForwardRefValIDs.erase(FI);
1875 NumberedVals.push_back(Inst);
1879 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1880 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1881 FI = ForwardRefVals.find(NameStr);
1882 if (FI != ForwardRefVals.end()) {
1883 if (FI->second.first->getType() != Inst->getType())
1884 return P.Error(NameLoc, "instruction forward referenced with type '" +
1885 FI->second.first->getType()->getDescription() + "'");
1886 FI->second.first->replaceAllUsesWith(Inst);
1887 delete FI->second.first;
1888 ForwardRefVals.erase(FI);
1891 // Set the name on the instruction.
1892 Inst->setName(NameStr);
1894 if (Inst->getName() != NameStr)
1895 return P.Error(NameLoc, "multiple definition of local value named '" +
1900 /// GetBB - Get a basic block with the specified name or ID, creating a
1901 /// forward reference record if needed.
1902 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1904 return cast_or_null<BasicBlock>(GetVal(Name,
1905 Type::getLabelTy(F.getContext()), Loc));
1908 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1909 return cast_or_null<BasicBlock>(GetVal(ID,
1910 Type::getLabelTy(F.getContext()), Loc));
1913 /// DefineBB - Define the specified basic block, which is either named or
1914 /// unnamed. If there is an error, this returns null otherwise it returns
1915 /// the block being defined.
1916 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1920 BB = GetBB(NumberedVals.size(), Loc);
1922 BB = GetBB(Name, Loc);
1923 if (BB == 0) return 0; // Already diagnosed error.
1925 // Move the block to the end of the function. Forward ref'd blocks are
1926 // inserted wherever they happen to be referenced.
1927 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1929 // Remove the block from forward ref sets.
1931 ForwardRefValIDs.erase(NumberedVals.size());
1932 NumberedVals.push_back(BB);
1934 // BB forward references are already in the function symbol table.
1935 ForwardRefVals.erase(Name);
1941 //===----------------------------------------------------------------------===//
1943 //===----------------------------------------------------------------------===//
1945 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1946 /// type implied. For example, if we parse "4" we don't know what integer type
1947 /// it has. The value will later be combined with its type and checked for
1948 /// sanity. PFS is used to convert function-local operands of metadata (since
1949 /// metadata operands are not just parsed here but also converted to values).
1950 /// PFS can be null when we are not parsing metadata values inside a function.
1951 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1952 ID.Loc = Lex.getLoc();
1953 switch (Lex.getKind()) {
1954 default: return TokError("expected value token");
1955 case lltok::GlobalID: // @42
1956 ID.UIntVal = Lex.getUIntVal();
1957 ID.Kind = ValID::t_GlobalID;
1959 case lltok::GlobalVar: // @foo
1960 ID.StrVal = Lex.getStrVal();
1961 ID.Kind = ValID::t_GlobalName;
1963 case lltok::LocalVarID: // %42
1964 ID.UIntVal = Lex.getUIntVal();
1965 ID.Kind = ValID::t_LocalID;
1967 case lltok::LocalVar: // %foo
1968 ID.StrVal = Lex.getStrVal();
1969 ID.Kind = ValID::t_LocalName;
1971 case lltok::exclaim: // !42, !{...}, or !"foo"
1972 return ParseMetadataValue(ID, PFS);
1974 ID.APSIntVal = Lex.getAPSIntVal();
1975 ID.Kind = ValID::t_APSInt;
1977 case lltok::APFloat:
1978 ID.APFloatVal = Lex.getAPFloatVal();
1979 ID.Kind = ValID::t_APFloat;
1981 case lltok::kw_true:
1982 ID.ConstantVal = ConstantInt::getTrue(Context);
1983 ID.Kind = ValID::t_Constant;
1985 case lltok::kw_false:
1986 ID.ConstantVal = ConstantInt::getFalse(Context);
1987 ID.Kind = ValID::t_Constant;
1989 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1990 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1991 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1993 case lltok::lbrace: {
1994 // ValID ::= '{' ConstVector '}'
1996 SmallVector<Constant*, 16> Elts;
1997 if (ParseGlobalValueVector(Elts) ||
1998 ParseToken(lltok::rbrace, "expected end of struct constant"))
2001 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2002 Elts.size(), false);
2003 ID.Kind = ValID::t_Constant;
2007 // ValID ::= '<' ConstVector '>' --> Vector.
2008 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2010 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2012 SmallVector<Constant*, 16> Elts;
2013 LocTy FirstEltLoc = Lex.getLoc();
2014 if (ParseGlobalValueVector(Elts) ||
2016 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2017 ParseToken(lltok::greater, "expected end of constant"))
2020 if (isPackedStruct) {
2022 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
2023 ID.Kind = ValID::t_Constant;
2028 return Error(ID.Loc, "constant vector must not be empty");
2030 if (!Elts[0]->getType()->isIntegerTy() &&
2031 !Elts[0]->getType()->isFloatingPointTy())
2032 return Error(FirstEltLoc,
2033 "vector elements must have integer or floating point type");
2035 // Verify that all the vector elements have the same type.
2036 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2037 if (Elts[i]->getType() != Elts[0]->getType())
2038 return Error(FirstEltLoc,
2039 "vector element #" + Twine(i) +
2040 " is not of type '" + Elts[0]->getType()->getDescription());
2042 ID.ConstantVal = ConstantVector::get(Elts);
2043 ID.Kind = ValID::t_Constant;
2046 case lltok::lsquare: { // Array Constant
2048 SmallVector<Constant*, 16> Elts;
2049 LocTy FirstEltLoc = Lex.getLoc();
2050 if (ParseGlobalValueVector(Elts) ||
2051 ParseToken(lltok::rsquare, "expected end of array constant"))
2054 // Handle empty element.
2056 // Use undef instead of an array because it's inconvenient to determine
2057 // the element type at this point, there being no elements to examine.
2058 ID.Kind = ValID::t_EmptyArray;
2062 if (!Elts[0]->getType()->isFirstClassType())
2063 return Error(FirstEltLoc, "invalid array element type: " +
2064 Elts[0]->getType()->getDescription());
2066 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2068 // Verify all elements are correct type!
2069 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2070 if (Elts[i]->getType() != Elts[0]->getType())
2071 return Error(FirstEltLoc,
2072 "array element #" + Twine(i) +
2073 " is not of type '" +Elts[0]->getType()->getDescription());
2076 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
2077 ID.Kind = ValID::t_Constant;
2080 case lltok::kw_c: // c "foo"
2082 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2083 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2084 ID.Kind = ValID::t_Constant;
2087 case lltok::kw_asm: {
2088 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2089 bool HasSideEffect, AlignStack;
2091 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2092 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2093 ParseStringConstant(ID.StrVal) ||
2094 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2095 ParseToken(lltok::StringConstant, "expected constraint string"))
2097 ID.StrVal2 = Lex.getStrVal();
2098 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2099 ID.Kind = ValID::t_InlineAsm;
2103 case lltok::kw_blockaddress: {
2104 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2108 LocTy FnLoc, LabelLoc;
2110 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2112 ParseToken(lltok::comma, "expected comma in block address expression")||
2113 ParseValID(Label) ||
2114 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2117 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2118 return Error(Fn.Loc, "expected function name in blockaddress");
2119 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2120 return Error(Label.Loc, "expected basic block name in blockaddress");
2122 // Make a global variable as a placeholder for this reference.
2123 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2124 false, GlobalValue::InternalLinkage,
2126 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2127 ID.ConstantVal = FwdRef;
2128 ID.Kind = ValID::t_Constant;
2132 case lltok::kw_trunc:
2133 case lltok::kw_zext:
2134 case lltok::kw_sext:
2135 case lltok::kw_fptrunc:
2136 case lltok::kw_fpext:
2137 case lltok::kw_bitcast:
2138 case lltok::kw_uitofp:
2139 case lltok::kw_sitofp:
2140 case lltok::kw_fptoui:
2141 case lltok::kw_fptosi:
2142 case lltok::kw_inttoptr:
2143 case lltok::kw_ptrtoint: {
2144 unsigned Opc = Lex.getUIntVal();
2145 PATypeHolder DestTy(Type::getVoidTy(Context));
2148 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2149 ParseGlobalTypeAndValue(SrcVal) ||
2150 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2151 ParseType(DestTy) ||
2152 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2154 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2155 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2156 SrcVal->getType()->getDescription() + "' to '" +
2157 DestTy->getDescription() + "'");
2158 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2160 ID.Kind = ValID::t_Constant;
2163 case lltok::kw_extractvalue: {
2166 SmallVector<unsigned, 4> Indices;
2167 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2168 ParseGlobalTypeAndValue(Val) ||
2169 ParseIndexList(Indices) ||
2170 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2173 if (!Val->getType()->isAggregateType())
2174 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2175 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2177 return Error(ID.Loc, "invalid indices for extractvalue");
2179 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2180 ID.Kind = ValID::t_Constant;
2183 case lltok::kw_insertvalue: {
2185 Constant *Val0, *Val1;
2186 SmallVector<unsigned, 4> Indices;
2187 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2188 ParseGlobalTypeAndValue(Val0) ||
2189 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2190 ParseGlobalTypeAndValue(Val1) ||
2191 ParseIndexList(Indices) ||
2192 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2194 if (!Val0->getType()->isAggregateType())
2195 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2196 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2198 return Error(ID.Loc, "invalid indices for insertvalue");
2199 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2200 Indices.data(), Indices.size());
2201 ID.Kind = ValID::t_Constant;
2204 case lltok::kw_icmp:
2205 case lltok::kw_fcmp: {
2206 unsigned PredVal, Opc = Lex.getUIntVal();
2207 Constant *Val0, *Val1;
2209 if (ParseCmpPredicate(PredVal, Opc) ||
2210 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2211 ParseGlobalTypeAndValue(Val0) ||
2212 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2213 ParseGlobalTypeAndValue(Val1) ||
2214 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2217 if (Val0->getType() != Val1->getType())
2218 return Error(ID.Loc, "compare operands must have the same type");
2220 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2222 if (Opc == Instruction::FCmp) {
2223 if (!Val0->getType()->isFPOrFPVectorTy())
2224 return Error(ID.Loc, "fcmp requires floating point operands");
2225 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2227 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2228 if (!Val0->getType()->isIntOrIntVectorTy() &&
2229 !Val0->getType()->isPointerTy())
2230 return Error(ID.Loc, "icmp requires pointer or integer operands");
2231 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2233 ID.Kind = ValID::t_Constant;
2237 // Binary Operators.
2239 case lltok::kw_fadd:
2241 case lltok::kw_fsub:
2243 case lltok::kw_fmul:
2244 case lltok::kw_udiv:
2245 case lltok::kw_sdiv:
2246 case lltok::kw_fdiv:
2247 case lltok::kw_urem:
2248 case lltok::kw_srem:
2249 case lltok::kw_frem:
2251 case lltok::kw_lshr:
2252 case lltok::kw_ashr: {
2256 unsigned Opc = Lex.getUIntVal();
2257 Constant *Val0, *Val1;
2259 LocTy ModifierLoc = Lex.getLoc();
2260 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2261 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2262 if (EatIfPresent(lltok::kw_nuw))
2264 if (EatIfPresent(lltok::kw_nsw)) {
2266 if (EatIfPresent(lltok::kw_nuw))
2269 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2270 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2271 if (EatIfPresent(lltok::kw_exact))
2274 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2275 ParseGlobalTypeAndValue(Val0) ||
2276 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2277 ParseGlobalTypeAndValue(Val1) ||
2278 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2280 if (Val0->getType() != Val1->getType())
2281 return Error(ID.Loc, "operands of constexpr must have same type");
2282 if (!Val0->getType()->isIntOrIntVectorTy()) {
2284 return Error(ModifierLoc, "nuw only applies to integer operations");
2286 return Error(ModifierLoc, "nsw only applies to integer operations");
2288 // Check that the type is valid for the operator.
2290 case Instruction::Add:
2291 case Instruction::Sub:
2292 case Instruction::Mul:
2293 case Instruction::UDiv:
2294 case Instruction::SDiv:
2295 case Instruction::URem:
2296 case Instruction::SRem:
2297 case Instruction::Shl:
2298 case Instruction::AShr:
2299 case Instruction::LShr:
2300 if (!Val0->getType()->isIntOrIntVectorTy())
2301 return Error(ID.Loc, "constexpr requires integer operands");
2303 case Instruction::FAdd:
2304 case Instruction::FSub:
2305 case Instruction::FMul:
2306 case Instruction::FDiv:
2307 case Instruction::FRem:
2308 if (!Val0->getType()->isFPOrFPVectorTy())
2309 return Error(ID.Loc, "constexpr requires fp operands");
2311 default: llvm_unreachable("Unknown binary operator!");
2314 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2315 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2316 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2317 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2319 ID.Kind = ValID::t_Constant;
2323 // Logical Operations
2326 case lltok::kw_xor: {
2327 unsigned Opc = Lex.getUIntVal();
2328 Constant *Val0, *Val1;
2330 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2331 ParseGlobalTypeAndValue(Val0) ||
2332 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2333 ParseGlobalTypeAndValue(Val1) ||
2334 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2336 if (Val0->getType() != Val1->getType())
2337 return Error(ID.Loc, "operands of constexpr must have same type");
2338 if (!Val0->getType()->isIntOrIntVectorTy())
2339 return Error(ID.Loc,
2340 "constexpr requires integer or integer vector operands");
2341 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2342 ID.Kind = ValID::t_Constant;
2346 case lltok::kw_getelementptr:
2347 case lltok::kw_shufflevector:
2348 case lltok::kw_insertelement:
2349 case lltok::kw_extractelement:
2350 case lltok::kw_select: {
2351 unsigned Opc = Lex.getUIntVal();
2352 SmallVector<Constant*, 16> Elts;
2353 bool InBounds = false;
2355 if (Opc == Instruction::GetElementPtr)
2356 InBounds = EatIfPresent(lltok::kw_inbounds);
2357 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2358 ParseGlobalValueVector(Elts) ||
2359 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2362 if (Opc == Instruction::GetElementPtr) {
2363 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
2364 return Error(ID.Loc, "getelementptr requires pointer operand");
2366 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2367 (Value**)(Elts.data() + 1),
2369 return Error(ID.Loc, "invalid indices for getelementptr");
2370 ID.ConstantVal = InBounds ?
2371 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2374 ConstantExpr::getGetElementPtr(Elts[0],
2375 Elts.data() + 1, Elts.size() - 1);
2376 } else if (Opc == Instruction::Select) {
2377 if (Elts.size() != 3)
2378 return Error(ID.Loc, "expected three operands to select");
2379 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2381 return Error(ID.Loc, Reason);
2382 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2383 } else if (Opc == Instruction::ShuffleVector) {
2384 if (Elts.size() != 3)
2385 return Error(ID.Loc, "expected three operands to shufflevector");
2386 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2387 return Error(ID.Loc, "invalid operands to shufflevector");
2389 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2390 } else if (Opc == Instruction::ExtractElement) {
2391 if (Elts.size() != 2)
2392 return Error(ID.Loc, "expected two operands to extractelement");
2393 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2394 return Error(ID.Loc, "invalid extractelement operands");
2395 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2397 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2398 if (Elts.size() != 3)
2399 return Error(ID.Loc, "expected three operands to insertelement");
2400 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2401 return Error(ID.Loc, "invalid insertelement operands");
2403 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2406 ID.Kind = ValID::t_Constant;
2415 /// ParseGlobalValue - Parse a global value with the specified type.
2416 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2420 bool Parsed = ParseValID(ID) ||
2421 ConvertValIDToValue(Ty, ID, V, NULL);
2422 if (V && !(C = dyn_cast<Constant>(V)))
2423 return Error(ID.Loc, "global values must be constants");
2427 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2428 PATypeHolder Type(Type::getVoidTy(Context));
2429 return ParseType(Type) ||
2430 ParseGlobalValue(Type, V);
2433 /// ParseGlobalValueVector
2435 /// ::= TypeAndValue (',' TypeAndValue)*
2436 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2438 if (Lex.getKind() == lltok::rbrace ||
2439 Lex.getKind() == lltok::rsquare ||
2440 Lex.getKind() == lltok::greater ||
2441 Lex.getKind() == lltok::rparen)
2445 if (ParseGlobalTypeAndValue(C)) return true;
2448 while (EatIfPresent(lltok::comma)) {
2449 if (ParseGlobalTypeAndValue(C)) return true;
2456 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2457 assert(Lex.getKind() == lltok::lbrace);
2460 SmallVector<Value*, 16> Elts;
2461 if (ParseMDNodeVector(Elts, PFS) ||
2462 ParseToken(lltok::rbrace, "expected end of metadata node"))
2465 ID.MDNodeVal = MDNode::get(Context, Elts);
2466 ID.Kind = ValID::t_MDNode;
2470 /// ParseMetadataValue
2474 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2475 assert(Lex.getKind() == lltok::exclaim);
2480 if (Lex.getKind() == lltok::lbrace)
2481 return ParseMetadataListValue(ID, PFS);
2483 // Standalone metadata reference
2485 if (Lex.getKind() == lltok::APSInt) {
2486 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2487 ID.Kind = ValID::t_MDNode;
2492 // ::= '!' STRINGCONSTANT
2493 if (ParseMDString(ID.MDStringVal)) return true;
2494 ID.Kind = ValID::t_MDString;
2499 //===----------------------------------------------------------------------===//
2500 // Function Parsing.
2501 //===----------------------------------------------------------------------===//
2503 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2504 PerFunctionState *PFS) {
2505 if (Ty->isFunctionTy())
2506 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2509 default: llvm_unreachable("Unknown ValID!");
2510 case ValID::t_LocalID:
2511 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2512 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2514 case ValID::t_LocalName:
2515 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2516 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2518 case ValID::t_InlineAsm: {
2519 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2520 const FunctionType *FTy =
2521 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2522 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2523 return Error(ID.Loc, "invalid type for inline asm constraint string");
2524 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2527 case ValID::t_MDNode:
2528 if (!Ty->isMetadataTy())
2529 return Error(ID.Loc, "metadata value must have metadata type");
2532 case ValID::t_MDString:
2533 if (!Ty->isMetadataTy())
2534 return Error(ID.Loc, "metadata value must have metadata type");
2537 case ValID::t_GlobalName:
2538 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2540 case ValID::t_GlobalID:
2541 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2543 case ValID::t_APSInt:
2544 if (!Ty->isIntegerTy())
2545 return Error(ID.Loc, "integer constant must have integer type");
2546 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2547 V = ConstantInt::get(Context, ID.APSIntVal);
2549 case ValID::t_APFloat:
2550 if (!Ty->isFloatingPointTy() ||
2551 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2552 return Error(ID.Loc, "floating point constant invalid for type");
2554 // The lexer has no type info, so builds all float and double FP constants
2555 // as double. Fix this here. Long double does not need this.
2556 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2559 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2562 V = ConstantFP::get(Context, ID.APFloatVal);
2564 if (V->getType() != Ty)
2565 return Error(ID.Loc, "floating point constant does not have type '" +
2566 Ty->getDescription() + "'");
2570 if (!Ty->isPointerTy())
2571 return Error(ID.Loc, "null must be a pointer type");
2572 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2574 case ValID::t_Undef:
2575 // FIXME: LabelTy should not be a first-class type.
2576 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
2578 return Error(ID.Loc, "invalid type for undef constant");
2579 V = UndefValue::get(Ty);
2581 case ValID::t_EmptyArray:
2582 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2583 return Error(ID.Loc, "invalid empty array initializer");
2584 V = UndefValue::get(Ty);
2587 // FIXME: LabelTy should not be a first-class type.
2588 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2589 return Error(ID.Loc, "invalid type for null constant");
2590 V = Constant::getNullValue(Ty);
2592 case ValID::t_Constant:
2593 if (ID.ConstantVal->getType() != Ty)
2594 return Error(ID.Loc, "constant expression type mismatch");
2601 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2604 return ParseValID(ID, &PFS) ||
2605 ConvertValIDToValue(Ty, ID, V, &PFS);
2608 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2609 PATypeHolder T(Type::getVoidTy(Context));
2610 return ParseType(T) ||
2611 ParseValue(T, V, PFS);
2614 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2615 PerFunctionState &PFS) {
2618 if (ParseTypeAndValue(V, PFS)) return true;
2619 if (!isa<BasicBlock>(V))
2620 return Error(Loc, "expected a basic block");
2621 BB = cast<BasicBlock>(V);
2627 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2628 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2629 /// OptionalAlign OptGC
2630 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2631 // Parse the linkage.
2632 LocTy LinkageLoc = Lex.getLoc();
2635 unsigned Visibility, RetAttrs;
2637 PATypeHolder RetType(Type::getVoidTy(Context));
2638 LocTy RetTypeLoc = Lex.getLoc();
2639 if (ParseOptionalLinkage(Linkage) ||
2640 ParseOptionalVisibility(Visibility) ||
2641 ParseOptionalCallingConv(CC) ||
2642 ParseOptionalAttrs(RetAttrs, 1) ||
2643 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2646 // Verify that the linkage is ok.
2647 switch ((GlobalValue::LinkageTypes)Linkage) {
2648 case GlobalValue::ExternalLinkage:
2649 break; // always ok.
2650 case GlobalValue::DLLImportLinkage:
2651 case GlobalValue::ExternalWeakLinkage:
2653 return Error(LinkageLoc, "invalid linkage for function definition");
2655 case GlobalValue::PrivateLinkage:
2656 case GlobalValue::LinkerPrivateLinkage:
2657 case GlobalValue::LinkerPrivateWeakLinkage:
2658 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
2659 case GlobalValue::InternalLinkage:
2660 case GlobalValue::AvailableExternallyLinkage:
2661 case GlobalValue::LinkOnceAnyLinkage:
2662 case GlobalValue::LinkOnceODRLinkage:
2663 case GlobalValue::WeakAnyLinkage:
2664 case GlobalValue::WeakODRLinkage:
2665 case GlobalValue::DLLExportLinkage:
2667 return Error(LinkageLoc, "invalid linkage for function declaration");
2669 case GlobalValue::AppendingLinkage:
2670 case GlobalValue::CommonLinkage:
2671 return Error(LinkageLoc, "invalid function linkage type");
2674 if (!FunctionType::isValidReturnType(RetType) ||
2675 RetType->isOpaqueTy())
2676 return Error(RetTypeLoc, "invalid function return type");
2678 LocTy NameLoc = Lex.getLoc();
2680 std::string FunctionName;
2681 if (Lex.getKind() == lltok::GlobalVar) {
2682 FunctionName = Lex.getStrVal();
2683 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2684 unsigned NameID = Lex.getUIntVal();
2686 if (NameID != NumberedVals.size())
2687 return TokError("function expected to be numbered '%" +
2688 Twine(NumberedVals.size()) + "'");
2690 return TokError("expected function name");
2695 if (Lex.getKind() != lltok::lparen)
2696 return TokError("expected '(' in function argument list");
2698 std::vector<ArgInfo> ArgList;
2701 std::string Section;
2705 LocTy UnnamedAddrLoc;
2707 if (ParseArgumentList(ArgList, isVarArg, false) ||
2708 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2710 ParseOptionalAttrs(FuncAttrs, 2) ||
2711 (EatIfPresent(lltok::kw_section) &&
2712 ParseStringConstant(Section)) ||
2713 ParseOptionalAlignment(Alignment) ||
2714 (EatIfPresent(lltok::kw_gc) &&
2715 ParseStringConstant(GC)))
2718 // If the alignment was parsed as an attribute, move to the alignment field.
2719 if (FuncAttrs & Attribute::Alignment) {
2720 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2721 FuncAttrs &= ~Attribute::Alignment;
2724 // Okay, if we got here, the function is syntactically valid. Convert types
2725 // and do semantic checks.
2726 std::vector<const Type*> ParamTypeList;
2727 SmallVector<AttributeWithIndex, 8> Attrs;
2729 if (RetAttrs != Attribute::None)
2730 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2732 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2733 ParamTypeList.push_back(ArgList[i].Type);
2734 if (ArgList[i].Attrs != Attribute::None)
2735 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2738 if (FuncAttrs != Attribute::None)
2739 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2741 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2743 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2744 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2746 const FunctionType *FT =
2747 FunctionType::get(RetType, ParamTypeList, isVarArg);
2748 const PointerType *PFT = PointerType::getUnqual(FT);
2751 if (!FunctionName.empty()) {
2752 // If this was a definition of a forward reference, remove the definition
2753 // from the forward reference table and fill in the forward ref.
2754 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2755 ForwardRefVals.find(FunctionName);
2756 if (FRVI != ForwardRefVals.end()) {
2757 Fn = M->getFunction(FunctionName);
2758 if (Fn->getType() != PFT)
2759 return Error(FRVI->second.second, "invalid forward reference to "
2760 "function '" + FunctionName + "' with wrong type!");
2762 ForwardRefVals.erase(FRVI);
2763 } else if ((Fn = M->getFunction(FunctionName))) {
2764 // If this function already exists in the symbol table, then it is
2765 // multiply defined. We accept a few cases for old backwards compat.
2766 // FIXME: Remove this stuff for LLVM 3.0.
2767 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2768 (!Fn->isDeclaration() && isDefine)) {
2769 // If the redefinition has different type or different attributes,
2770 // reject it. If both have bodies, reject it.
2771 return Error(NameLoc, "invalid redefinition of function '" +
2772 FunctionName + "'");
2773 } else if (Fn->isDeclaration()) {
2774 // Make sure to strip off any argument names so we can't get conflicts.
2775 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2779 } else if (M->getNamedValue(FunctionName)) {
2780 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2784 // If this is a definition of a forward referenced function, make sure the
2786 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2787 = ForwardRefValIDs.find(NumberedVals.size());
2788 if (I != ForwardRefValIDs.end()) {
2789 Fn = cast<Function>(I->second.first);
2790 if (Fn->getType() != PFT)
2791 return Error(NameLoc, "type of definition and forward reference of '@" +
2792 Twine(NumberedVals.size()) + "' disagree");
2793 ForwardRefValIDs.erase(I);
2798 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2799 else // Move the forward-reference to the correct spot in the module.
2800 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2802 if (FunctionName.empty())
2803 NumberedVals.push_back(Fn);
2805 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2806 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2807 Fn->setCallingConv(CC);
2808 Fn->setAttributes(PAL);
2809 Fn->setUnnamedAddr(UnnamedAddr);
2810 Fn->setAlignment(Alignment);
2811 Fn->setSection(Section);
2812 if (!GC.empty()) Fn->setGC(GC.c_str());
2814 // Add all of the arguments we parsed to the function.
2815 Function::arg_iterator ArgIt = Fn->arg_begin();
2816 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2817 // If we run out of arguments in the Function prototype, exit early.
2818 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2819 if (ArgIt == Fn->arg_end()) break;
2821 // If the argument has a name, insert it into the argument symbol table.
2822 if (ArgList[i].Name.empty()) continue;
2824 // Set the name, if it conflicted, it will be auto-renamed.
2825 ArgIt->setName(ArgList[i].Name);
2827 if (ArgIt->getName() != ArgList[i].Name)
2828 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2829 ArgList[i].Name + "'");
2836 /// ParseFunctionBody
2837 /// ::= '{' BasicBlock+ '}'
2839 bool LLParser::ParseFunctionBody(Function &Fn) {
2840 if (Lex.getKind() != lltok::lbrace)
2841 return TokError("expected '{' in function body");
2842 Lex.Lex(); // eat the {.
2844 int FunctionNumber = -1;
2845 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2847 PerFunctionState PFS(*this, Fn, FunctionNumber);
2849 // We need at least one basic block.
2850 if (Lex.getKind() == lltok::rbrace)
2851 return TokError("function body requires at least one basic block");
2853 while (Lex.getKind() != lltok::rbrace)
2854 if (ParseBasicBlock(PFS)) return true;
2859 // Verify function is ok.
2860 return PFS.FinishFunction();
2864 /// ::= LabelStr? Instruction*
2865 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2866 // If this basic block starts out with a name, remember it.
2868 LocTy NameLoc = Lex.getLoc();
2869 if (Lex.getKind() == lltok::LabelStr) {
2870 Name = Lex.getStrVal();
2874 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2875 if (BB == 0) return true;
2877 std::string NameStr;
2879 // Parse the instructions in this block until we get a terminator.
2881 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2883 // This instruction may have three possibilities for a name: a) none
2884 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2885 LocTy NameLoc = Lex.getLoc();
2889 if (Lex.getKind() == lltok::LocalVarID) {
2890 NameID = Lex.getUIntVal();
2892 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2894 } else if (Lex.getKind() == lltok::LocalVar) {
2895 NameStr = Lex.getStrVal();
2897 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2901 switch (ParseInstruction(Inst, BB, PFS)) {
2902 default: assert(0 && "Unknown ParseInstruction result!");
2903 case InstError: return true;
2905 BB->getInstList().push_back(Inst);
2907 // With a normal result, we check to see if the instruction is followed by
2908 // a comma and metadata.
2909 if (EatIfPresent(lltok::comma))
2910 if (ParseInstructionMetadata(Inst, &PFS))
2913 case InstExtraComma:
2914 BB->getInstList().push_back(Inst);
2916 // If the instruction parser ate an extra comma at the end of it, it
2917 // *must* be followed by metadata.
2918 if (ParseInstructionMetadata(Inst, &PFS))
2923 // Set the name on the instruction.
2924 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2925 } while (!isa<TerminatorInst>(Inst));
2930 //===----------------------------------------------------------------------===//
2931 // Instruction Parsing.
2932 //===----------------------------------------------------------------------===//
2934 /// ParseInstruction - Parse one of the many different instructions.
2936 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2937 PerFunctionState &PFS) {
2938 lltok::Kind Token = Lex.getKind();
2939 if (Token == lltok::Eof)
2940 return TokError("found end of file when expecting more instructions");
2941 LocTy Loc = Lex.getLoc();
2942 unsigned KeywordVal = Lex.getUIntVal();
2943 Lex.Lex(); // Eat the keyword.
2946 default: return Error(Loc, "expected instruction opcode");
2947 // Terminator Instructions.
2948 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2949 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2950 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2951 case lltok::kw_br: return ParseBr(Inst, PFS);
2952 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2953 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2954 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2955 // Binary Operators.
2959 case lltok::kw_shl: {
2960 bool NUW = EatIfPresent(lltok::kw_nuw);
2961 bool NSW = EatIfPresent(lltok::kw_nsw);
2962 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2964 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2966 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2967 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2970 case lltok::kw_fadd:
2971 case lltok::kw_fsub:
2972 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2974 case lltok::kw_sdiv:
2975 case lltok::kw_udiv:
2976 case lltok::kw_lshr:
2977 case lltok::kw_ashr: {
2978 bool Exact = EatIfPresent(lltok::kw_exact);
2980 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2981 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2985 case lltok::kw_urem:
2986 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2987 case lltok::kw_fdiv:
2988 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2991 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2992 case lltok::kw_icmp:
2993 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2995 case lltok::kw_trunc:
2996 case lltok::kw_zext:
2997 case lltok::kw_sext:
2998 case lltok::kw_fptrunc:
2999 case lltok::kw_fpext:
3000 case lltok::kw_bitcast:
3001 case lltok::kw_uitofp:
3002 case lltok::kw_sitofp:
3003 case lltok::kw_fptoui:
3004 case lltok::kw_fptosi:
3005 case lltok::kw_inttoptr:
3006 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3008 case lltok::kw_select: return ParseSelect(Inst, PFS);
3009 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3010 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3011 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3012 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3013 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3014 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3015 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3017 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3018 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3019 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3020 case lltok::kw_volatile:
3021 if (EatIfPresent(lltok::kw_load))
3022 return ParseLoad(Inst, PFS, true);
3023 else if (EatIfPresent(lltok::kw_store))
3024 return ParseStore(Inst, PFS, true);
3026 return TokError("expected 'load' or 'store'");
3027 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3028 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3029 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3030 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3034 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3035 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3036 if (Opc == Instruction::FCmp) {
3037 switch (Lex.getKind()) {
3038 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3039 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3040 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3041 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3042 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3043 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3044 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3045 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3046 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3047 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3048 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3049 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3050 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3051 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3052 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3053 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3054 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3057 switch (Lex.getKind()) {
3058 default: TokError("expected icmp predicate (e.g. 'eq')");
3059 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3060 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3061 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3062 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3063 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3064 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3065 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3066 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3067 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3068 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3075 //===----------------------------------------------------------------------===//
3076 // Terminator Instructions.
3077 //===----------------------------------------------------------------------===//
3079 /// ParseRet - Parse a return instruction.
3080 /// ::= 'ret' void (',' !dbg, !1)*
3081 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3082 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3083 PerFunctionState &PFS) {
3084 PATypeHolder Ty(Type::getVoidTy(Context));
3085 if (ParseType(Ty, true /*void allowed*/)) return true;
3087 if (Ty->isVoidTy()) {
3088 Inst = ReturnInst::Create(Context);
3093 if (ParseValue(Ty, RV, PFS)) return true;
3095 Inst = ReturnInst::Create(Context, RV);
3101 /// ::= 'br' TypeAndValue
3102 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3103 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3106 BasicBlock *Op1, *Op2;
3107 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3109 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3110 Inst = BranchInst::Create(BB);
3114 if (Op0->getType() != Type::getInt1Ty(Context))
3115 return Error(Loc, "branch condition must have 'i1' type");
3117 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3118 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3119 ParseToken(lltok::comma, "expected ',' after true destination") ||
3120 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3123 Inst = BranchInst::Create(Op1, Op2, Op0);
3129 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3131 /// ::= (TypeAndValue ',' TypeAndValue)*
3132 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3133 LocTy CondLoc, BBLoc;
3135 BasicBlock *DefaultBB;
3136 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3137 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3138 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3139 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3142 if (!Cond->getType()->isIntegerTy())
3143 return Error(CondLoc, "switch condition must have integer type");
3145 // Parse the jump table pairs.
3146 SmallPtrSet<Value*, 32> SeenCases;
3147 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3148 while (Lex.getKind() != lltok::rsquare) {
3152 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3153 ParseToken(lltok::comma, "expected ',' after case value") ||
3154 ParseTypeAndBasicBlock(DestBB, PFS))
3157 if (!SeenCases.insert(Constant))
3158 return Error(CondLoc, "duplicate case value in switch");
3159 if (!isa<ConstantInt>(Constant))
3160 return Error(CondLoc, "case value is not a constant integer");
3162 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3165 Lex.Lex(); // Eat the ']'.
3167 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3168 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3169 SI->addCase(Table[i].first, Table[i].second);
3176 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3177 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3180 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3181 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3182 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3185 if (!Address->getType()->isPointerTy())
3186 return Error(AddrLoc, "indirectbr address must have pointer type");
3188 // Parse the destination list.
3189 SmallVector<BasicBlock*, 16> DestList;
3191 if (Lex.getKind() != lltok::rsquare) {
3193 if (ParseTypeAndBasicBlock(DestBB, PFS))
3195 DestList.push_back(DestBB);
3197 while (EatIfPresent(lltok::comma)) {
3198 if (ParseTypeAndBasicBlock(DestBB, PFS))
3200 DestList.push_back(DestBB);
3204 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3207 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3208 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3209 IBI->addDestination(DestList[i]);
3216 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3217 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3218 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3219 LocTy CallLoc = Lex.getLoc();
3220 unsigned RetAttrs, FnAttrs;
3222 PATypeHolder RetType(Type::getVoidTy(Context));
3225 SmallVector<ParamInfo, 16> ArgList;
3227 BasicBlock *NormalBB, *UnwindBB;
3228 if (ParseOptionalCallingConv(CC) ||
3229 ParseOptionalAttrs(RetAttrs, 1) ||
3230 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3231 ParseValID(CalleeID) ||
3232 ParseParameterList(ArgList, PFS) ||
3233 ParseOptionalAttrs(FnAttrs, 2) ||
3234 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3235 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3236 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3237 ParseTypeAndBasicBlock(UnwindBB, PFS))
3240 // If RetType is a non-function pointer type, then this is the short syntax
3241 // for the call, which means that RetType is just the return type. Infer the
3242 // rest of the function argument types from the arguments that are present.
3243 const PointerType *PFTy = 0;
3244 const FunctionType *Ty = 0;
3245 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3246 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3247 // Pull out the types of all of the arguments...
3248 std::vector<const Type*> ParamTypes;
3249 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3250 ParamTypes.push_back(ArgList[i].V->getType());
3252 if (!FunctionType::isValidReturnType(RetType))
3253 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3255 Ty = FunctionType::get(RetType, ParamTypes, false);
3256 PFTy = PointerType::getUnqual(Ty);
3259 // Look up the callee.
3261 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3263 // Set up the Attributes for the function.
3264 SmallVector<AttributeWithIndex, 8> Attrs;
3265 if (RetAttrs != Attribute::None)
3266 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3268 SmallVector<Value*, 8> Args;
3270 // Loop through FunctionType's arguments and ensure they are specified
3271 // correctly. Also, gather any parameter attributes.
3272 FunctionType::param_iterator I = Ty->param_begin();
3273 FunctionType::param_iterator E = Ty->param_end();
3274 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3275 const Type *ExpectedTy = 0;
3278 } else if (!Ty->isVarArg()) {
3279 return Error(ArgList[i].Loc, "too many arguments specified");
3282 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3283 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3284 ExpectedTy->getDescription() + "'");
3285 Args.push_back(ArgList[i].V);
3286 if (ArgList[i].Attrs != Attribute::None)
3287 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3291 return Error(CallLoc, "not enough parameters specified for call");
3293 if (FnAttrs != Attribute::None)
3294 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3296 // Finish off the Attributes and check them
3297 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3299 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
3300 Args.begin(), Args.end());
3301 II->setCallingConv(CC);
3302 II->setAttributes(PAL);
3309 //===----------------------------------------------------------------------===//
3310 // Binary Operators.
3311 //===----------------------------------------------------------------------===//
3314 /// ::= ArithmeticOps TypeAndValue ',' Value
3316 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3317 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3318 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3319 unsigned Opc, unsigned OperandType) {
3320 LocTy Loc; Value *LHS, *RHS;
3321 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3322 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3323 ParseValue(LHS->getType(), RHS, PFS))
3327 switch (OperandType) {
3328 default: llvm_unreachable("Unknown operand type!");
3329 case 0: // int or FP.
3330 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3331 LHS->getType()->isFPOrFPVectorTy();
3333 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3334 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3338 return Error(Loc, "invalid operand type for instruction");
3340 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3345 /// ::= ArithmeticOps TypeAndValue ',' Value {
3346 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3348 LocTy Loc; Value *LHS, *RHS;
3349 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3350 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3351 ParseValue(LHS->getType(), RHS, PFS))
3354 if (!LHS->getType()->isIntOrIntVectorTy())
3355 return Error(Loc,"instruction requires integer or integer vector operands");
3357 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3363 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3364 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3365 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3367 // Parse the integer/fp comparison predicate.
3371 if (ParseCmpPredicate(Pred, Opc) ||
3372 ParseTypeAndValue(LHS, Loc, PFS) ||
3373 ParseToken(lltok::comma, "expected ',' after compare value") ||
3374 ParseValue(LHS->getType(), RHS, PFS))
3377 if (Opc == Instruction::FCmp) {
3378 if (!LHS->getType()->isFPOrFPVectorTy())
3379 return Error(Loc, "fcmp requires floating point operands");
3380 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3382 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3383 if (!LHS->getType()->isIntOrIntVectorTy() &&
3384 !LHS->getType()->isPointerTy())
3385 return Error(Loc, "icmp requires integer operands");
3386 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3391 //===----------------------------------------------------------------------===//
3392 // Other Instructions.
3393 //===----------------------------------------------------------------------===//
3397 /// ::= CastOpc TypeAndValue 'to' Type
3398 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3400 LocTy Loc; Value *Op;
3401 PATypeHolder DestTy(Type::getVoidTy(Context));
3402 if (ParseTypeAndValue(Op, Loc, PFS) ||
3403 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3407 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3408 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3409 return Error(Loc, "invalid cast opcode for cast from '" +
3410 Op->getType()->getDescription() + "' to '" +
3411 DestTy->getDescription() + "'");
3413 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3418 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3419 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3421 Value *Op0, *Op1, *Op2;
3422 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3423 ParseToken(lltok::comma, "expected ',' after select condition") ||
3424 ParseTypeAndValue(Op1, PFS) ||
3425 ParseToken(lltok::comma, "expected ',' after select value") ||
3426 ParseTypeAndValue(Op2, PFS))
3429 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3430 return Error(Loc, Reason);
3432 Inst = SelectInst::Create(Op0, Op1, Op2);
3437 /// ::= 'va_arg' TypeAndValue ',' Type
3438 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3440 PATypeHolder EltTy(Type::getVoidTy(Context));
3442 if (ParseTypeAndValue(Op, PFS) ||
3443 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3444 ParseType(EltTy, TypeLoc))
3447 if (!EltTy->isFirstClassType())
3448 return Error(TypeLoc, "va_arg requires operand with first class type");
3450 Inst = new VAArgInst(Op, EltTy);
3454 /// ParseExtractElement
3455 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3456 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3459 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3460 ParseToken(lltok::comma, "expected ',' after extract value") ||
3461 ParseTypeAndValue(Op1, PFS))
3464 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3465 return Error(Loc, "invalid extractelement operands");
3467 Inst = ExtractElementInst::Create(Op0, Op1);
3471 /// ParseInsertElement
3472 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3473 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3475 Value *Op0, *Op1, *Op2;
3476 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3477 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3478 ParseTypeAndValue(Op1, PFS) ||
3479 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3480 ParseTypeAndValue(Op2, PFS))
3483 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3484 return Error(Loc, "invalid insertelement operands");
3486 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3490 /// ParseShuffleVector
3491 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3492 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3494 Value *Op0, *Op1, *Op2;
3495 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3496 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3497 ParseTypeAndValue(Op1, PFS) ||
3498 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3499 ParseTypeAndValue(Op2, PFS))
3502 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3503 return Error(Loc, "invalid extractelement operands");
3505 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3510 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3511 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3512 PATypeHolder Ty(Type::getVoidTy(Context));
3514 LocTy TypeLoc = Lex.getLoc();
3516 if (ParseType(Ty) ||
3517 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3518 ParseValue(Ty, Op0, PFS) ||
3519 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3520 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3521 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3524 bool AteExtraComma = false;
3525 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3527 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3529 if (!EatIfPresent(lltok::comma))
3532 if (Lex.getKind() == lltok::MetadataVar) {
3533 AteExtraComma = true;
3537 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3538 ParseValue(Ty, Op0, PFS) ||
3539 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3540 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3541 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3545 if (!Ty->isFirstClassType())
3546 return Error(TypeLoc, "phi node must have first class type");
3548 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3549 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3550 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3552 return AteExtraComma ? InstExtraComma : InstNormal;
3556 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3557 /// ParameterList OptionalAttrs
3558 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3560 unsigned RetAttrs, FnAttrs;
3562 PATypeHolder RetType(Type::getVoidTy(Context));
3565 SmallVector<ParamInfo, 16> ArgList;
3566 LocTy CallLoc = Lex.getLoc();
3568 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3569 ParseOptionalCallingConv(CC) ||
3570 ParseOptionalAttrs(RetAttrs, 1) ||
3571 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3572 ParseValID(CalleeID) ||
3573 ParseParameterList(ArgList, PFS) ||
3574 ParseOptionalAttrs(FnAttrs, 2))
3577 // If RetType is a non-function pointer type, then this is the short syntax
3578 // for the call, which means that RetType is just the return type. Infer the
3579 // rest of the function argument types from the arguments that are present.
3580 const PointerType *PFTy = 0;
3581 const FunctionType *Ty = 0;
3582 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3583 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3584 // Pull out the types of all of the arguments...
3585 std::vector<const Type*> ParamTypes;
3586 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3587 ParamTypes.push_back(ArgList[i].V->getType());
3589 if (!FunctionType::isValidReturnType(RetType))
3590 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3592 Ty = FunctionType::get(RetType, ParamTypes, false);
3593 PFTy = PointerType::getUnqual(Ty);
3596 // Look up the callee.
3598 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3600 // Set up the Attributes for the function.
3601 SmallVector<AttributeWithIndex, 8> Attrs;
3602 if (RetAttrs != Attribute::None)
3603 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3605 SmallVector<Value*, 8> Args;
3607 // Loop through FunctionType's arguments and ensure they are specified
3608 // correctly. Also, gather any parameter attributes.
3609 FunctionType::param_iterator I = Ty->param_begin();
3610 FunctionType::param_iterator E = Ty->param_end();
3611 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3612 const Type *ExpectedTy = 0;
3615 } else if (!Ty->isVarArg()) {
3616 return Error(ArgList[i].Loc, "too many arguments specified");
3619 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3620 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3621 ExpectedTy->getDescription() + "'");
3622 Args.push_back(ArgList[i].V);
3623 if (ArgList[i].Attrs != Attribute::None)
3624 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3628 return Error(CallLoc, "not enough parameters specified for call");
3630 if (FnAttrs != Attribute::None)
3631 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3633 // Finish off the Attributes and check them
3634 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3636 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3637 CI->setTailCall(isTail);
3638 CI->setCallingConv(CC);
3639 CI->setAttributes(PAL);
3644 //===----------------------------------------------------------------------===//
3645 // Memory Instructions.
3646 //===----------------------------------------------------------------------===//
3649 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3650 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3651 PATypeHolder Ty(Type::getVoidTy(Context));
3654 unsigned Alignment = 0;
3655 if (ParseType(Ty)) return true;
3657 bool AteExtraComma = false;
3658 if (EatIfPresent(lltok::comma)) {
3659 if (Lex.getKind() == lltok::kw_align) {
3660 if (ParseOptionalAlignment(Alignment)) return true;
3661 } else if (Lex.getKind() == lltok::MetadataVar) {
3662 AteExtraComma = true;
3664 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3665 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3670 if (Size && !Size->getType()->isIntegerTy())
3671 return Error(SizeLoc, "element count must have integer type");
3673 Inst = new AllocaInst(Ty, Size, Alignment);
3674 return AteExtraComma ? InstExtraComma : InstNormal;
3678 /// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3679 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3681 Value *Val; LocTy Loc;
3682 unsigned Alignment = 0;
3683 bool AteExtraComma = false;
3684 if (ParseTypeAndValue(Val, Loc, PFS) ||
3685 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3688 if (!Val->getType()->isPointerTy() ||
3689 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3690 return Error(Loc, "load operand must be a pointer to a first class type");
3692 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3693 return AteExtraComma ? InstExtraComma : InstNormal;
3697 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3698 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3700 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3701 unsigned Alignment = 0;
3702 bool AteExtraComma = false;
3703 if (ParseTypeAndValue(Val, Loc, PFS) ||
3704 ParseToken(lltok::comma, "expected ',' after store operand") ||
3705 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3706 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3709 if (!Ptr->getType()->isPointerTy())
3710 return Error(PtrLoc, "store operand must be a pointer");
3711 if (!Val->getType()->isFirstClassType())
3712 return Error(Loc, "store operand must be a first class value");
3713 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3714 return Error(Loc, "stored value and pointer type do not match");
3716 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3717 return AteExtraComma ? InstExtraComma : InstNormal;
3721 /// ::= 'getresult' TypeAndValue ',' i32
3722 /// FIXME: Remove support for getresult in LLVM 3.0
3723 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3724 Value *Val; LocTy ValLoc, EltLoc;
3726 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3727 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3728 ParseUInt32(Element, EltLoc))
3731 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
3732 return Error(ValLoc, "getresult inst requires an aggregate operand");
3733 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3734 return Error(EltLoc, "invalid getresult index for value");
3735 Inst = ExtractValueInst::Create(Val, Element);
3739 /// ParseGetElementPtr
3740 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3741 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3742 Value *Ptr, *Val; LocTy Loc, EltLoc;
3744 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3746 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3748 if (!Ptr->getType()->isPointerTy())
3749 return Error(Loc, "base of getelementptr must be a pointer");
3751 SmallVector<Value*, 16> Indices;
3752 bool AteExtraComma = false;
3753 while (EatIfPresent(lltok::comma)) {
3754 if (Lex.getKind() == lltok::MetadataVar) {
3755 AteExtraComma = true;
3758 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3759 if (!Val->getType()->isIntegerTy())
3760 return Error(EltLoc, "getelementptr index must be an integer");
3761 Indices.push_back(Val);
3764 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3765 Indices.begin(), Indices.end()))
3766 return Error(Loc, "invalid getelementptr indices");
3767 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3769 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3770 return AteExtraComma ? InstExtraComma : InstNormal;
3773 /// ParseExtractValue
3774 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3775 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3776 Value *Val; LocTy Loc;
3777 SmallVector<unsigned, 4> Indices;
3779 if (ParseTypeAndValue(Val, Loc, PFS) ||
3780 ParseIndexList(Indices, AteExtraComma))
3783 if (!Val->getType()->isAggregateType())
3784 return Error(Loc, "extractvalue operand must be aggregate type");
3786 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3788 return Error(Loc, "invalid indices for extractvalue");
3789 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3790 return AteExtraComma ? InstExtraComma : InstNormal;
3793 /// ParseInsertValue
3794 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3795 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3796 Value *Val0, *Val1; LocTy Loc0, Loc1;
3797 SmallVector<unsigned, 4> Indices;
3799 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3800 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3801 ParseTypeAndValue(Val1, Loc1, PFS) ||
3802 ParseIndexList(Indices, AteExtraComma))
3805 if (!Val0->getType()->isAggregateType())
3806 return Error(Loc0, "insertvalue operand must be aggregate type");
3808 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3810 return Error(Loc0, "invalid indices for insertvalue");
3811 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3812 return AteExtraComma ? InstExtraComma : InstNormal;
3815 //===----------------------------------------------------------------------===//
3816 // Embedded metadata.
3817 //===----------------------------------------------------------------------===//
3819 /// ParseMDNodeVector
3820 /// ::= Element (',' Element)*
3822 /// ::= 'null' | TypeAndValue
3823 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
3824 PerFunctionState *PFS) {
3825 // Check for an empty list.
3826 if (Lex.getKind() == lltok::rbrace)
3830 // Null is a special case since it is typeless.
3831 if (EatIfPresent(lltok::kw_null)) {
3837 PATypeHolder Ty(Type::getVoidTy(Context));
3839 if (ParseType(Ty) || ParseValID(ID, PFS) ||
3840 ConvertValIDToValue(Ty, ID, V, PFS))
3844 } while (EatIfPresent(lltok::comma));