LLVM API Documentation
00001 //===-- LLParser.cpp - Parser Class ---------------------------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines the parser class for .ll files. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "LLParser.h" 00015 #include "llvm/ADT/SmallPtrSet.h" 00016 #include "llvm/AutoUpgrade.h" 00017 #include "llvm/IR/CallingConv.h" 00018 #include "llvm/IR/Constants.h" 00019 #include "llvm/IR/DerivedTypes.h" 00020 #include "llvm/IR/InlineAsm.h" 00021 #include "llvm/IR/Instructions.h" 00022 #include "llvm/IR/Module.h" 00023 #include "llvm/IR/Operator.h" 00024 #include "llvm/IR/ValueSymbolTable.h" 00025 #include "llvm/Support/ErrorHandling.h" 00026 #include "llvm/Support/raw_ostream.h" 00027 using namespace llvm; 00028 00029 static std::string getTypeString(Type *T) { 00030 std::string Result; 00031 raw_string_ostream Tmp(Result); 00032 Tmp << *T; 00033 return Tmp.str(); 00034 } 00035 00036 /// Run: module ::= toplevelentity* 00037 bool LLParser::Run() { 00038 // Prime the lexer. 00039 Lex.Lex(); 00040 00041 return ParseTopLevelEntities() || 00042 ValidateEndOfModule(); 00043 } 00044 00045 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the 00046 /// module. 00047 bool LLParser::ValidateEndOfModule() { 00048 // Handle any instruction metadata forward references. 00049 if (!ForwardRefInstMetadata.empty()) { 00050 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator 00051 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end(); 00052 I != E; ++I) { 00053 Instruction *Inst = I->first; 00054 const std::vector<MDRef> &MDList = I->second; 00055 00056 for (unsigned i = 0, e = MDList.size(); i != e; ++i) { 00057 unsigned SlotNo = MDList[i].MDSlot; 00058 00059 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0) 00060 return Error(MDList[i].Loc, "use of undefined metadata '!" + 00061 Twine(SlotNo) + "'"); 00062 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]); 00063 } 00064 } 00065 ForwardRefInstMetadata.clear(); 00066 } 00067 00068 // Handle any function attribute group forward references. 00069 for (std::map<Value*, std::vector<unsigned> >::iterator 00070 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end(); 00071 I != E; ++I) { 00072 Value *V = I->first; 00073 std::vector<unsigned> &Vec = I->second; 00074 AttrBuilder B; 00075 00076 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end(); 00077 VI != VE; ++VI) 00078 B.merge(NumberedAttrBuilders[*VI]); 00079 00080 if (Function *Fn = dyn_cast<Function>(V)) { 00081 AttributeSet AS = Fn->getAttributes(); 00082 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex); 00083 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex, 00084 AS.getFnAttributes()); 00085 00086 FnAttrs.merge(B); 00087 00088 // If the alignment was parsed as an attribute, move to the alignment 00089 // field. 00090 if (FnAttrs.hasAlignmentAttr()) { 00091 Fn->setAlignment(FnAttrs.getAlignment()); 00092 FnAttrs.removeAttribute(Attribute::Alignment); 00093 } 00094 00095 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex, 00096 AttributeSet::get(Context, 00097 AttributeSet::FunctionIndex, 00098 FnAttrs)); 00099 Fn->setAttributes(AS); 00100 } else if (CallInst *CI = dyn_cast<CallInst>(V)) { 00101 AttributeSet AS = CI->getAttributes(); 00102 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex); 00103 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex, 00104 AS.getFnAttributes()); 00105 FnAttrs.merge(B); 00106 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex, 00107 AttributeSet::get(Context, 00108 AttributeSet::FunctionIndex, 00109 FnAttrs)); 00110 CI->setAttributes(AS); 00111 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) { 00112 AttributeSet AS = II->getAttributes(); 00113 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex); 00114 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex, 00115 AS.getFnAttributes()); 00116 FnAttrs.merge(B); 00117 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex, 00118 AttributeSet::get(Context, 00119 AttributeSet::FunctionIndex, 00120 FnAttrs)); 00121 II->setAttributes(AS); 00122 } else { 00123 llvm_unreachable("invalid object with forward attribute group reference"); 00124 } 00125 } 00126 00127 // If there are entries in ForwardRefBlockAddresses at this point, they are 00128 // references after the function was defined. Resolve those now. 00129 while (!ForwardRefBlockAddresses.empty()) { 00130 // Okay, we are referencing an already-parsed function, resolve them now. 00131 Function *TheFn = 0; 00132 const ValID &Fn = ForwardRefBlockAddresses.begin()->first; 00133 if (Fn.Kind == ValID::t_GlobalName) 00134 TheFn = M->getFunction(Fn.StrVal); 00135 else if (Fn.UIntVal < NumberedVals.size()) 00136 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]); 00137 00138 if (TheFn == 0) 00139 return Error(Fn.Loc, "unknown function referenced by blockaddress"); 00140 00141 // Resolve all these references. 00142 if (ResolveForwardRefBlockAddresses(TheFn, 00143 ForwardRefBlockAddresses.begin()->second, 00144 0)) 00145 return true; 00146 00147 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin()); 00148 } 00149 00150 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) 00151 if (NumberedTypes[i].second.isValid()) 00152 return Error(NumberedTypes[i].second, 00153 "use of undefined type '%" + Twine(i) + "'"); 00154 00155 for (StringMap<std::pair<Type*, LocTy> >::iterator I = 00156 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) 00157 if (I->second.second.isValid()) 00158 return Error(I->second.second, 00159 "use of undefined type named '" + I->getKey() + "'"); 00160 00161 if (!ForwardRefVals.empty()) 00162 return Error(ForwardRefVals.begin()->second.second, 00163 "use of undefined value '@" + ForwardRefVals.begin()->first + 00164 "'"); 00165 00166 if (!ForwardRefValIDs.empty()) 00167 return Error(ForwardRefValIDs.begin()->second.second, 00168 "use of undefined value '@" + 00169 Twine(ForwardRefValIDs.begin()->first) + "'"); 00170 00171 if (!ForwardRefMDNodes.empty()) 00172 return Error(ForwardRefMDNodes.begin()->second.second, 00173 "use of undefined metadata '!" + 00174 Twine(ForwardRefMDNodes.begin()->first) + "'"); 00175 00176 00177 // Look for intrinsic functions and CallInst that need to be upgraded 00178 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) 00179 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove 00180 00181 return false; 00182 } 00183 00184 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn, 00185 std::vector<std::pair<ValID, GlobalValue*> > &Refs, 00186 PerFunctionState *PFS) { 00187 // Loop over all the references, resolving them. 00188 for (unsigned i = 0, e = Refs.size(); i != e; ++i) { 00189 BasicBlock *Res; 00190 if (PFS) { 00191 if (Refs[i].first.Kind == ValID::t_LocalName) 00192 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc); 00193 else 00194 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc); 00195 } else if (Refs[i].first.Kind == ValID::t_LocalID) { 00196 return Error(Refs[i].first.Loc, 00197 "cannot take address of numeric label after the function is defined"); 00198 } else { 00199 Res = dyn_cast_or_null<BasicBlock>( 00200 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal)); 00201 } 00202 00203 if (Res == 0) 00204 return Error(Refs[i].first.Loc, 00205 "referenced value is not a basic block"); 00206 00207 // Get the BlockAddress for this and update references to use it. 00208 BlockAddress *BA = BlockAddress::get(TheFn, Res); 00209 Refs[i].second->replaceAllUsesWith(BA); 00210 Refs[i].second->eraseFromParent(); 00211 } 00212 return false; 00213 } 00214 00215 00216 //===----------------------------------------------------------------------===// 00217 // Top-Level Entities 00218 //===----------------------------------------------------------------------===// 00219 00220 bool LLParser::ParseTopLevelEntities() { 00221 while (1) { 00222 switch (Lex.getKind()) { 00223 default: return TokError("expected top-level entity"); 00224 case lltok::Eof: return false; 00225 case lltok::kw_declare: if (ParseDeclare()) return true; break; 00226 case lltok::kw_define: if (ParseDefine()) return true; break; 00227 case lltok::kw_module: if (ParseModuleAsm()) return true; break; 00228 case lltok::kw_target: if (ParseTargetDefinition()) return true; break; 00229 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break; 00230 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break; 00231 case lltok::LocalVar: if (ParseNamedType()) return true; break; 00232 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break; 00233 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break; 00234 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break; 00235 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break; 00236 00237 // The Global variable production with no name can have many different 00238 // optional leading prefixes, the production is: 00239 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal 00240 // OptionalAddrSpace OptionalUnNammedAddr 00241 // ('constant'|'global') ... 00242 case lltok::kw_private: // OptionalLinkage 00243 case lltok::kw_linker_private: // OptionalLinkage 00244 case lltok::kw_linker_private_weak: // OptionalLinkage 00245 case lltok::kw_linker_private_weak_def_auto: // FIXME: backwards compat. 00246 case lltok::kw_internal: // OptionalLinkage 00247 case lltok::kw_weak: // OptionalLinkage 00248 case lltok::kw_weak_odr: // OptionalLinkage 00249 case lltok::kw_linkonce: // OptionalLinkage 00250 case lltok::kw_linkonce_odr: // OptionalLinkage 00251 case lltok::kw_linkonce_odr_auto_hide: // OptionalLinkage 00252 case lltok::kw_appending: // OptionalLinkage 00253 case lltok::kw_dllexport: // OptionalLinkage 00254 case lltok::kw_common: // OptionalLinkage 00255 case lltok::kw_dllimport: // OptionalLinkage 00256 case lltok::kw_extern_weak: // OptionalLinkage 00257 case lltok::kw_external: { // OptionalLinkage 00258 unsigned Linkage, Visibility; 00259 if (ParseOptionalLinkage(Linkage) || 00260 ParseOptionalVisibility(Visibility) || 00261 ParseGlobal("", SMLoc(), Linkage, true, Visibility)) 00262 return true; 00263 break; 00264 } 00265 case lltok::kw_default: // OptionalVisibility 00266 case lltok::kw_hidden: // OptionalVisibility 00267 case lltok::kw_protected: { // OptionalVisibility 00268 unsigned Visibility; 00269 if (ParseOptionalVisibility(Visibility) || 00270 ParseGlobal("", SMLoc(), 0, false, Visibility)) 00271 return true; 00272 break; 00273 } 00274 00275 case lltok::kw_thread_local: // OptionalThreadLocal 00276 case lltok::kw_addrspace: // OptionalAddrSpace 00277 case lltok::kw_constant: // GlobalType 00278 case lltok::kw_global: // GlobalType 00279 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true; 00280 break; 00281 00282 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break; 00283 } 00284 } 00285 } 00286 00287 00288 /// toplevelentity 00289 /// ::= 'module' 'asm' STRINGCONSTANT 00290 bool LLParser::ParseModuleAsm() { 00291 assert(Lex.getKind() == lltok::kw_module); 00292 Lex.Lex(); 00293 00294 std::string AsmStr; 00295 if (ParseToken(lltok::kw_asm, "expected 'module asm'") || 00296 ParseStringConstant(AsmStr)) return true; 00297 00298 M->appendModuleInlineAsm(AsmStr); 00299 return false; 00300 } 00301 00302 /// toplevelentity 00303 /// ::= 'target' 'triple' '=' STRINGCONSTANT 00304 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT 00305 bool LLParser::ParseTargetDefinition() { 00306 assert(Lex.getKind() == lltok::kw_target); 00307 std::string Str; 00308 switch (Lex.Lex()) { 00309 default: return TokError("unknown target property"); 00310 case lltok::kw_triple: 00311 Lex.Lex(); 00312 if (ParseToken(lltok::equal, "expected '=' after target triple") || 00313 ParseStringConstant(Str)) 00314 return true; 00315 M->setTargetTriple(Str); 00316 return false; 00317 case lltok::kw_datalayout: 00318 Lex.Lex(); 00319 if (ParseToken(lltok::equal, "expected '=' after target datalayout") || 00320 ParseStringConstant(Str)) 00321 return true; 00322 M->setDataLayout(Str); 00323 return false; 00324 } 00325 } 00326 00327 /// toplevelentity 00328 /// ::= 'deplibs' '=' '[' ']' 00329 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']' 00330 /// FIXME: Remove in 4.0. Currently parse, but ignore. 00331 bool LLParser::ParseDepLibs() { 00332 assert(Lex.getKind() == lltok::kw_deplibs); 00333 Lex.Lex(); 00334 if (ParseToken(lltok::equal, "expected '=' after deplibs") || 00335 ParseToken(lltok::lsquare, "expected '=' after deplibs")) 00336 return true; 00337 00338 if (EatIfPresent(lltok::rsquare)) 00339 return false; 00340 00341 do { 00342 std::string Str; 00343 if (ParseStringConstant(Str)) return true; 00344 } while (EatIfPresent(lltok::comma)); 00345 00346 return ParseToken(lltok::rsquare, "expected ']' at end of list"); 00347 } 00348 00349 /// ParseUnnamedType: 00350 /// ::= LocalVarID '=' 'type' type 00351 bool LLParser::ParseUnnamedType() { 00352 LocTy TypeLoc = Lex.getLoc(); 00353 unsigned TypeID = Lex.getUIntVal(); 00354 Lex.Lex(); // eat LocalVarID; 00355 00356 if (ParseToken(lltok::equal, "expected '=' after name") || 00357 ParseToken(lltok::kw_type, "expected 'type' after '='")) 00358 return true; 00359 00360 if (TypeID >= NumberedTypes.size()) 00361 NumberedTypes.resize(TypeID+1); 00362 00363 Type *Result = 0; 00364 if (ParseStructDefinition(TypeLoc, "", 00365 NumberedTypes[TypeID], Result)) return true; 00366 00367 if (!isa<StructType>(Result)) { 00368 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID]; 00369 if (Entry.first) 00370 return Error(TypeLoc, "non-struct types may not be recursive"); 00371 Entry.first = Result; 00372 Entry.second = SMLoc(); 00373 } 00374 00375 return false; 00376 } 00377 00378 00379 /// toplevelentity 00380 /// ::= LocalVar '=' 'type' type 00381 bool LLParser::ParseNamedType() { 00382 std::string Name = Lex.getStrVal(); 00383 LocTy NameLoc = Lex.getLoc(); 00384 Lex.Lex(); // eat LocalVar. 00385 00386 if (ParseToken(lltok::equal, "expected '=' after name") || 00387 ParseToken(lltok::kw_type, "expected 'type' after name")) 00388 return true; 00389 00390 Type *Result = 0; 00391 if (ParseStructDefinition(NameLoc, Name, 00392 NamedTypes[Name], Result)) return true; 00393 00394 if (!isa<StructType>(Result)) { 00395 std::pair<Type*, LocTy> &Entry = NamedTypes[Name]; 00396 if (Entry.first) 00397 return Error(NameLoc, "non-struct types may not be recursive"); 00398 Entry.first = Result; 00399 Entry.second = SMLoc(); 00400 } 00401 00402 return false; 00403 } 00404 00405 00406 /// toplevelentity 00407 /// ::= 'declare' FunctionHeader 00408 bool LLParser::ParseDeclare() { 00409 assert(Lex.getKind() == lltok::kw_declare); 00410 Lex.Lex(); 00411 00412 Function *F; 00413 return ParseFunctionHeader(F, false); 00414 } 00415 00416 /// toplevelentity 00417 /// ::= 'define' FunctionHeader '{' ... 00418 bool LLParser::ParseDefine() { 00419 assert(Lex.getKind() == lltok::kw_define); 00420 Lex.Lex(); 00421 00422 Function *F; 00423 return ParseFunctionHeader(F, true) || 00424 ParseFunctionBody(*F); 00425 } 00426 00427 /// ParseGlobalType 00428 /// ::= 'constant' 00429 /// ::= 'global' 00430 bool LLParser::ParseGlobalType(bool &IsConstant) { 00431 if (Lex.getKind() == lltok::kw_constant) 00432 IsConstant = true; 00433 else if (Lex.getKind() == lltok::kw_global) 00434 IsConstant = false; 00435 else { 00436 IsConstant = false; 00437 return TokError("expected 'global' or 'constant'"); 00438 } 00439 Lex.Lex(); 00440 return false; 00441 } 00442 00443 /// ParseUnnamedGlobal: 00444 /// OptionalVisibility ALIAS ... 00445 /// OptionalLinkage OptionalVisibility ... -> global variable 00446 /// GlobalID '=' OptionalVisibility ALIAS ... 00447 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable 00448 bool LLParser::ParseUnnamedGlobal() { 00449 unsigned VarID = NumberedVals.size(); 00450 std::string Name; 00451 LocTy NameLoc = Lex.getLoc(); 00452 00453 // Handle the GlobalID form. 00454 if (Lex.getKind() == lltok::GlobalID) { 00455 if (Lex.getUIntVal() != VarID) 00456 return Error(Lex.getLoc(), "variable expected to be numbered '%" + 00457 Twine(VarID) + "'"); 00458 Lex.Lex(); // eat GlobalID; 00459 00460 if (ParseToken(lltok::equal, "expected '=' after name")) 00461 return true; 00462 } 00463 00464 bool HasLinkage; 00465 unsigned Linkage, Visibility; 00466 if (ParseOptionalLinkage(Linkage, HasLinkage) || 00467 ParseOptionalVisibility(Visibility)) 00468 return true; 00469 00470 if (HasLinkage || Lex.getKind() != lltok::kw_alias) 00471 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility); 00472 return ParseAlias(Name, NameLoc, Visibility); 00473 } 00474 00475 /// ParseNamedGlobal: 00476 /// GlobalVar '=' OptionalVisibility ALIAS ... 00477 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable 00478 bool LLParser::ParseNamedGlobal() { 00479 assert(Lex.getKind() == lltok::GlobalVar); 00480 LocTy NameLoc = Lex.getLoc(); 00481 std::string Name = Lex.getStrVal(); 00482 Lex.Lex(); 00483 00484 bool HasLinkage; 00485 unsigned Linkage, Visibility; 00486 if (ParseToken(lltok::equal, "expected '=' in global variable") || 00487 ParseOptionalLinkage(Linkage, HasLinkage) || 00488 ParseOptionalVisibility(Visibility)) 00489 return true; 00490 00491 if (HasLinkage || Lex.getKind() != lltok::kw_alias) 00492 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility); 00493 return ParseAlias(Name, NameLoc, Visibility); 00494 } 00495 00496 // MDString: 00497 // ::= '!' STRINGCONSTANT 00498 bool LLParser::ParseMDString(MDString *&Result) { 00499 std::string Str; 00500 if (ParseStringConstant(Str)) return true; 00501 Result = MDString::get(Context, Str); 00502 return false; 00503 } 00504 00505 // MDNode: 00506 // ::= '!' MDNodeNumber 00507 // 00508 /// This version of ParseMDNodeID returns the slot number and null in the case 00509 /// of a forward reference. 00510 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) { 00511 // !{ ..., !42, ... } 00512 if (ParseUInt32(SlotNo)) return true; 00513 00514 // Check existing MDNode. 00515 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0) 00516 Result = NumberedMetadata[SlotNo]; 00517 else 00518 Result = 0; 00519 return false; 00520 } 00521 00522 bool LLParser::ParseMDNodeID(MDNode *&Result) { 00523 // !{ ..., !42, ... } 00524 unsigned MID = 0; 00525 if (ParseMDNodeID(Result, MID)) return true; 00526 00527 // If not a forward reference, just return it now. 00528 if (Result) return false; 00529 00530 // Otherwise, create MDNode forward reference. 00531 MDNode *FwdNode = MDNode::getTemporary(Context, None); 00532 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc()); 00533 00534 if (NumberedMetadata.size() <= MID) 00535 NumberedMetadata.resize(MID+1); 00536 NumberedMetadata[MID] = FwdNode; 00537 Result = FwdNode; 00538 return false; 00539 } 00540 00541 /// ParseNamedMetadata: 00542 /// !foo = !{ !1, !2 } 00543 bool LLParser::ParseNamedMetadata() { 00544 assert(Lex.getKind() == lltok::MetadataVar); 00545 std::string Name = Lex.getStrVal(); 00546 Lex.Lex(); 00547 00548 if (ParseToken(lltok::equal, "expected '=' here") || 00549 ParseToken(lltok::exclaim, "Expected '!' here") || 00550 ParseToken(lltok::lbrace, "Expected '{' here")) 00551 return true; 00552 00553 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name); 00554 if (Lex.getKind() != lltok::rbrace) 00555 do { 00556 if (ParseToken(lltok::exclaim, "Expected '!' here")) 00557 return true; 00558 00559 MDNode *N = 0; 00560 if (ParseMDNodeID(N)) return true; 00561 NMD->addOperand(N); 00562 } while (EatIfPresent(lltok::comma)); 00563 00564 if (ParseToken(lltok::rbrace, "expected end of metadata node")) 00565 return true; 00566 00567 return false; 00568 } 00569 00570 /// ParseStandaloneMetadata: 00571 /// !42 = !{...} 00572 bool LLParser::ParseStandaloneMetadata() { 00573 assert(Lex.getKind() == lltok::exclaim); 00574 Lex.Lex(); 00575 unsigned MetadataID = 0; 00576 00577 LocTy TyLoc; 00578 Type *Ty = 0; 00579 SmallVector<Value *, 16> Elts; 00580 if (ParseUInt32(MetadataID) || 00581 ParseToken(lltok::equal, "expected '=' here") || 00582 ParseType(Ty, TyLoc) || 00583 ParseToken(lltok::exclaim, "Expected '!' here") || 00584 ParseToken(lltok::lbrace, "Expected '{' here") || 00585 ParseMDNodeVector(Elts, NULL) || 00586 ParseToken(lltok::rbrace, "expected end of metadata node")) 00587 return true; 00588 00589 MDNode *Init = MDNode::get(Context, Elts); 00590 00591 // See if this was forward referenced, if so, handle it. 00592 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator 00593 FI = ForwardRefMDNodes.find(MetadataID); 00594 if (FI != ForwardRefMDNodes.end()) { 00595 MDNode *Temp = FI->second.first; 00596 Temp->replaceAllUsesWith(Init); 00597 MDNode::deleteTemporary(Temp); 00598 ForwardRefMDNodes.erase(FI); 00599 00600 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work"); 00601 } else { 00602 if (MetadataID >= NumberedMetadata.size()) 00603 NumberedMetadata.resize(MetadataID+1); 00604 00605 if (NumberedMetadata[MetadataID] != 0) 00606 return TokError("Metadata id is already used"); 00607 NumberedMetadata[MetadataID] = Init; 00608 } 00609 00610 return false; 00611 } 00612 00613 /// ParseAlias: 00614 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee 00615 /// Aliasee 00616 /// ::= TypeAndValue 00617 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')' 00618 /// ::= 'getelementptr' 'inbounds'? '(' ... ')' 00619 /// 00620 /// Everything through visibility has already been parsed. 00621 /// 00622 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, 00623 unsigned Visibility) { 00624 assert(Lex.getKind() == lltok::kw_alias); 00625 Lex.Lex(); 00626 unsigned Linkage; 00627 LocTy LinkageLoc = Lex.getLoc(); 00628 if (ParseOptionalLinkage(Linkage)) 00629 return true; 00630 00631 if (Linkage != GlobalValue::ExternalLinkage && 00632 Linkage != GlobalValue::WeakAnyLinkage && 00633 Linkage != GlobalValue::WeakODRLinkage && 00634 Linkage != GlobalValue::InternalLinkage && 00635 Linkage != GlobalValue::PrivateLinkage && 00636 Linkage != GlobalValue::LinkerPrivateLinkage && 00637 Linkage != GlobalValue::LinkerPrivateWeakLinkage) 00638 return Error(LinkageLoc, "invalid linkage type for alias"); 00639 00640 Constant *Aliasee; 00641 LocTy AliaseeLoc = Lex.getLoc(); 00642 if (Lex.getKind() != lltok::kw_bitcast && 00643 Lex.getKind() != lltok::kw_getelementptr) { 00644 if (ParseGlobalTypeAndValue(Aliasee)) return true; 00645 } else { 00646 // The bitcast dest type is not present, it is implied by the dest type. 00647 ValID ID; 00648 if (ParseValID(ID)) return true; 00649 if (ID.Kind != ValID::t_Constant) 00650 return Error(AliaseeLoc, "invalid aliasee"); 00651 Aliasee = ID.ConstantVal; 00652 } 00653 00654 if (!Aliasee->getType()->isPointerTy()) 00655 return Error(AliaseeLoc, "alias must have pointer type"); 00656 00657 // Okay, create the alias but do not insert it into the module yet. 00658 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), 00659 (GlobalValue::LinkageTypes)Linkage, Name, 00660 Aliasee); 00661 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility); 00662 00663 // See if this value already exists in the symbol table. If so, it is either 00664 // a redefinition or a definition of a forward reference. 00665 if (GlobalValue *Val = M->getNamedValue(Name)) { 00666 // See if this was a redefinition. If so, there is no entry in 00667 // ForwardRefVals. 00668 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator 00669 I = ForwardRefVals.find(Name); 00670 if (I == ForwardRefVals.end()) 00671 return Error(NameLoc, "redefinition of global named '@" + Name + "'"); 00672 00673 // Otherwise, this was a definition of forward ref. Verify that types 00674 // agree. 00675 if (Val->getType() != GA->getType()) 00676 return Error(NameLoc, 00677 "forward reference and definition of alias have different types"); 00678 00679 // If they agree, just RAUW the old value with the alias and remove the 00680 // forward ref info. 00681 Val->replaceAllUsesWith(GA); 00682 Val->eraseFromParent(); 00683 ForwardRefVals.erase(I); 00684 } 00685 00686 // Insert into the module, we know its name won't collide now. 00687 M->getAliasList().push_back(GA); 00688 assert(GA->getName() == Name && "Should not be a name conflict!"); 00689 00690 return false; 00691 } 00692 00693 /// ParseGlobal 00694 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal 00695 /// OptionalAddrSpace OptionalUnNammedAddr 00696 /// OptionalExternallyInitialized GlobalType Type Const 00697 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal 00698 /// OptionalAddrSpace OptionalUnNammedAddr 00699 /// OptionalExternallyInitialized GlobalType Type Const 00700 /// 00701 /// Everything through visibility has been parsed already. 00702 /// 00703 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, 00704 unsigned Linkage, bool HasLinkage, 00705 unsigned Visibility) { 00706 unsigned AddrSpace; 00707 bool IsConstant, UnnamedAddr, IsExternallyInitialized; 00708 GlobalVariable::ThreadLocalMode TLM; 00709 LocTy UnnamedAddrLoc; 00710 LocTy IsExternallyInitializedLoc; 00711 LocTy TyLoc; 00712 00713 Type *Ty = 0; 00714 if (ParseOptionalThreadLocal(TLM) || 00715 ParseOptionalAddrSpace(AddrSpace) || 00716 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr, 00717 &UnnamedAddrLoc) || 00718 ParseOptionalToken(lltok::kw_externally_initialized, 00719 IsExternallyInitialized, 00720 &IsExternallyInitializedLoc) || 00721 ParseGlobalType(IsConstant) || 00722 ParseType(Ty, TyLoc)) 00723 return true; 00724 00725 // If the linkage is specified and is external, then no initializer is 00726 // present. 00727 Constant *Init = 0; 00728 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage && 00729 Linkage != GlobalValue::ExternalWeakLinkage && 00730 Linkage != GlobalValue::ExternalLinkage)) { 00731 if (ParseGlobalValue(Ty, Init)) 00732 return true; 00733 } 00734 00735 if (Ty->isFunctionTy() || Ty->isLabelTy()) 00736 return Error(TyLoc, "invalid type for global variable"); 00737 00738 GlobalVariable *GV = 0; 00739 00740 // See if the global was forward referenced, if so, use the global. 00741 if (!Name.empty()) { 00742 if (GlobalValue *GVal = M->getNamedValue(Name)) { 00743 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal)) 00744 return Error(NameLoc, "redefinition of global '@" + Name + "'"); 00745 GV = cast<GlobalVariable>(GVal); 00746 } 00747 } else { 00748 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator 00749 I = ForwardRefValIDs.find(NumberedVals.size()); 00750 if (I != ForwardRefValIDs.end()) { 00751 GV = cast<GlobalVariable>(I->second.first); 00752 ForwardRefValIDs.erase(I); 00753 } 00754 } 00755 00756 if (GV == 0) { 00757 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0, 00758 Name, 0, GlobalVariable::NotThreadLocal, 00759 AddrSpace); 00760 } else { 00761 if (GV->getType()->getElementType() != Ty) 00762 return Error(TyLoc, 00763 "forward reference and definition of global have different types"); 00764 00765 // Move the forward-reference to the correct spot in the module. 00766 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV); 00767 } 00768 00769 if (Name.empty()) 00770 NumberedVals.push_back(GV); 00771 00772 // Set the parsed properties on the global. 00773 if (Init) 00774 GV->setInitializer(Init); 00775 GV->setConstant(IsConstant); 00776 GV->setLinkage((GlobalValue::LinkageTypes)Linkage); 00777 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility); 00778 GV->setExternallyInitialized(IsExternallyInitialized); 00779 GV->setThreadLocalMode(TLM); 00780 GV->setUnnamedAddr(UnnamedAddr); 00781 00782 // Parse attributes on the global. 00783 while (Lex.getKind() == lltok::comma) { 00784 Lex.Lex(); 00785 00786 if (Lex.getKind() == lltok::kw_section) { 00787 Lex.Lex(); 00788 GV->setSection(Lex.getStrVal()); 00789 if (ParseToken(lltok::StringConstant, "expected global section string")) 00790 return true; 00791 } else if (Lex.getKind() == lltok::kw_align) { 00792 unsigned Alignment; 00793 if (ParseOptionalAlignment(Alignment)) return true; 00794 GV->setAlignment(Alignment); 00795 } else { 00796 TokError("unknown global variable property!"); 00797 } 00798 } 00799 00800 return false; 00801 } 00802 00803 /// ParseUnnamedAttrGrp 00804 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}' 00805 bool LLParser::ParseUnnamedAttrGrp() { 00806 assert(Lex.getKind() == lltok::kw_attributes); 00807 LocTy AttrGrpLoc = Lex.getLoc(); 00808 Lex.Lex(); 00809 00810 assert(Lex.getKind() == lltok::AttrGrpID); 00811 unsigned VarID = Lex.getUIntVal(); 00812 std::vector<unsigned> unused; 00813 LocTy NoBuiltinLoc; 00814 Lex.Lex(); 00815 00816 if (ParseToken(lltok::equal, "expected '=' here") || 00817 ParseToken(lltok::lbrace, "expected '{' here") || 00818 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true, 00819 NoBuiltinLoc) || 00820 ParseToken(lltok::rbrace, "expected end of attribute group")) 00821 return true; 00822 00823 if (!NumberedAttrBuilders[VarID].hasAttributes()) 00824 return Error(AttrGrpLoc, "attribute group has no attributes"); 00825 00826 return false; 00827 } 00828 00829 /// ParseFnAttributeValuePairs 00830 /// ::= <attr> | <attr> '=' <value> 00831 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B, 00832 std::vector<unsigned> &FwdRefAttrGrps, 00833 bool inAttrGrp, LocTy &NoBuiltinLoc) { 00834 bool HaveError = false; 00835 00836 B.clear(); 00837 00838 while (true) { 00839 lltok::Kind Token = Lex.getKind(); 00840 if (Token == lltok::kw_nobuiltin) 00841 NoBuiltinLoc = Lex.getLoc(); 00842 switch (Token) { 00843 default: 00844 if (!inAttrGrp) return HaveError; 00845 return Error(Lex.getLoc(), "unterminated attribute group"); 00846 case lltok::rbrace: 00847 // Finished. 00848 return false; 00849 00850 case lltok::AttrGrpID: { 00851 // Allow a function to reference an attribute group: 00852 // 00853 // define void @foo() #1 { ... } 00854 if (inAttrGrp) 00855 HaveError |= 00856 Error(Lex.getLoc(), 00857 "cannot have an attribute group reference in an attribute group"); 00858 00859 unsigned AttrGrpNum = Lex.getUIntVal(); 00860 if (inAttrGrp) break; 00861 00862 // Save the reference to the attribute group. We'll fill it in later. 00863 FwdRefAttrGrps.push_back(AttrGrpNum); 00864 break; 00865 } 00866 // Target-dependent attributes: 00867 case lltok::StringConstant: { 00868 std::string Attr = Lex.getStrVal(); 00869 Lex.Lex(); 00870 std::string Val; 00871 if (EatIfPresent(lltok::equal) && 00872 ParseStringConstant(Val)) 00873 return true; 00874 00875 B.addAttribute(Attr, Val); 00876 continue; 00877 } 00878 00879 // Target-independent attributes: 00880 case lltok::kw_align: { 00881 // As a hack, we allow function alignment to be initially parsed as an 00882 // attribute on a function declaration/definition or added to an attribute 00883 // group and later moved to the alignment field. 00884 unsigned Alignment; 00885 if (inAttrGrp) { 00886 Lex.Lex(); 00887 if (ParseToken(lltok::equal, "expected '=' here") || 00888 ParseUInt32(Alignment)) 00889 return true; 00890 } else { 00891 if (ParseOptionalAlignment(Alignment)) 00892 return true; 00893 } 00894 B.addAlignmentAttr(Alignment); 00895 continue; 00896 } 00897 case lltok::kw_alignstack: { 00898 unsigned Alignment; 00899 if (inAttrGrp) { 00900 Lex.Lex(); 00901 if (ParseToken(lltok::equal, "expected '=' here") || 00902 ParseUInt32(Alignment)) 00903 return true; 00904 } else { 00905 if (ParseOptionalStackAlignment(Alignment)) 00906 return true; 00907 } 00908 B.addStackAlignmentAttr(Alignment); 00909 continue; 00910 } 00911 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break; 00912 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break; 00913 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break; 00914 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break; 00915 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break; 00916 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break; 00917 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break; 00918 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break; 00919 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break; 00920 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break; 00921 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break; 00922 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break; 00923 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break; 00924 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break; 00925 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break; 00926 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break; 00927 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break; 00928 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break; 00929 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break; 00930 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break; 00931 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break; 00932 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break; 00933 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break; 00934 00935 // Error handling. 00936 case lltok::kw_inreg: 00937 case lltok::kw_signext: 00938 case lltok::kw_zeroext: 00939 HaveError |= 00940 Error(Lex.getLoc(), 00941 "invalid use of attribute on a function"); 00942 break; 00943 case lltok::kw_byval: 00944 case lltok::kw_nest: 00945 case lltok::kw_noalias: 00946 case lltok::kw_nocapture: 00947 case lltok::kw_returned: 00948 case lltok::kw_sret: 00949 HaveError |= 00950 Error(Lex.getLoc(), 00951 "invalid use of parameter-only attribute on a function"); 00952 break; 00953 } 00954 00955 Lex.Lex(); 00956 } 00957 } 00958 00959 //===----------------------------------------------------------------------===// 00960 // GlobalValue Reference/Resolution Routines. 00961 //===----------------------------------------------------------------------===// 00962 00963 /// GetGlobalVal - Get a value with the specified name or ID, creating a 00964 /// forward reference record if needed. This can return null if the value 00965 /// exists but does not have the right type. 00966 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty, 00967 LocTy Loc) { 00968 PointerType *PTy = dyn_cast<PointerType>(Ty); 00969 if (PTy == 0) { 00970 Error(Loc, "global variable reference must have pointer type"); 00971 return 0; 00972 } 00973 00974 // Look this name up in the normal function symbol table. 00975 GlobalValue *Val = 00976 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name)); 00977 00978 // If this is a forward reference for the value, see if we already created a 00979 // forward ref record. 00980 if (Val == 0) { 00981 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator 00982 I = ForwardRefVals.find(Name); 00983 if (I != ForwardRefVals.end()) 00984 Val = I->second.first; 00985 } 00986 00987 // If we have the value in the symbol table or fwd-ref table, return it. 00988 if (Val) { 00989 if (Val->getType() == Ty) return Val; 00990 Error(Loc, "'@" + Name + "' defined with type '" + 00991 getTypeString(Val->getType()) + "'"); 00992 return 0; 00993 } 00994 00995 // Otherwise, create a new forward reference for this value and remember it. 00996 GlobalValue *FwdVal; 00997 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) 00998 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M); 00999 else 01000 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false, 01001 GlobalValue::ExternalWeakLinkage, 0, Name, 01002 0, GlobalVariable::NotThreadLocal, 01003 PTy->getAddressSpace()); 01004 01005 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 01006 return FwdVal; 01007 } 01008 01009 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) { 01010 PointerType *PTy = dyn_cast<PointerType>(Ty); 01011 if (PTy == 0) { 01012 Error(Loc, "global variable reference must have pointer type"); 01013 return 0; 01014 } 01015 01016 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0; 01017 01018 // If this is a forward reference for the value, see if we already created a 01019 // forward ref record. 01020 if (Val == 0) { 01021 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator 01022 I = ForwardRefValIDs.find(ID); 01023 if (I != ForwardRefValIDs.end()) 01024 Val = I->second.first; 01025 } 01026 01027 // If we have the value in the symbol table or fwd-ref table, return it. 01028 if (Val) { 01029 if (Val->getType() == Ty) return Val; 01030 Error(Loc, "'@" + Twine(ID) + "' defined with type '" + 01031 getTypeString(Val->getType()) + "'"); 01032 return 0; 01033 } 01034 01035 // Otherwise, create a new forward reference for this value and remember it. 01036 GlobalValue *FwdVal; 01037 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) 01038 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M); 01039 else 01040 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false, 01041 GlobalValue::ExternalWeakLinkage, 0, ""); 01042 01043 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 01044 return FwdVal; 01045 } 01046 01047 01048 //===----------------------------------------------------------------------===// 01049 // Helper Routines. 01050 //===----------------------------------------------------------------------===// 01051 01052 /// ParseToken - If the current token has the specified kind, eat it and return 01053 /// success. Otherwise, emit the specified error and return failure. 01054 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) { 01055 if (Lex.getKind() != T) 01056 return TokError(ErrMsg); 01057 Lex.Lex(); 01058 return false; 01059 } 01060 01061 /// ParseStringConstant 01062 /// ::= StringConstant 01063 bool LLParser::ParseStringConstant(std::string &Result) { 01064 if (Lex.getKind() != lltok::StringConstant) 01065 return TokError("expected string constant"); 01066 Result = Lex.getStrVal(); 01067 Lex.Lex(); 01068 return false; 01069 } 01070 01071 /// ParseUInt32 01072 /// ::= uint32 01073 bool LLParser::ParseUInt32(unsigned &Val) { 01074 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 01075 return TokError("expected integer"); 01076 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1); 01077 if (Val64 != unsigned(Val64)) 01078 return TokError("expected 32-bit integer (too large)"); 01079 Val = Val64; 01080 Lex.Lex(); 01081 return false; 01082 } 01083 01084 /// ParseTLSModel 01085 /// := 'localdynamic' 01086 /// := 'initialexec' 01087 /// := 'localexec' 01088 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) { 01089 switch (Lex.getKind()) { 01090 default: 01091 return TokError("expected localdynamic, initialexec or localexec"); 01092 case lltok::kw_localdynamic: 01093 TLM = GlobalVariable::LocalDynamicTLSModel; 01094 break; 01095 case lltok::kw_initialexec: 01096 TLM = GlobalVariable::InitialExecTLSModel; 01097 break; 01098 case lltok::kw_localexec: 01099 TLM = GlobalVariable::LocalExecTLSModel; 01100 break; 01101 } 01102 01103 Lex.Lex(); 01104 return false; 01105 } 01106 01107 /// ParseOptionalThreadLocal 01108 /// := /*empty*/ 01109 /// := 'thread_local' 01110 /// := 'thread_local' '(' tlsmodel ')' 01111 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) { 01112 TLM = GlobalVariable::NotThreadLocal; 01113 if (!EatIfPresent(lltok::kw_thread_local)) 01114 return false; 01115 01116 TLM = GlobalVariable::GeneralDynamicTLSModel; 01117 if (Lex.getKind() == lltok::lparen) { 01118 Lex.Lex(); 01119 return ParseTLSModel(TLM) || 01120 ParseToken(lltok::rparen, "expected ')' after thread local model"); 01121 } 01122 return false; 01123 } 01124 01125 /// ParseOptionalAddrSpace 01126 /// := /*empty*/ 01127 /// := 'addrspace' '(' uint32 ')' 01128 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) { 01129 AddrSpace = 0; 01130 if (!EatIfPresent(lltok::kw_addrspace)) 01131 return false; 01132 return ParseToken(lltok::lparen, "expected '(' in address space") || 01133 ParseUInt32(AddrSpace) || 01134 ParseToken(lltok::rparen, "expected ')' in address space"); 01135 } 01136 01137 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes. 01138 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) { 01139 bool HaveError = false; 01140 01141 B.clear(); 01142 01143 while (1) { 01144 lltok::Kind Token = Lex.getKind(); 01145 switch (Token) { 01146 default: // End of attributes. 01147 return HaveError; 01148 case lltok::kw_align: { 01149 unsigned Alignment; 01150 if (ParseOptionalAlignment(Alignment)) 01151 return true; 01152 B.addAlignmentAttr(Alignment); 01153 continue; 01154 } 01155 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break; 01156 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break; 01157 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break; 01158 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break; 01159 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break; 01160 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break; 01161 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break; 01162 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break; 01163 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break; 01164 01165 case lltok::kw_alignstack: 01166 case lltok::kw_alwaysinline: 01167 case lltok::kw_inlinehint: 01168 case lltok::kw_minsize: 01169 case lltok::kw_naked: 01170 case lltok::kw_nobuiltin: 01171 case lltok::kw_noduplicate: 01172 case lltok::kw_noimplicitfloat: 01173 case lltok::kw_noinline: 01174 case lltok::kw_nonlazybind: 01175 case lltok::kw_noredzone: 01176 case lltok::kw_noreturn: 01177 case lltok::kw_nounwind: 01178 case lltok::kw_optsize: 01179 case lltok::kw_readnone: 01180 case lltok::kw_readonly: 01181 case lltok::kw_returns_twice: 01182 case lltok::kw_sanitize_address: 01183 case lltok::kw_sanitize_memory: 01184 case lltok::kw_sanitize_thread: 01185 case lltok::kw_ssp: 01186 case lltok::kw_sspreq: 01187 case lltok::kw_sspstrong: 01188 case lltok::kw_uwtable: 01189 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute"); 01190 break; 01191 } 01192 01193 Lex.Lex(); 01194 } 01195 } 01196 01197 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes. 01198 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) { 01199 bool HaveError = false; 01200 01201 B.clear(); 01202 01203 while (1) { 01204 lltok::Kind Token = Lex.getKind(); 01205 switch (Token) { 01206 default: // End of attributes. 01207 return HaveError; 01208 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break; 01209 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break; 01210 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break; 01211 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break; 01212 01213 // Error handling. 01214 case lltok::kw_align: 01215 case lltok::kw_byval: 01216 case lltok::kw_nest: 01217 case lltok::kw_nocapture: 01218 case lltok::kw_returned: 01219 case lltok::kw_sret: 01220 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute"); 01221 break; 01222 01223 case lltok::kw_alignstack: 01224 case lltok::kw_alwaysinline: 01225 case lltok::kw_inlinehint: 01226 case lltok::kw_minsize: 01227 case lltok::kw_naked: 01228 case lltok::kw_nobuiltin: 01229 case lltok::kw_noduplicate: 01230 case lltok::kw_noimplicitfloat: 01231 case lltok::kw_noinline: 01232 case lltok::kw_nonlazybind: 01233 case lltok::kw_noredzone: 01234 case lltok::kw_noreturn: 01235 case lltok::kw_nounwind: 01236 case lltok::kw_optsize: 01237 case lltok::kw_readnone: 01238 case lltok::kw_readonly: 01239 case lltok::kw_returns_twice: 01240 case lltok::kw_sanitize_address: 01241 case lltok::kw_sanitize_memory: 01242 case lltok::kw_sanitize_thread: 01243 case lltok::kw_ssp: 01244 case lltok::kw_sspreq: 01245 case lltok::kw_sspstrong: 01246 case lltok::kw_uwtable: 01247 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute"); 01248 break; 01249 } 01250 01251 Lex.Lex(); 01252 } 01253 } 01254 01255 /// ParseOptionalLinkage 01256 /// ::= /*empty*/ 01257 /// ::= 'private' 01258 /// ::= 'linker_private' 01259 /// ::= 'linker_private_weak' 01260 /// ::= 'internal' 01261 /// ::= 'weak' 01262 /// ::= 'weak_odr' 01263 /// ::= 'linkonce' 01264 /// ::= 'linkonce_odr' 01265 /// ::= 'linkonce_odr_auto_hide' 01266 /// ::= 'available_externally' 01267 /// ::= 'appending' 01268 /// ::= 'dllexport' 01269 /// ::= 'common' 01270 /// ::= 'dllimport' 01271 /// ::= 'extern_weak' 01272 /// ::= 'external' 01273 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) { 01274 HasLinkage = false; 01275 switch (Lex.getKind()) { 01276 default: Res=GlobalValue::ExternalLinkage; return false; 01277 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break; 01278 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break; 01279 case lltok::kw_linker_private_weak: 01280 Res = GlobalValue::LinkerPrivateWeakLinkage; 01281 break; 01282 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break; 01283 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break; 01284 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break; 01285 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break; 01286 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break; 01287 case lltok::kw_linkonce_odr_auto_hide: 01288 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat. 01289 Res = GlobalValue::LinkOnceODRAutoHideLinkage; 01290 break; 01291 case lltok::kw_available_externally: 01292 Res = GlobalValue::AvailableExternallyLinkage; 01293 break; 01294 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break; 01295 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break; 01296 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break; 01297 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break; 01298 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break; 01299 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break; 01300 } 01301 Lex.Lex(); 01302 HasLinkage = true; 01303 return false; 01304 } 01305 01306 /// ParseOptionalVisibility 01307 /// ::= /*empty*/ 01308 /// ::= 'default' 01309 /// ::= 'hidden' 01310 /// ::= 'protected' 01311 /// 01312 bool LLParser::ParseOptionalVisibility(unsigned &Res) { 01313 switch (Lex.getKind()) { 01314 default: Res = GlobalValue::DefaultVisibility; return false; 01315 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break; 01316 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break; 01317 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break; 01318 } 01319 Lex.Lex(); 01320 return false; 01321 } 01322 01323 /// ParseOptionalCallingConv 01324 /// ::= /*empty*/ 01325 /// ::= 'ccc' 01326 /// ::= 'fastcc' 01327 /// ::= 'kw_intel_ocl_bicc' 01328 /// ::= 'coldcc' 01329 /// ::= 'x86_stdcallcc' 01330 /// ::= 'x86_fastcallcc' 01331 /// ::= 'x86_thiscallcc' 01332 /// ::= 'arm_apcscc' 01333 /// ::= 'arm_aapcscc' 01334 /// ::= 'arm_aapcs_vfpcc' 01335 /// ::= 'msp430_intrcc' 01336 /// ::= 'ptx_kernel' 01337 /// ::= 'ptx_device' 01338 /// ::= 'spir_func' 01339 /// ::= 'spir_kernel' 01340 /// ::= 'cc' UINT 01341 /// 01342 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) { 01343 switch (Lex.getKind()) { 01344 default: CC = CallingConv::C; return false; 01345 case lltok::kw_ccc: CC = CallingConv::C; break; 01346 case lltok::kw_fastcc: CC = CallingConv::Fast; break; 01347 case lltok::kw_coldcc: CC = CallingConv::Cold; break; 01348 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break; 01349 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break; 01350 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break; 01351 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break; 01352 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break; 01353 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break; 01354 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break; 01355 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break; 01356 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break; 01357 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break; 01358 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break; 01359 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break; 01360 case lltok::kw_cc: { 01361 unsigned ArbitraryCC; 01362 Lex.Lex(); 01363 if (ParseUInt32(ArbitraryCC)) 01364 return true; 01365 CC = static_cast<CallingConv::ID>(ArbitraryCC); 01366 return false; 01367 } 01368 } 01369 01370 Lex.Lex(); 01371 return false; 01372 } 01373 01374 /// ParseInstructionMetadata 01375 /// ::= !dbg !42 (',' !dbg !57)* 01376 bool LLParser::ParseInstructionMetadata(Instruction *Inst, 01377 PerFunctionState *PFS) { 01378 do { 01379 if (Lex.getKind() != lltok::MetadataVar) 01380 return TokError("expected metadata after comma"); 01381 01382 std::string Name = Lex.getStrVal(); 01383 unsigned MDK = M->getMDKindID(Name); 01384 Lex.Lex(); 01385 01386 MDNode *Node; 01387 SMLoc Loc = Lex.getLoc(); 01388 01389 if (ParseToken(lltok::exclaim, "expected '!' here")) 01390 return true; 01391 01392 // This code is similar to that of ParseMetadataValue, however it needs to 01393 // have special-case code for a forward reference; see the comments on 01394 // ForwardRefInstMetadata for details. Also, MDStrings are not supported 01395 // at the top level here. 01396 if (Lex.getKind() == lltok::lbrace) { 01397 ValID ID; 01398 if (ParseMetadataListValue(ID, PFS)) 01399 return true; 01400 assert(ID.Kind == ValID::t_MDNode); 01401 Inst->setMetadata(MDK, ID.MDNodeVal); 01402 } else { 01403 unsigned NodeID = 0; 01404 if (ParseMDNodeID(Node, NodeID)) 01405 return true; 01406 if (Node) { 01407 // If we got the node, add it to the instruction. 01408 Inst->setMetadata(MDK, Node); 01409 } else { 01410 MDRef R = { Loc, MDK, NodeID }; 01411 // Otherwise, remember that this should be resolved later. 01412 ForwardRefInstMetadata[Inst].push_back(R); 01413 } 01414 } 01415 01416 // If this is the end of the list, we're done. 01417 } while (EatIfPresent(lltok::comma)); 01418 return false; 01419 } 01420 01421 /// ParseOptionalAlignment 01422 /// ::= /* empty */ 01423 /// ::= 'align' 4 01424 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) { 01425 Alignment = 0; 01426 if (!EatIfPresent(lltok::kw_align)) 01427 return false; 01428 LocTy AlignLoc = Lex.getLoc(); 01429 if (ParseUInt32(Alignment)) return true; 01430 if (!isPowerOf2_32(Alignment)) 01431 return Error(AlignLoc, "alignment is not a power of two"); 01432 if (Alignment > Value::MaximumAlignment) 01433 return Error(AlignLoc, "huge alignments are not supported yet"); 01434 return false; 01435 } 01436 01437 /// ParseOptionalCommaAlign 01438 /// ::= 01439 /// ::= ',' align 4 01440 /// 01441 /// This returns with AteExtraComma set to true if it ate an excess comma at the 01442 /// end. 01443 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment, 01444 bool &AteExtraComma) { 01445 AteExtraComma = false; 01446 while (EatIfPresent(lltok::comma)) { 01447 // Metadata at the end is an early exit. 01448 if (Lex.getKind() == lltok::MetadataVar) { 01449 AteExtraComma = true; 01450 return false; 01451 } 01452 01453 if (Lex.getKind() != lltok::kw_align) 01454 return Error(Lex.getLoc(), "expected metadata or 'align'"); 01455 01456 if (ParseOptionalAlignment(Alignment)) return true; 01457 } 01458 01459 return false; 01460 } 01461 01462 /// ParseScopeAndOrdering 01463 /// if isAtomic: ::= 'singlethread'? AtomicOrdering 01464 /// else: ::= 01465 /// 01466 /// This sets Scope and Ordering to the parsed values. 01467 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope, 01468 AtomicOrdering &Ordering) { 01469 if (!isAtomic) 01470 return false; 01471 01472 Scope = CrossThread; 01473 if (EatIfPresent(lltok::kw_singlethread)) 01474 Scope = SingleThread; 01475 switch (Lex.getKind()) { 01476 default: return TokError("Expected ordering on atomic instruction"); 01477 case lltok::kw_unordered: Ordering = Unordered; break; 01478 case lltok::kw_monotonic: Ordering = Monotonic; break; 01479 case lltok::kw_acquire: Ordering = Acquire; break; 01480 case lltok::kw_release: Ordering = Release; break; 01481 case lltok::kw_acq_rel: Ordering = AcquireRelease; break; 01482 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break; 01483 } 01484 Lex.Lex(); 01485 return false; 01486 } 01487 01488 /// ParseOptionalStackAlignment 01489 /// ::= /* empty */ 01490 /// ::= 'alignstack' '(' 4 ')' 01491 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) { 01492 Alignment = 0; 01493 if (!EatIfPresent(lltok::kw_alignstack)) 01494 return false; 01495 LocTy ParenLoc = Lex.getLoc(); 01496 if (!EatIfPresent(lltok::lparen)) 01497 return Error(ParenLoc, "expected '('"); 01498 LocTy AlignLoc = Lex.getLoc(); 01499 if (ParseUInt32(Alignment)) return true; 01500 ParenLoc = Lex.getLoc(); 01501 if (!EatIfPresent(lltok::rparen)) 01502 return Error(ParenLoc, "expected ')'"); 01503 if (!isPowerOf2_32(Alignment)) 01504 return Error(AlignLoc, "stack alignment is not a power of two"); 01505 return false; 01506 } 01507 01508 /// ParseIndexList - This parses the index list for an insert/extractvalue 01509 /// instruction. This sets AteExtraComma in the case where we eat an extra 01510 /// comma at the end of the line and find that it is followed by metadata. 01511 /// Clients that don't allow metadata can call the version of this function that 01512 /// only takes one argument. 01513 /// 01514 /// ParseIndexList 01515 /// ::= (',' uint32)+ 01516 /// 01517 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices, 01518 bool &AteExtraComma) { 01519 AteExtraComma = false; 01520 01521 if (Lex.getKind() != lltok::comma) 01522 return TokError("expected ',' as start of index list"); 01523 01524 while (EatIfPresent(lltok::comma)) { 01525 if (Lex.getKind() == lltok::MetadataVar) { 01526 AteExtraComma = true; 01527 return false; 01528 } 01529 unsigned Idx = 0; 01530 if (ParseUInt32(Idx)) return true; 01531 Indices.push_back(Idx); 01532 } 01533 01534 return false; 01535 } 01536 01537 //===----------------------------------------------------------------------===// 01538 // Type Parsing. 01539 //===----------------------------------------------------------------------===// 01540 01541 /// ParseType - Parse a type. 01542 bool LLParser::ParseType(Type *&Result, bool AllowVoid) { 01543 SMLoc TypeLoc = Lex.getLoc(); 01544 switch (Lex.getKind()) { 01545 default: 01546 return TokError("expected type"); 01547 case lltok::Type: 01548 // Type ::= 'float' | 'void' (etc) 01549 Result = Lex.getTyVal(); 01550 Lex.Lex(); 01551 break; 01552 case lltok::lbrace: 01553 // Type ::= StructType 01554 if (ParseAnonStructType(Result, false)) 01555 return true; 01556 break; 01557 case lltok::lsquare: 01558 // Type ::= '[' ... ']' 01559 Lex.Lex(); // eat the lsquare. 01560 if (ParseArrayVectorType(Result, false)) 01561 return true; 01562 break; 01563 case lltok::less: // Either vector or packed struct. 01564 // Type ::= '<' ... '>' 01565 Lex.Lex(); 01566 if (Lex.getKind() == lltok::lbrace) { 01567 if (ParseAnonStructType(Result, true) || 01568 ParseToken(lltok::greater, "expected '>' at end of packed struct")) 01569 return true; 01570 } else if (ParseArrayVectorType(Result, true)) 01571 return true; 01572 break; 01573 case lltok::LocalVar: { 01574 // Type ::= %foo 01575 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()]; 01576 01577 // If the type hasn't been defined yet, create a forward definition and 01578 // remember where that forward def'n was seen (in case it never is defined). 01579 if (Entry.first == 0) { 01580 Entry.first = StructType::create(Context, Lex.getStrVal()); 01581 Entry.second = Lex.getLoc(); 01582 } 01583 Result = Entry.first; 01584 Lex.Lex(); 01585 break; 01586 } 01587 01588 case lltok::LocalVarID: { 01589 // Type ::= %4 01590 if (Lex.getUIntVal() >= NumberedTypes.size()) 01591 NumberedTypes.resize(Lex.getUIntVal()+1); 01592 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()]; 01593 01594 // If the type hasn't been defined yet, create a forward definition and 01595 // remember where that forward def'n was seen (in case it never is defined). 01596 if (Entry.first == 0) { 01597 Entry.first = StructType::create(Context); 01598 Entry.second = Lex.getLoc(); 01599 } 01600 Result = Entry.first; 01601 Lex.Lex(); 01602 break; 01603 } 01604 } 01605 01606 // Parse the type suffixes. 01607 while (1) { 01608 switch (Lex.getKind()) { 01609 // End of type. 01610 default: 01611 if (!AllowVoid && Result->isVoidTy()) 01612 return Error(TypeLoc, "void type only allowed for function results"); 01613 return false; 01614 01615 // Type ::= Type '*' 01616 case lltok::star: 01617 if (Result->isLabelTy()) 01618 return TokError("basic block pointers are invalid"); 01619 if (Result->isVoidTy()) 01620 return TokError("pointers to void are invalid - use i8* instead"); 01621 if (!PointerType::isValidElementType(Result)) 01622 return TokError("pointer to this type is invalid"); 01623 Result = PointerType::getUnqual(Result); 01624 Lex.Lex(); 01625 break; 01626 01627 // Type ::= Type 'addrspace' '(' uint32 ')' '*' 01628 case lltok::kw_addrspace: { 01629 if (Result->isLabelTy()) 01630 return TokError("basic block pointers are invalid"); 01631 if (Result->isVoidTy()) 01632 return TokError("pointers to void are invalid; use i8* instead"); 01633 if (!PointerType::isValidElementType(Result)) 01634 return TokError("pointer to this type is invalid"); 01635 unsigned AddrSpace; 01636 if (ParseOptionalAddrSpace(AddrSpace) || 01637 ParseToken(lltok::star, "expected '*' in address space")) 01638 return true; 01639 01640 Result = PointerType::get(Result, AddrSpace); 01641 break; 01642 } 01643 01644 /// Types '(' ArgTypeListI ')' OptFuncAttrs 01645 case lltok::lparen: 01646 if (ParseFunctionType(Result)) 01647 return true; 01648 break; 01649 } 01650 } 01651 } 01652 01653 /// ParseParameterList 01654 /// ::= '(' ')' 01655 /// ::= '(' Arg (',' Arg)* ')' 01656 /// Arg 01657 /// ::= Type OptionalAttributes Value OptionalAttributes 01658 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList, 01659 PerFunctionState &PFS) { 01660 if (ParseToken(lltok::lparen, "expected '(' in call")) 01661 return true; 01662 01663 unsigned AttrIndex = 1; 01664 while (Lex.getKind() != lltok::rparen) { 01665 // If this isn't the first argument, we need a comma. 01666 if (!ArgList.empty() && 01667 ParseToken(lltok::comma, "expected ',' in argument list")) 01668 return true; 01669 01670 // Parse the argument. 01671 LocTy ArgLoc; 01672 Type *ArgTy = 0; 01673 AttrBuilder ArgAttrs; 01674 Value *V; 01675 if (ParseType(ArgTy, ArgLoc)) 01676 return true; 01677 01678 // Otherwise, handle normal operands. 01679 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS)) 01680 return true; 01681 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(), 01682 AttrIndex++, 01683 ArgAttrs))); 01684 } 01685 01686 Lex.Lex(); // Lex the ')'. 01687 return false; 01688 } 01689 01690 01691 01692 /// ParseArgumentList - Parse the argument list for a function type or function 01693 /// prototype. 01694 /// ::= '(' ArgTypeListI ')' 01695 /// ArgTypeListI 01696 /// ::= /*empty*/ 01697 /// ::= '...' 01698 /// ::= ArgTypeList ',' '...' 01699 /// ::= ArgType (',' ArgType)* 01700 /// 01701 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, 01702 bool &isVarArg){ 01703 isVarArg = false; 01704 assert(Lex.getKind() == lltok::lparen); 01705 Lex.Lex(); // eat the (. 01706 01707 if (Lex.getKind() == lltok::rparen) { 01708 // empty 01709 } else if (Lex.getKind() == lltok::dotdotdot) { 01710 isVarArg = true; 01711 Lex.Lex(); 01712 } else { 01713 LocTy TypeLoc = Lex.getLoc(); 01714 Type *ArgTy = 0; 01715 AttrBuilder Attrs; 01716 std::string Name; 01717 01718 if (ParseType(ArgTy) || 01719 ParseOptionalParamAttrs(Attrs)) return true; 01720 01721 if (ArgTy->isVoidTy()) 01722 return Error(TypeLoc, "argument can not have void type"); 01723 01724 if (Lex.getKind() == lltok::LocalVar) { 01725 Name = Lex.getStrVal(); 01726 Lex.Lex(); 01727 } 01728 01729 if (!FunctionType::isValidArgumentType(ArgTy)) 01730 return Error(TypeLoc, "invalid type for function argument"); 01731 01732 unsigned AttrIndex = 1; 01733 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, 01734 AttributeSet::get(ArgTy->getContext(), 01735 AttrIndex++, Attrs), Name)); 01736 01737 while (EatIfPresent(lltok::comma)) { 01738 // Handle ... at end of arg list. 01739 if (EatIfPresent(lltok::dotdotdot)) { 01740 isVarArg = true; 01741 break; 01742 } 01743 01744 // Otherwise must be an argument type. 01745 TypeLoc = Lex.getLoc(); 01746 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true; 01747 01748 if (ArgTy->isVoidTy()) 01749 return Error(TypeLoc, "argument can not have void type"); 01750 01751 if (Lex.getKind() == lltok::LocalVar) { 01752 Name = Lex.getStrVal(); 01753 Lex.Lex(); 01754 } else { 01755 Name = ""; 01756 } 01757 01758 if (!ArgTy->isFirstClassType()) 01759 return Error(TypeLoc, "invalid type for function argument"); 01760 01761 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, 01762 AttributeSet::get(ArgTy->getContext(), 01763 AttrIndex++, Attrs), 01764 Name)); 01765 } 01766 } 01767 01768 return ParseToken(lltok::rparen, "expected ')' at end of argument list"); 01769 } 01770 01771 /// ParseFunctionType 01772 /// ::= Type ArgumentList OptionalAttrs 01773 bool LLParser::ParseFunctionType(Type *&Result) { 01774 assert(Lex.getKind() == lltok::lparen); 01775 01776 if (!FunctionType::isValidReturnType(Result)) 01777 return TokError("invalid function return type"); 01778 01779 SmallVector<ArgInfo, 8> ArgList; 01780 bool isVarArg; 01781 if (ParseArgumentList(ArgList, isVarArg)) 01782 return true; 01783 01784 // Reject names on the arguments lists. 01785 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 01786 if (!ArgList[i].Name.empty()) 01787 return Error(ArgList[i].Loc, "argument name invalid in function type"); 01788 if (ArgList[i].Attrs.hasAttributes(i + 1)) 01789 return Error(ArgList[i].Loc, 01790 "argument attributes invalid in function type"); 01791 } 01792 01793 SmallVector<Type*, 16> ArgListTy; 01794 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 01795 ArgListTy.push_back(ArgList[i].Ty); 01796 01797 Result = FunctionType::get(Result, ArgListTy, isVarArg); 01798 return false; 01799 } 01800 01801 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into 01802 /// other structs. 01803 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) { 01804 SmallVector<Type*, 8> Elts; 01805 if (ParseStructBody(Elts)) return true; 01806 01807 Result = StructType::get(Context, Elts, Packed); 01808 return false; 01809 } 01810 01811 /// ParseStructDefinition - Parse a struct in a 'type' definition. 01812 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name, 01813 std::pair<Type*, LocTy> &Entry, 01814 Type *&ResultTy) { 01815 // If the type was already defined, diagnose the redefinition. 01816 if (Entry.first && !Entry.second.isValid()) 01817 return Error(TypeLoc, "redefinition of type"); 01818 01819 // If we have opaque, just return without filling in the definition for the 01820 // struct. This counts as a definition as far as the .ll file goes. 01821 if (EatIfPresent(lltok::kw_opaque)) { 01822 // This type is being defined, so clear the location to indicate this. 01823 Entry.second = SMLoc(); 01824 01825 // If this type number has never been uttered, create it. 01826 if (Entry.first == 0) 01827 Entry.first = StructType::create(Context, Name); 01828 ResultTy = Entry.first; 01829 return false; 01830 } 01831 01832 // If the type starts with '<', then it is either a packed struct or a vector. 01833 bool isPacked = EatIfPresent(lltok::less); 01834 01835 // If we don't have a struct, then we have a random type alias, which we 01836 // accept for compatibility with old files. These types are not allowed to be 01837 // forward referenced and not allowed to be recursive. 01838 if (Lex.getKind() != lltok::lbrace) { 01839 if (Entry.first) 01840 return Error(TypeLoc, "forward references to non-struct type"); 01841 01842 ResultTy = 0; 01843 if (isPacked) 01844 return ParseArrayVectorType(ResultTy, true); 01845 return ParseType(ResultTy); 01846 } 01847 01848 // This type is being defined, so clear the location to indicate this. 01849 Entry.second = SMLoc(); 01850 01851 // If this type number has never been uttered, create it. 01852 if (Entry.first == 0) 01853 Entry.first = StructType::create(Context, Name); 01854 01855 StructType *STy = cast<StructType>(Entry.first); 01856 01857 SmallVector<Type*, 8> Body; 01858 if (ParseStructBody(Body) || 01859 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct"))) 01860 return true; 01861 01862 STy->setBody(Body, isPacked); 01863 ResultTy = STy; 01864 return false; 01865 } 01866 01867 01868 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere. 01869 /// StructType 01870 /// ::= '{' '}' 01871 /// ::= '{' Type (',' Type)* '}' 01872 /// ::= '<' '{' '}' '>' 01873 /// ::= '<' '{' Type (',' Type)* '}' '>' 01874 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) { 01875 assert(Lex.getKind() == lltok::lbrace); 01876 Lex.Lex(); // Consume the '{' 01877 01878 // Handle the empty struct. 01879 if (EatIfPresent(lltok::rbrace)) 01880 return false; 01881 01882 LocTy EltTyLoc = Lex.getLoc(); 01883 Type *Ty = 0; 01884 if (ParseType(Ty)) return true; 01885 Body.push_back(Ty); 01886 01887 if (!StructType::isValidElementType(Ty)) 01888 return Error(EltTyLoc, "invalid element type for struct"); 01889 01890 while (EatIfPresent(lltok::comma)) { 01891 EltTyLoc = Lex.getLoc(); 01892 if (ParseType(Ty)) return true; 01893 01894 if (!StructType::isValidElementType(Ty)) 01895 return Error(EltTyLoc, "invalid element type for struct"); 01896 01897 Body.push_back(Ty); 01898 } 01899 01900 return ParseToken(lltok::rbrace, "expected '}' at end of struct"); 01901 } 01902 01903 /// ParseArrayVectorType - Parse an array or vector type, assuming the first 01904 /// token has already been consumed. 01905 /// Type 01906 /// ::= '[' APSINTVAL 'x' Types ']' 01907 /// ::= '<' APSINTVAL 'x' Types '>' 01908 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) { 01909 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() || 01910 Lex.getAPSIntVal().getBitWidth() > 64) 01911 return TokError("expected number in address space"); 01912 01913 LocTy SizeLoc = Lex.getLoc(); 01914 uint64_t Size = Lex.getAPSIntVal().getZExtValue(); 01915 Lex.Lex(); 01916 01917 if (ParseToken(lltok::kw_x, "expected 'x' after element count")) 01918 return true; 01919 01920 LocTy TypeLoc = Lex.getLoc(); 01921 Type *EltTy = 0; 01922 if (ParseType(EltTy)) return true; 01923 01924 if (ParseToken(isVector ? lltok::greater : lltok::rsquare, 01925 "expected end of sequential type")) 01926 return true; 01927 01928 if (isVector) { 01929 if (Size == 0) 01930 return Error(SizeLoc, "zero element vector is illegal"); 01931 if ((unsigned)Size != Size) 01932 return Error(SizeLoc, "size too large for vector"); 01933 if (!VectorType::isValidElementType(EltTy)) 01934 return Error(TypeLoc, "invalid vector element type"); 01935 Result = VectorType::get(EltTy, unsigned(Size)); 01936 } else { 01937 if (!ArrayType::isValidElementType(EltTy)) 01938 return Error(TypeLoc, "invalid array element type"); 01939 Result = ArrayType::get(EltTy, Size); 01940 } 01941 return false; 01942 } 01943 01944 //===----------------------------------------------------------------------===// 01945 // Function Semantic Analysis. 01946 //===----------------------------------------------------------------------===// 01947 01948 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f, 01949 int functionNumber) 01950 : P(p), F(f), FunctionNumber(functionNumber) { 01951 01952 // Insert unnamed arguments into the NumberedVals list. 01953 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); 01954 AI != E; ++AI) 01955 if (!AI->hasName()) 01956 NumberedVals.push_back(AI); 01957 } 01958 01959 LLParser::PerFunctionState::~PerFunctionState() { 01960 // If there were any forward referenced non-basicblock values, delete them. 01961 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator 01962 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I) 01963 if (!isa<BasicBlock>(I->second.first)) { 01964 I->second.first->replaceAllUsesWith( 01965 UndefValue::get(I->second.first->getType())); 01966 delete I->second.first; 01967 I->second.first = 0; 01968 } 01969 01970 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator 01971 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I) 01972 if (!isa<BasicBlock>(I->second.first)) { 01973 I->second.first->replaceAllUsesWith( 01974 UndefValue::get(I->second.first->getType())); 01975 delete I->second.first; 01976 I->second.first = 0; 01977 } 01978 } 01979 01980 bool LLParser::PerFunctionState::FinishFunction() { 01981 // Check to see if someone took the address of labels in this block. 01982 if (!P.ForwardRefBlockAddresses.empty()) { 01983 ValID FunctionID; 01984 if (!F.getName().empty()) { 01985 FunctionID.Kind = ValID::t_GlobalName; 01986 FunctionID.StrVal = F.getName(); 01987 } else { 01988 FunctionID.Kind = ValID::t_GlobalID; 01989 FunctionID.UIntVal = FunctionNumber; 01990 } 01991 01992 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator 01993 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID); 01994 if (FRBAI != P.ForwardRefBlockAddresses.end()) { 01995 // Resolve all these references. 01996 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this)) 01997 return true; 01998 01999 P.ForwardRefBlockAddresses.erase(FRBAI); 02000 } 02001 } 02002 02003 if (!ForwardRefVals.empty()) 02004 return P.Error(ForwardRefVals.begin()->second.second, 02005 "use of undefined value '%" + ForwardRefVals.begin()->first + 02006 "'"); 02007 if (!ForwardRefValIDs.empty()) 02008 return P.Error(ForwardRefValIDs.begin()->second.second, 02009 "use of undefined value '%" + 02010 Twine(ForwardRefValIDs.begin()->first) + "'"); 02011 return false; 02012 } 02013 02014 02015 /// GetVal - Get a value with the specified name or ID, creating a 02016 /// forward reference record if needed. This can return null if the value 02017 /// exists but does not have the right type. 02018 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, 02019 Type *Ty, LocTy Loc) { 02020 // Look this name up in the normal function symbol table. 02021 Value *Val = F.getValueSymbolTable().lookup(Name); 02022 02023 // If this is a forward reference for the value, see if we already created a 02024 // forward ref record. 02025 if (Val == 0) { 02026 std::map<std::string, std::pair<Value*, LocTy> >::iterator 02027 I = ForwardRefVals.find(Name); 02028 if (I != ForwardRefVals.end()) 02029 Val = I->second.first; 02030 } 02031 02032 // If we have the value in the symbol table or fwd-ref table, return it. 02033 if (Val) { 02034 if (Val->getType() == Ty) return Val; 02035 if (Ty->isLabelTy()) 02036 P.Error(Loc, "'%" + Name + "' is not a basic block"); 02037 else 02038 P.Error(Loc, "'%" + Name + "' defined with type '" + 02039 getTypeString(Val->getType()) + "'"); 02040 return 0; 02041 } 02042 02043 // Don't make placeholders with invalid type. 02044 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) { 02045 P.Error(Loc, "invalid use of a non-first-class type"); 02046 return 0; 02047 } 02048 02049 // Otherwise, create a new forward reference for this value and remember it. 02050 Value *FwdVal; 02051 if (Ty->isLabelTy()) 02052 FwdVal = BasicBlock::Create(F.getContext(), Name, &F); 02053 else 02054 FwdVal = new Argument(Ty, Name); 02055 02056 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 02057 return FwdVal; 02058 } 02059 02060 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, 02061 LocTy Loc) { 02062 // Look this name up in the normal function symbol table. 02063 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0; 02064 02065 // If this is a forward reference for the value, see if we already created a 02066 // forward ref record. 02067 if (Val == 0) { 02068 std::map<unsigned, std::pair<Value*, LocTy> >::iterator 02069 I = ForwardRefValIDs.find(ID); 02070 if (I != ForwardRefValIDs.end()) 02071 Val = I->second.first; 02072 } 02073 02074 // If we have the value in the symbol table or fwd-ref table, return it. 02075 if (Val) { 02076 if (Val->getType() == Ty) return Val; 02077 if (Ty->isLabelTy()) 02078 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block"); 02079 else 02080 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" + 02081 getTypeString(Val->getType()) + "'"); 02082 return 0; 02083 } 02084 02085 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) { 02086 P.Error(Loc, "invalid use of a non-first-class type"); 02087 return 0; 02088 } 02089 02090 // Otherwise, create a new forward reference for this value and remember it. 02091 Value *FwdVal; 02092 if (Ty->isLabelTy()) 02093 FwdVal = BasicBlock::Create(F.getContext(), "", &F); 02094 else 02095 FwdVal = new Argument(Ty); 02096 02097 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 02098 return FwdVal; 02099 } 02100 02101 /// SetInstName - After an instruction is parsed and inserted into its 02102 /// basic block, this installs its name. 02103 bool LLParser::PerFunctionState::SetInstName(int NameID, 02104 const std::string &NameStr, 02105 LocTy NameLoc, Instruction *Inst) { 02106 // If this instruction has void type, it cannot have a name or ID specified. 02107 if (Inst->getType()->isVoidTy()) { 02108 if (NameID != -1 || !NameStr.empty()) 02109 return P.Error(NameLoc, "instructions returning void cannot have a name"); 02110 return false; 02111 } 02112 02113 // If this was a numbered instruction, verify that the instruction is the 02114 // expected value and resolve any forward references. 02115 if (NameStr.empty()) { 02116 // If neither a name nor an ID was specified, just use the next ID. 02117 if (NameID == -1) 02118 NameID = NumberedVals.size(); 02119 02120 if (unsigned(NameID) != NumberedVals.size()) 02121 return P.Error(NameLoc, "instruction expected to be numbered '%" + 02122 Twine(NumberedVals.size()) + "'"); 02123 02124 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI = 02125 ForwardRefValIDs.find(NameID); 02126 if (FI != ForwardRefValIDs.end()) { 02127 if (FI->second.first->getType() != Inst->getType()) 02128 return P.Error(NameLoc, "instruction forward referenced with type '" + 02129 getTypeString(FI->second.first->getType()) + "'"); 02130 FI->second.first->replaceAllUsesWith(Inst); 02131 delete FI->second.first; 02132 ForwardRefValIDs.erase(FI); 02133 } 02134 02135 NumberedVals.push_back(Inst); 02136 return false; 02137 } 02138 02139 // Otherwise, the instruction had a name. Resolve forward refs and set it. 02140 std::map<std::string, std::pair<Value*, LocTy> >::iterator 02141 FI = ForwardRefVals.find(NameStr); 02142 if (FI != ForwardRefVals.end()) { 02143 if (FI->second.first->getType() != Inst->getType()) 02144 return P.Error(NameLoc, "instruction forward referenced with type '" + 02145 getTypeString(FI->second.first->getType()) + "'"); 02146 FI->second.first->replaceAllUsesWith(Inst); 02147 delete FI->second.first; 02148 ForwardRefVals.erase(FI); 02149 } 02150 02151 // Set the name on the instruction. 02152 Inst->setName(NameStr); 02153 02154 if (Inst->getName() != NameStr) 02155 return P.Error(NameLoc, "multiple definition of local value named '" + 02156 NameStr + "'"); 02157 return false; 02158 } 02159 02160 /// GetBB - Get a basic block with the specified name or ID, creating a 02161 /// forward reference record if needed. 02162 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name, 02163 LocTy Loc) { 02164 return cast_or_null<BasicBlock>(GetVal(Name, 02165 Type::getLabelTy(F.getContext()), Loc)); 02166 } 02167 02168 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) { 02169 return cast_or_null<BasicBlock>(GetVal(ID, 02170 Type::getLabelTy(F.getContext()), Loc)); 02171 } 02172 02173 /// DefineBB - Define the specified basic block, which is either named or 02174 /// unnamed. If there is an error, this returns null otherwise it returns 02175 /// the block being defined. 02176 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name, 02177 LocTy Loc) { 02178 BasicBlock *BB; 02179 if (Name.empty()) 02180 BB = GetBB(NumberedVals.size(), Loc); 02181 else 02182 BB = GetBB(Name, Loc); 02183 if (BB == 0) return 0; // Already diagnosed error. 02184 02185 // Move the block to the end of the function. Forward ref'd blocks are 02186 // inserted wherever they happen to be referenced. 02187 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB); 02188 02189 // Remove the block from forward ref sets. 02190 if (Name.empty()) { 02191 ForwardRefValIDs.erase(NumberedVals.size()); 02192 NumberedVals.push_back(BB); 02193 } else { 02194 // BB forward references are already in the function symbol table. 02195 ForwardRefVals.erase(Name); 02196 } 02197 02198 return BB; 02199 } 02200 02201 //===----------------------------------------------------------------------===// 02202 // Constants. 02203 //===----------------------------------------------------------------------===// 02204 02205 /// ParseValID - Parse an abstract value that doesn't necessarily have a 02206 /// type implied. For example, if we parse "4" we don't know what integer type 02207 /// it has. The value will later be combined with its type and checked for 02208 /// sanity. PFS is used to convert function-local operands of metadata (since 02209 /// metadata operands are not just parsed here but also converted to values). 02210 /// PFS can be null when we are not parsing metadata values inside a function. 02211 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) { 02212 ID.Loc = Lex.getLoc(); 02213 switch (Lex.getKind()) { 02214 default: return TokError("expected value token"); 02215 case lltok::GlobalID: // @42 02216 ID.UIntVal = Lex.getUIntVal(); 02217 ID.Kind = ValID::t_GlobalID; 02218 break; 02219 case lltok::GlobalVar: // @foo 02220 ID.StrVal = Lex.getStrVal(); 02221 ID.Kind = ValID::t_GlobalName; 02222 break; 02223 case lltok::LocalVarID: // %42 02224 ID.UIntVal = Lex.getUIntVal(); 02225 ID.Kind = ValID::t_LocalID; 02226 break; 02227 case lltok::LocalVar: // %foo 02228 ID.StrVal = Lex.getStrVal(); 02229 ID.Kind = ValID::t_LocalName; 02230 break; 02231 case lltok::exclaim: // !42, !{...}, or !"foo" 02232 return ParseMetadataValue(ID, PFS); 02233 case lltok::APSInt: 02234 ID.APSIntVal = Lex.getAPSIntVal(); 02235 ID.Kind = ValID::t_APSInt; 02236 break; 02237 case lltok::APFloat: 02238 ID.APFloatVal = Lex.getAPFloatVal(); 02239 ID.Kind = ValID::t_APFloat; 02240 break; 02241 case lltok::kw_true: 02242 ID.ConstantVal = ConstantInt::getTrue(Context); 02243 ID.Kind = ValID::t_Constant; 02244 break; 02245 case lltok::kw_false: 02246 ID.ConstantVal = ConstantInt::getFalse(Context); 02247 ID.Kind = ValID::t_Constant; 02248 break; 02249 case lltok::kw_null: ID.Kind = ValID::t_Null; break; 02250 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break; 02251 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break; 02252 02253 case lltok::lbrace: { 02254 // ValID ::= '{' ConstVector '}' 02255 Lex.Lex(); 02256 SmallVector<Constant*, 16> Elts; 02257 if (ParseGlobalValueVector(Elts) || 02258 ParseToken(lltok::rbrace, "expected end of struct constant")) 02259 return true; 02260 02261 ID.ConstantStructElts = new Constant*[Elts.size()]; 02262 ID.UIntVal = Elts.size(); 02263 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0])); 02264 ID.Kind = ValID::t_ConstantStruct; 02265 return false; 02266 } 02267 case lltok::less: { 02268 // ValID ::= '<' ConstVector '>' --> Vector. 02269 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct. 02270 Lex.Lex(); 02271 bool isPackedStruct = EatIfPresent(lltok::lbrace); 02272 02273 SmallVector<Constant*, 16> Elts; 02274 LocTy FirstEltLoc = Lex.getLoc(); 02275 if (ParseGlobalValueVector(Elts) || 02276 (isPackedStruct && 02277 ParseToken(lltok::rbrace, "expected end of packed struct")) || 02278 ParseToken(lltok::greater, "expected end of constant")) 02279 return true; 02280 02281 if (isPackedStruct) { 02282 ID.ConstantStructElts = new Constant*[Elts.size()]; 02283 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0])); 02284 ID.UIntVal = Elts.size(); 02285 ID.Kind = ValID::t_PackedConstantStruct; 02286 return false; 02287 } 02288 02289 if (Elts.empty()) 02290 return Error(ID.Loc, "constant vector must not be empty"); 02291 02292 if (!Elts[0]->getType()->isIntegerTy() && 02293 !Elts[0]->getType()->isFloatingPointTy() && 02294 !Elts[0]->getType()->isPointerTy()) 02295 return Error(FirstEltLoc, 02296 "vector elements must have integer, pointer or floating point type"); 02297 02298 // Verify that all the vector elements have the same type. 02299 for (unsigned i = 1, e = Elts.size(); i != e; ++i) 02300 if (Elts[i]->getType() != Elts[0]->getType()) 02301 return Error(FirstEltLoc, 02302 "vector element #" + Twine(i) + 02303 " is not of type '" + getTypeString(Elts[0]->getType())); 02304 02305 ID.ConstantVal = ConstantVector::get(Elts); 02306 ID.Kind = ValID::t_Constant; 02307 return false; 02308 } 02309 case lltok::lsquare: { // Array Constant 02310 Lex.Lex(); 02311 SmallVector<Constant*, 16> Elts; 02312 LocTy FirstEltLoc = Lex.getLoc(); 02313 if (ParseGlobalValueVector(Elts) || 02314 ParseToken(lltok::rsquare, "expected end of array constant")) 02315 return true; 02316 02317 // Handle empty element. 02318 if (Elts.empty()) { 02319 // Use undef instead of an array because it's inconvenient to determine 02320 // the element type at this point, there being no elements to examine. 02321 ID.Kind = ValID::t_EmptyArray; 02322 return false; 02323 } 02324 02325 if (!Elts[0]->getType()->isFirstClassType()) 02326 return Error(FirstEltLoc, "invalid array element type: " + 02327 getTypeString(Elts[0]->getType())); 02328 02329 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size()); 02330 02331 // Verify all elements are correct type! 02332 for (unsigned i = 0, e = Elts.size(); i != e; ++i) { 02333 if (Elts[i]->getType() != Elts[0]->getType()) 02334 return Error(FirstEltLoc, 02335 "array element #" + Twine(i) + 02336 " is not of type '" + getTypeString(Elts[0]->getType())); 02337 } 02338 02339 ID.ConstantVal = ConstantArray::get(ATy, Elts); 02340 ID.Kind = ValID::t_Constant; 02341 return false; 02342 } 02343 case lltok::kw_c: // c "foo" 02344 Lex.Lex(); 02345 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(), 02346 false); 02347 if (ParseToken(lltok::StringConstant, "expected string")) return true; 02348 ID.Kind = ValID::t_Constant; 02349 return false; 02350 02351 case lltok::kw_asm: { 02352 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ',' 02353 // STRINGCONSTANT 02354 bool HasSideEffect, AlignStack, AsmDialect; 02355 Lex.Lex(); 02356 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) || 02357 ParseOptionalToken(lltok::kw_alignstack, AlignStack) || 02358 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) || 02359 ParseStringConstant(ID.StrVal) || 02360 ParseToken(lltok::comma, "expected comma in inline asm expression") || 02361 ParseToken(lltok::StringConstant, "expected constraint string")) 02362 return true; 02363 ID.StrVal2 = Lex.getStrVal(); 02364 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) | 02365 (unsigned(AsmDialect)<<2); 02366 ID.Kind = ValID::t_InlineAsm; 02367 return false; 02368 } 02369 02370 case lltok::kw_blockaddress: { 02371 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')' 02372 Lex.Lex(); 02373 02374 ValID Fn, Label; 02375 LocTy FnLoc, LabelLoc; 02376 02377 if (ParseToken(lltok::lparen, "expected '(' in block address expression") || 02378 ParseValID(Fn) || 02379 ParseToken(lltok::comma, "expected comma in block address expression")|| 02380 ParseValID(Label) || 02381 ParseToken(lltok::rparen, "expected ')' in block address expression")) 02382 return true; 02383 02384 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName) 02385 return Error(Fn.Loc, "expected function name in blockaddress"); 02386 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName) 02387 return Error(Label.Loc, "expected basic block name in blockaddress"); 02388 02389 // Make a global variable as a placeholder for this reference. 02390 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), 02391 false, GlobalValue::InternalLinkage, 02392 0, ""); 02393 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef)); 02394 ID.ConstantVal = FwdRef; 02395 ID.Kind = ValID::t_Constant; 02396 return false; 02397 } 02398 02399 case lltok::kw_trunc: 02400 case lltok::kw_zext: 02401 case lltok::kw_sext: 02402 case lltok::kw_fptrunc: 02403 case lltok::kw_fpext: 02404 case lltok::kw_bitcast: 02405 case lltok::kw_uitofp: 02406 case lltok::kw_sitofp: 02407 case lltok::kw_fptoui: 02408 case lltok::kw_fptosi: 02409 case lltok::kw_inttoptr: 02410 case lltok::kw_ptrtoint: { 02411 unsigned Opc = Lex.getUIntVal(); 02412 Type *DestTy = 0; 02413 Constant *SrcVal; 02414 Lex.Lex(); 02415 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") || 02416 ParseGlobalTypeAndValue(SrcVal) || 02417 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") || 02418 ParseType(DestTy) || 02419 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast")) 02420 return true; 02421 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy)) 02422 return Error(ID.Loc, "invalid cast opcode for cast from '" + 02423 getTypeString(SrcVal->getType()) + "' to '" + 02424 getTypeString(DestTy) + "'"); 02425 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, 02426 SrcVal, DestTy); 02427 ID.Kind = ValID::t_Constant; 02428 return false; 02429 } 02430 case lltok::kw_extractvalue: { 02431 Lex.Lex(); 02432 Constant *Val; 02433 SmallVector<unsigned, 4> Indices; 02434 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")|| 02435 ParseGlobalTypeAndValue(Val) || 02436 ParseIndexList(Indices) || 02437 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr")) 02438 return true; 02439 02440 if (!Val->getType()->isAggregateType()) 02441 return Error(ID.Loc, "extractvalue operand must be aggregate type"); 02442 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 02443 return Error(ID.Loc, "invalid indices for extractvalue"); 02444 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices); 02445 ID.Kind = ValID::t_Constant; 02446 return false; 02447 } 02448 case lltok::kw_insertvalue: { 02449 Lex.Lex(); 02450 Constant *Val0, *Val1; 02451 SmallVector<unsigned, 4> Indices; 02452 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")|| 02453 ParseGlobalTypeAndValue(Val0) || 02454 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")|| 02455 ParseGlobalTypeAndValue(Val1) || 02456 ParseIndexList(Indices) || 02457 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr")) 02458 return true; 02459 if (!Val0->getType()->isAggregateType()) 02460 return Error(ID.Loc, "insertvalue operand must be aggregate type"); 02461 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices)) 02462 return Error(ID.Loc, "invalid indices for insertvalue"); 02463 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices); 02464 ID.Kind = ValID::t_Constant; 02465 return false; 02466 } 02467 case lltok::kw_icmp: 02468 case lltok::kw_fcmp: { 02469 unsigned PredVal, Opc = Lex.getUIntVal(); 02470 Constant *Val0, *Val1; 02471 Lex.Lex(); 02472 if (ParseCmpPredicate(PredVal, Opc) || 02473 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") || 02474 ParseGlobalTypeAndValue(Val0) || 02475 ParseToken(lltok::comma, "expected comma in compare constantexpr") || 02476 ParseGlobalTypeAndValue(Val1) || 02477 ParseToken(lltok::rparen, "expected ')' in compare constantexpr")) 02478 return true; 02479 02480 if (Val0->getType() != Val1->getType()) 02481 return Error(ID.Loc, "compare operands must have the same type"); 02482 02483 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal; 02484 02485 if (Opc == Instruction::FCmp) { 02486 if (!Val0->getType()->isFPOrFPVectorTy()) 02487 return Error(ID.Loc, "fcmp requires floating point operands"); 02488 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1); 02489 } else { 02490 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!"); 02491 if (!Val0->getType()->isIntOrIntVectorTy() && 02492 !Val0->getType()->getScalarType()->isPointerTy()) 02493 return Error(ID.Loc, "icmp requires pointer or integer operands"); 02494 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1); 02495 } 02496 ID.Kind = ValID::t_Constant; 02497 return false; 02498 } 02499 02500 // Binary Operators. 02501 case lltok::kw_add: 02502 case lltok::kw_fadd: 02503 case lltok::kw_sub: 02504 case lltok::kw_fsub: 02505 case lltok::kw_mul: 02506 case lltok::kw_fmul: 02507 case lltok::kw_udiv: 02508 case lltok::kw_sdiv: 02509 case lltok::kw_fdiv: 02510 case lltok::kw_urem: 02511 case lltok::kw_srem: 02512 case lltok::kw_frem: 02513 case lltok::kw_shl: 02514 case lltok::kw_lshr: 02515 case lltok::kw_ashr: { 02516 bool NUW = false; 02517 bool NSW = false; 02518 bool Exact = false; 02519 unsigned Opc = Lex.getUIntVal(); 02520 Constant *Val0, *Val1; 02521 Lex.Lex(); 02522 LocTy ModifierLoc = Lex.getLoc(); 02523 if (Opc == Instruction::Add || Opc == Instruction::Sub || 02524 Opc == Instruction::Mul || Opc == Instruction::Shl) { 02525 if (EatIfPresent(lltok::kw_nuw)) 02526 NUW = true; 02527 if (EatIfPresent(lltok::kw_nsw)) { 02528 NSW = true; 02529 if (EatIfPresent(lltok::kw_nuw)) 02530 NUW = true; 02531 } 02532 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv || 02533 Opc == Instruction::LShr || Opc == Instruction::AShr) { 02534 if (EatIfPresent(lltok::kw_exact)) 02535 Exact = true; 02536 } 02537 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") || 02538 ParseGlobalTypeAndValue(Val0) || 02539 ParseToken(lltok::comma, "expected comma in binary constantexpr") || 02540 ParseGlobalTypeAndValue(Val1) || 02541 ParseToken(lltok::rparen, "expected ')' in binary constantexpr")) 02542 return true; 02543 if (Val0->getType() != Val1->getType()) 02544 return Error(ID.Loc, "operands of constexpr must have same type"); 02545 if (!Val0->getType()->isIntOrIntVectorTy()) { 02546 if (NUW) 02547 return Error(ModifierLoc, "nuw only applies to integer operations"); 02548 if (NSW) 02549 return Error(ModifierLoc, "nsw only applies to integer operations"); 02550 } 02551 // Check that the type is valid for the operator. 02552 switch (Opc) { 02553 case Instruction::Add: 02554 case Instruction::Sub: 02555 case Instruction::Mul: 02556 case Instruction::UDiv: 02557 case Instruction::SDiv: 02558 case Instruction::URem: 02559 case Instruction::SRem: 02560 case Instruction::Shl: 02561 case Instruction::AShr: 02562 case Instruction::LShr: 02563 if (!Val0->getType()->isIntOrIntVectorTy()) 02564 return Error(ID.Loc, "constexpr requires integer operands"); 02565 break; 02566 case Instruction::FAdd: 02567 case Instruction::FSub: 02568 case Instruction::FMul: 02569 case Instruction::FDiv: 02570 case Instruction::FRem: 02571 if (!Val0->getType()->isFPOrFPVectorTy()) 02572 return Error(ID.Loc, "constexpr requires fp operands"); 02573 break; 02574 default: llvm_unreachable("Unknown binary operator!"); 02575 } 02576 unsigned Flags = 0; 02577 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 02578 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap; 02579 if (Exact) Flags |= PossiblyExactOperator::IsExact; 02580 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags); 02581 ID.ConstantVal = C; 02582 ID.Kind = ValID::t_Constant; 02583 return false; 02584 } 02585 02586 // Logical Operations 02587 case lltok::kw_and: 02588 case lltok::kw_or: 02589 case lltok::kw_xor: { 02590 unsigned Opc = Lex.getUIntVal(); 02591 Constant *Val0, *Val1; 02592 Lex.Lex(); 02593 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") || 02594 ParseGlobalTypeAndValue(Val0) || 02595 ParseToken(lltok::comma, "expected comma in logical constantexpr") || 02596 ParseGlobalTypeAndValue(Val1) || 02597 ParseToken(lltok::rparen, "expected ')' in logical constantexpr")) 02598 return true; 02599 if (Val0->getType() != Val1->getType()) 02600 return Error(ID.Loc, "operands of constexpr must have same type"); 02601 if (!Val0->getType()->isIntOrIntVectorTy()) 02602 return Error(ID.Loc, 02603 "constexpr requires integer or integer vector operands"); 02604 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1); 02605 ID.Kind = ValID::t_Constant; 02606 return false; 02607 } 02608 02609 case lltok::kw_getelementptr: 02610 case lltok::kw_shufflevector: 02611 case lltok::kw_insertelement: 02612 case lltok::kw_extractelement: 02613 case lltok::kw_select: { 02614 unsigned Opc = Lex.getUIntVal(); 02615 SmallVector<Constant*, 16> Elts; 02616 bool InBounds = false; 02617 Lex.Lex(); 02618 if (Opc == Instruction::GetElementPtr) 02619 InBounds = EatIfPresent(lltok::kw_inbounds); 02620 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") || 02621 ParseGlobalValueVector(Elts) || 02622 ParseToken(lltok::rparen, "expected ')' in constantexpr")) 02623 return true; 02624 02625 if (Opc == Instruction::GetElementPtr) { 02626 if (Elts.size() == 0 || 02627 !Elts[0]->getType()->getScalarType()->isPointerTy()) 02628 return Error(ID.Loc, "getelementptr requires pointer operand"); 02629 02630 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 02631 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices)) 02632 return Error(ID.Loc, "invalid indices for getelementptr"); 02633 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices, 02634 InBounds); 02635 } else if (Opc == Instruction::Select) { 02636 if (Elts.size() != 3) 02637 return Error(ID.Loc, "expected three operands to select"); 02638 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1], 02639 Elts[2])) 02640 return Error(ID.Loc, Reason); 02641 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]); 02642 } else if (Opc == Instruction::ShuffleVector) { 02643 if (Elts.size() != 3) 02644 return Error(ID.Loc, "expected three operands to shufflevector"); 02645 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 02646 return Error(ID.Loc, "invalid operands to shufflevector"); 02647 ID.ConstantVal = 02648 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]); 02649 } else if (Opc == Instruction::ExtractElement) { 02650 if (Elts.size() != 2) 02651 return Error(ID.Loc, "expected two operands to extractelement"); 02652 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1])) 02653 return Error(ID.Loc, "invalid extractelement operands"); 02654 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]); 02655 } else { 02656 assert(Opc == Instruction::InsertElement && "Unknown opcode"); 02657 if (Elts.size() != 3) 02658 return Error(ID.Loc, "expected three operands to insertelement"); 02659 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 02660 return Error(ID.Loc, "invalid insertelement operands"); 02661 ID.ConstantVal = 02662 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]); 02663 } 02664 02665 ID.Kind = ValID::t_Constant; 02666 return false; 02667 } 02668 } 02669 02670 Lex.Lex(); 02671 return false; 02672 } 02673 02674 /// ParseGlobalValue - Parse a global value with the specified type. 02675 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) { 02676 C = 0; 02677 ValID ID; 02678 Value *V = NULL; 02679 bool Parsed = ParseValID(ID) || 02680 ConvertValIDToValue(Ty, ID, V, NULL); 02681 if (V && !(C = dyn_cast<Constant>(V))) 02682 return Error(ID.Loc, "global values must be constants"); 02683 return Parsed; 02684 } 02685 02686 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) { 02687 Type *Ty = 0; 02688 return ParseType(Ty) || 02689 ParseGlobalValue(Ty, V); 02690 } 02691 02692 /// ParseGlobalValueVector 02693 /// ::= /*empty*/ 02694 /// ::= TypeAndValue (',' TypeAndValue)* 02695 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) { 02696 // Empty list. 02697 if (Lex.getKind() == lltok::rbrace || 02698 Lex.getKind() == lltok::rsquare || 02699 Lex.getKind() == lltok::greater || 02700 Lex.getKind() == lltok::rparen) 02701 return false; 02702 02703 Constant *C; 02704 if (ParseGlobalTypeAndValue(C)) return true; 02705 Elts.push_back(C); 02706 02707 while (EatIfPresent(lltok::comma)) { 02708 if (ParseGlobalTypeAndValue(C)) return true; 02709 Elts.push_back(C); 02710 } 02711 02712 return false; 02713 } 02714 02715 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) { 02716 assert(Lex.getKind() == lltok::lbrace); 02717 Lex.Lex(); 02718 02719 SmallVector<Value*, 16> Elts; 02720 if (ParseMDNodeVector(Elts, PFS) || 02721 ParseToken(lltok::rbrace, "expected end of metadata node")) 02722 return true; 02723 02724 ID.MDNodeVal = MDNode::get(Context, Elts); 02725 ID.Kind = ValID::t_MDNode; 02726 return false; 02727 } 02728 02729 /// ParseMetadataValue 02730 /// ::= !42 02731 /// ::= !{...} 02732 /// ::= !"string" 02733 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) { 02734 assert(Lex.getKind() == lltok::exclaim); 02735 Lex.Lex(); 02736 02737 // MDNode: 02738 // !{ ... } 02739 if (Lex.getKind() == lltok::lbrace) 02740 return ParseMetadataListValue(ID, PFS); 02741 02742 // Standalone metadata reference 02743 // !42 02744 if (Lex.getKind() == lltok::APSInt) { 02745 if (ParseMDNodeID(ID.MDNodeVal)) return true; 02746 ID.Kind = ValID::t_MDNode; 02747 return false; 02748 } 02749 02750 // MDString: 02751 // ::= '!' STRINGCONSTANT 02752 if (ParseMDString(ID.MDStringVal)) return true; 02753 ID.Kind = ValID::t_MDString; 02754 return false; 02755 } 02756 02757 02758 //===----------------------------------------------------------------------===// 02759 // Function Parsing. 02760 //===----------------------------------------------------------------------===// 02761 02762 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V, 02763 PerFunctionState *PFS) { 02764 if (Ty->isFunctionTy()) 02765 return Error(ID.Loc, "functions are not values, refer to them as pointers"); 02766 02767 switch (ID.Kind) { 02768 case ValID::t_LocalID: 02769 if (!PFS) return Error(ID.Loc, "invalid use of function-local name"); 02770 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc); 02771 return (V == 0); 02772 case ValID::t_LocalName: 02773 if (!PFS) return Error(ID.Loc, "invalid use of function-local name"); 02774 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc); 02775 return (V == 0); 02776 case ValID::t_InlineAsm: { 02777 PointerType *PTy = dyn_cast<PointerType>(Ty); 02778 FunctionType *FTy = 02779 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0; 02780 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2)) 02781 return Error(ID.Loc, "invalid type for inline asm constraint string"); 02782 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, 02783 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2))); 02784 return false; 02785 } 02786 case ValID::t_MDNode: 02787 if (!Ty->isMetadataTy()) 02788 return Error(ID.Loc, "metadata value must have metadata type"); 02789 V = ID.MDNodeVal; 02790 return false; 02791 case ValID::t_MDString: 02792 if (!Ty->isMetadataTy()) 02793 return Error(ID.Loc, "metadata value must have metadata type"); 02794 V = ID.MDStringVal; 02795 return false; 02796 case ValID::t_GlobalName: 02797 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc); 02798 return V == 0; 02799 case ValID::t_GlobalID: 02800 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc); 02801 return V == 0; 02802 case ValID::t_APSInt: 02803 if (!Ty->isIntegerTy()) 02804 return Error(ID.Loc, "integer constant must have integer type"); 02805 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits()); 02806 V = ConstantInt::get(Context, ID.APSIntVal); 02807 return false; 02808 case ValID::t_APFloat: 02809 if (!Ty->isFloatingPointTy() || 02810 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal)) 02811 return Error(ID.Loc, "floating point constant invalid for type"); 02812 02813 // The lexer has no type info, so builds all half, float, and double FP 02814 // constants as double. Fix this here. Long double does not need this. 02815 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) { 02816 bool Ignored; 02817 if (Ty->isHalfTy()) 02818 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, 02819 &Ignored); 02820 else if (Ty->isFloatTy()) 02821 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, 02822 &Ignored); 02823 } 02824 V = ConstantFP::get(Context, ID.APFloatVal); 02825 02826 if (V->getType() != Ty) 02827 return Error(ID.Loc, "floating point constant does not have type '" + 02828 getTypeString(Ty) + "'"); 02829 02830 return false; 02831 case ValID::t_Null: 02832 if (!Ty->isPointerTy()) 02833 return Error(ID.Loc, "null must be a pointer type"); 02834 V = ConstantPointerNull::get(cast<PointerType>(Ty)); 02835 return false; 02836 case ValID::t_Undef: 02837 // FIXME: LabelTy should not be a first-class type. 02838 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 02839 return Error(ID.Loc, "invalid type for undef constant"); 02840 V = UndefValue::get(Ty); 02841 return false; 02842 case ValID::t_EmptyArray: 02843 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0) 02844 return Error(ID.Loc, "invalid empty array initializer"); 02845 V = UndefValue::get(Ty); 02846 return false; 02847 case ValID::t_Zero: 02848 // FIXME: LabelTy should not be a first-class type. 02849 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 02850 return Error(ID.Loc, "invalid type for null constant"); 02851 V = Constant::getNullValue(Ty); 02852 return false; 02853 case ValID::t_Constant: 02854 if (ID.ConstantVal->getType() != Ty) 02855 return Error(ID.Loc, "constant expression type mismatch"); 02856 02857 V = ID.ConstantVal; 02858 return false; 02859 case ValID::t_ConstantStruct: 02860 case ValID::t_PackedConstantStruct: 02861 if (StructType *ST = dyn_cast<StructType>(Ty)) { 02862 if (ST->getNumElements() != ID.UIntVal) 02863 return Error(ID.Loc, 02864 "initializer with struct type has wrong # elements"); 02865 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct)) 02866 return Error(ID.Loc, "packed'ness of initializer and type don't match"); 02867 02868 // Verify that the elements are compatible with the structtype. 02869 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i) 02870 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i)) 02871 return Error(ID.Loc, "element " + Twine(i) + 02872 " of struct initializer doesn't match struct element type"); 02873 02874 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts, 02875 ID.UIntVal)); 02876 } else 02877 return Error(ID.Loc, "constant expression type mismatch"); 02878 return false; 02879 } 02880 llvm_unreachable("Invalid ValID"); 02881 } 02882 02883 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) { 02884 V = 0; 02885 ValID ID; 02886 return ParseValID(ID, PFS) || 02887 ConvertValIDToValue(Ty, ID, V, PFS); 02888 } 02889 02890 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) { 02891 Type *Ty = 0; 02892 return ParseType(Ty) || 02893 ParseValue(Ty, V, PFS); 02894 } 02895 02896 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc, 02897 PerFunctionState &PFS) { 02898 Value *V; 02899 Loc = Lex.getLoc(); 02900 if (ParseTypeAndValue(V, PFS)) return true; 02901 if (!isa<BasicBlock>(V)) 02902 return Error(Loc, "expected a basic block"); 02903 BB = cast<BasicBlock>(V); 02904 return false; 02905 } 02906 02907 02908 /// FunctionHeader 02909 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs 02910 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection 02911 /// OptionalAlign OptGC 02912 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { 02913 // Parse the linkage. 02914 LocTy LinkageLoc = Lex.getLoc(); 02915 unsigned Linkage; 02916 02917 unsigned Visibility; 02918 AttrBuilder RetAttrs; 02919 CallingConv::ID CC; 02920 Type *RetType = 0; 02921 LocTy RetTypeLoc = Lex.getLoc(); 02922 if (ParseOptionalLinkage(Linkage) || 02923 ParseOptionalVisibility(Visibility) || 02924 ParseOptionalCallingConv(CC) || 02925 ParseOptionalReturnAttrs(RetAttrs) || 02926 ParseType(RetType, RetTypeLoc, true /*void allowed*/)) 02927 return true; 02928 02929 // Verify that the linkage is ok. 02930 switch ((GlobalValue::LinkageTypes)Linkage) { 02931 case GlobalValue::ExternalLinkage: 02932 break; // always ok. 02933 case GlobalValue::DLLImportLinkage: 02934 case GlobalValue::ExternalWeakLinkage: 02935 if (isDefine) 02936 return Error(LinkageLoc, "invalid linkage for function definition"); 02937 break; 02938 case GlobalValue::PrivateLinkage: 02939 case GlobalValue::LinkerPrivateLinkage: 02940 case GlobalValue::LinkerPrivateWeakLinkage: 02941 case GlobalValue::InternalLinkage: 02942 case GlobalValue::AvailableExternallyLinkage: 02943 case GlobalValue::LinkOnceAnyLinkage: 02944 case GlobalValue::LinkOnceODRLinkage: 02945 case GlobalValue::LinkOnceODRAutoHideLinkage: 02946 case GlobalValue::WeakAnyLinkage: 02947 case GlobalValue::WeakODRLinkage: 02948 case GlobalValue::DLLExportLinkage: 02949 if (!isDefine) 02950 return Error(LinkageLoc, "invalid linkage for function declaration"); 02951 break; 02952 case GlobalValue::AppendingLinkage: 02953 case GlobalValue::CommonLinkage: 02954 return Error(LinkageLoc, "invalid function linkage type"); 02955 } 02956 02957 if (!FunctionType::isValidReturnType(RetType)) 02958 return Error(RetTypeLoc, "invalid function return type"); 02959 02960 LocTy NameLoc = Lex.getLoc(); 02961 02962 std::string FunctionName; 02963 if (Lex.getKind() == lltok::GlobalVar) { 02964 FunctionName = Lex.getStrVal(); 02965 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok. 02966 unsigned NameID = Lex.getUIntVal(); 02967 02968 if (NameID != NumberedVals.size()) 02969 return TokError("function expected to be numbered '%" + 02970 Twine(NumberedVals.size()) + "'"); 02971 } else { 02972 return TokError("expected function name"); 02973 } 02974 02975 Lex.Lex(); 02976 02977 if (Lex.getKind() != lltok::lparen) 02978 return TokError("expected '(' in function argument list"); 02979 02980 SmallVector<ArgInfo, 8> ArgList; 02981 bool isVarArg; 02982 AttrBuilder FuncAttrs; 02983 std::vector<unsigned> FwdRefAttrGrps; 02984 LocTy NoBuiltinLoc; 02985 std::string Section; 02986 unsigned Alignment; 02987 std::string GC; 02988 bool UnnamedAddr; 02989 LocTy UnnamedAddrLoc; 02990 02991 if (ParseArgumentList(ArgList, isVarArg) || 02992 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr, 02993 &UnnamedAddrLoc) || 02994 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false, 02995 NoBuiltinLoc) || 02996 (EatIfPresent(lltok::kw_section) && 02997 ParseStringConstant(Section)) || 02998 ParseOptionalAlignment(Alignment) || 02999 (EatIfPresent(lltok::kw_gc) && 03000 ParseStringConstant(GC))) 03001 return true; 03002 03003 if (FuncAttrs.contains(Attribute::NoBuiltin)) 03004 return Error(NoBuiltinLoc, "'nobuiltin' attribute not valid on function"); 03005 03006 // If the alignment was parsed as an attribute, move to the alignment field. 03007 if (FuncAttrs.hasAlignmentAttr()) { 03008 Alignment = FuncAttrs.getAlignment(); 03009 FuncAttrs.removeAttribute(Attribute::Alignment); 03010 } 03011 03012 // Okay, if we got here, the function is syntactically valid. Convert types 03013 // and do semantic checks. 03014 std::vector<Type*> ParamTypeList; 03015 SmallVector<AttributeSet, 8> Attrs; 03016 03017 if (RetAttrs.hasAttributes()) 03018 Attrs.push_back(AttributeSet::get(RetType->getContext(), 03019 AttributeSet::ReturnIndex, 03020 RetAttrs)); 03021 03022 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 03023 ParamTypeList.push_back(ArgList[i].Ty); 03024 if (ArgList[i].Attrs.hasAttributes(i + 1)) { 03025 AttrBuilder B(ArgList[i].Attrs, i + 1); 03026 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B)); 03027 } 03028 } 03029 03030 if (FuncAttrs.hasAttributes()) 03031 Attrs.push_back(AttributeSet::get(RetType->getContext(), 03032 AttributeSet::FunctionIndex, 03033 FuncAttrs)); 03034 03035 AttributeSet PAL = AttributeSet::get(Context, Attrs); 03036 03037 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy()) 03038 return Error(RetTypeLoc, "functions with 'sret' argument must return void"); 03039 03040 FunctionType *FT = 03041 FunctionType::get(RetType, ParamTypeList, isVarArg); 03042 PointerType *PFT = PointerType::getUnqual(FT); 03043 03044 Fn = 0; 03045 if (!FunctionName.empty()) { 03046 // If this was a definition of a forward reference, remove the definition 03047 // from the forward reference table and fill in the forward ref. 03048 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI = 03049 ForwardRefVals.find(FunctionName); 03050 if (FRVI != ForwardRefVals.end()) { 03051 Fn = M->getFunction(FunctionName); 03052 if (!Fn) 03053 return Error(FRVI->second.second, "invalid forward reference to " 03054 "function as global value!"); 03055 if (Fn->getType() != PFT) 03056 return Error(FRVI->second.second, "invalid forward reference to " 03057 "function '" + FunctionName + "' with wrong type!"); 03058 03059 ForwardRefVals.erase(FRVI); 03060 } else if ((Fn = M->getFunction(FunctionName))) { 03061 // Reject redefinitions. 03062 return Error(NameLoc, "invalid redefinition of function '" + 03063 FunctionName + "'"); 03064 } else if (M->getNamedValue(FunctionName)) { 03065 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'"); 03066 } 03067 03068 } else { 03069 // If this is a definition of a forward referenced function, make sure the 03070 // types agree. 03071 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I 03072 = ForwardRefValIDs.find(NumberedVals.size()); 03073 if (I != ForwardRefValIDs.end()) { 03074 Fn = cast<Function>(I->second.first); 03075 if (Fn->getType() != PFT) 03076 return Error(NameLoc, "type of definition and forward reference of '@" + 03077 Twine(NumberedVals.size()) + "' disagree"); 03078 ForwardRefValIDs.erase(I); 03079 } 03080 } 03081 03082 if (Fn == 0) 03083 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M); 03084 else // Move the forward-reference to the correct spot in the module. 03085 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn); 03086 03087 if (FunctionName.empty()) 03088 NumberedVals.push_back(Fn); 03089 03090 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); 03091 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); 03092 Fn->setCallingConv(CC); 03093 Fn->setAttributes(PAL); 03094 Fn->setUnnamedAddr(UnnamedAddr); 03095 Fn->setAlignment(Alignment); 03096 Fn->setSection(Section); 03097 if (!GC.empty()) Fn->setGC(GC.c_str()); 03098 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps; 03099 03100 // Add all of the arguments we parsed to the function. 03101 Function::arg_iterator ArgIt = Fn->arg_begin(); 03102 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { 03103 // If the argument has a name, insert it into the argument symbol table. 03104 if (ArgList[i].Name.empty()) continue; 03105 03106 // Set the name, if it conflicted, it will be auto-renamed. 03107 ArgIt->setName(ArgList[i].Name); 03108 03109 if (ArgIt->getName() != ArgList[i].Name) 03110 return Error(ArgList[i].Loc, "redefinition of argument '%" + 03111 ArgList[i].Name + "'"); 03112 } 03113 03114 return false; 03115 } 03116 03117 03118 /// ParseFunctionBody 03119 /// ::= '{' BasicBlock+ '}' 03120 /// 03121 bool LLParser::ParseFunctionBody(Function &Fn) { 03122 if (Lex.getKind() != lltok::lbrace) 03123 return TokError("expected '{' in function body"); 03124 Lex.Lex(); // eat the {. 03125 03126 int FunctionNumber = -1; 03127 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1; 03128 03129 PerFunctionState PFS(*this, Fn, FunctionNumber); 03130 03131 // We need at least one basic block. 03132 if (Lex.getKind() == lltok::rbrace) 03133 return TokError("function body requires at least one basic block"); 03134 03135 while (Lex.getKind() != lltok::rbrace) 03136 if (ParseBasicBlock(PFS)) return true; 03137 03138 // Eat the }. 03139 Lex.Lex(); 03140 03141 // Verify function is ok. 03142 return PFS.FinishFunction(); 03143 } 03144 03145 /// ParseBasicBlock 03146 /// ::= LabelStr? Instruction* 03147 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) { 03148 // If this basic block starts out with a name, remember it. 03149 std::string Name; 03150 LocTy NameLoc = Lex.getLoc(); 03151 if (Lex.getKind() == lltok::LabelStr) { 03152 Name = Lex.getStrVal(); 03153 Lex.Lex(); 03154 } 03155 03156 BasicBlock *BB = PFS.DefineBB(Name, NameLoc); 03157 if (BB == 0) return true; 03158 03159 std::string NameStr; 03160 03161 // Parse the instructions in this block until we get a terminator. 03162 Instruction *Inst; 03163 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst; 03164 do { 03165 // This instruction may have three possibilities for a name: a) none 03166 // specified, b) name specified "%foo =", c) number specified: "%4 =". 03167 LocTy NameLoc = Lex.getLoc(); 03168 int NameID = -1; 03169 NameStr = ""; 03170 03171 if (Lex.getKind() == lltok::LocalVarID) { 03172 NameID = Lex.getUIntVal(); 03173 Lex.Lex(); 03174 if (ParseToken(lltok::equal, "expected '=' after instruction id")) 03175 return true; 03176 } else if (Lex.getKind() == lltok::LocalVar) { 03177 NameStr = Lex.getStrVal(); 03178 Lex.Lex(); 03179 if (ParseToken(lltok::equal, "expected '=' after instruction name")) 03180 return true; 03181 } 03182 03183 switch (ParseInstruction(Inst, BB, PFS)) { 03184 default: llvm_unreachable("Unknown ParseInstruction result!"); 03185 case InstError: return true; 03186 case InstNormal: 03187 BB->getInstList().push_back(Inst); 03188 03189 // With a normal result, we check to see if the instruction is followed by 03190 // a comma and metadata. 03191 if (EatIfPresent(lltok::comma)) 03192 if (ParseInstructionMetadata(Inst, &PFS)) 03193 return true; 03194 break; 03195 case InstExtraComma: 03196 BB->getInstList().push_back(Inst); 03197 03198 // If the instruction parser ate an extra comma at the end of it, it 03199 // *must* be followed by metadata. 03200 if (ParseInstructionMetadata(Inst, &PFS)) 03201 return true; 03202 break; 03203 } 03204 03205 // Set the name on the instruction. 03206 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true; 03207 } while (!isa<TerminatorInst>(Inst)); 03208 03209 return false; 03210 } 03211 03212 //===----------------------------------------------------------------------===// 03213 // Instruction Parsing. 03214 //===----------------------------------------------------------------------===// 03215 03216 /// ParseInstruction - Parse one of the many different instructions. 03217 /// 03218 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB, 03219 PerFunctionState &PFS) { 03220 lltok::Kind Token = Lex.getKind(); 03221 if (Token == lltok::Eof) 03222 return TokError("found end of file when expecting more instructions"); 03223 LocTy Loc = Lex.getLoc(); 03224 unsigned KeywordVal = Lex.getUIntVal(); 03225 Lex.Lex(); // Eat the keyword. 03226 03227 switch (Token) { 03228 default: return Error(Loc, "expected instruction opcode"); 03229 // Terminator Instructions. 03230 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false; 03231 case lltok::kw_ret: return ParseRet(Inst, BB, PFS); 03232 case lltok::kw_br: return ParseBr(Inst, PFS); 03233 case lltok::kw_switch: return ParseSwitch(Inst, PFS); 03234 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS); 03235 case lltok::kw_invoke: return ParseInvoke(Inst, PFS); 03236 case lltok::kw_resume: return ParseResume(Inst, PFS); 03237 // Binary Operators. 03238 case lltok::kw_add: 03239 case lltok::kw_sub: 03240 case lltok::kw_mul: 03241 case lltok::kw_shl: { 03242 bool NUW = EatIfPresent(lltok::kw_nuw); 03243 bool NSW = EatIfPresent(lltok::kw_nsw); 03244 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw); 03245 03246 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true; 03247 03248 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true); 03249 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true); 03250 return false; 03251 } 03252 case lltok::kw_fadd: 03253 case lltok::kw_fsub: 03254 case lltok::kw_fmul: 03255 case lltok::kw_fdiv: 03256 case lltok::kw_frem: { 03257 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 03258 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2); 03259 if (Res != 0) 03260 return Res; 03261 if (FMF.any()) 03262 Inst->setFastMathFlags(FMF); 03263 return 0; 03264 } 03265 03266 case lltok::kw_sdiv: 03267 case lltok::kw_udiv: 03268 case lltok::kw_lshr: 03269 case lltok::kw_ashr: { 03270 bool Exact = EatIfPresent(lltok::kw_exact); 03271 03272 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true; 03273 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true); 03274 return false; 03275 } 03276 03277 case lltok::kw_urem: 03278 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1); 03279 case lltok::kw_and: 03280 case lltok::kw_or: 03281 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal); 03282 case lltok::kw_icmp: 03283 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal); 03284 // Casts. 03285 case lltok::kw_trunc: 03286 case lltok::kw_zext: 03287 case lltok::kw_sext: 03288 case lltok::kw_fptrunc: 03289 case lltok::kw_fpext: 03290 case lltok::kw_bitcast: 03291 case lltok::kw_uitofp: 03292 case lltok::kw_sitofp: 03293 case lltok::kw_fptoui: 03294 case lltok::kw_fptosi: 03295 case lltok::kw_inttoptr: 03296 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal); 03297 // Other. 03298 case lltok::kw_select: return ParseSelect(Inst, PFS); 03299 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS); 03300 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS); 03301 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS); 03302 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS); 03303 case lltok::kw_phi: return ParsePHI(Inst, PFS); 03304 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS); 03305 case lltok::kw_call: return ParseCall(Inst, PFS, false); 03306 case lltok::kw_tail: return ParseCall(Inst, PFS, true); 03307 // Memory. 03308 case lltok::kw_alloca: return ParseAlloc(Inst, PFS); 03309 case lltok::kw_load: return ParseLoad(Inst, PFS); 03310 case lltok::kw_store: return ParseStore(Inst, PFS); 03311 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS); 03312 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS); 03313 case lltok::kw_fence: return ParseFence(Inst, PFS); 03314 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS); 03315 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS); 03316 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS); 03317 } 03318 } 03319 03320 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind. 03321 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) { 03322 if (Opc == Instruction::FCmp) { 03323 switch (Lex.getKind()) { 03324 default: return TokError("expected fcmp predicate (e.g. 'oeq')"); 03325 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break; 03326 case lltok::kw_one: P = CmpInst::FCMP_ONE; break; 03327 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break; 03328 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break; 03329 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break; 03330 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break; 03331 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break; 03332 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break; 03333 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break; 03334 case lltok::kw_une: P = CmpInst::FCMP_UNE; break; 03335 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break; 03336 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break; 03337 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break; 03338 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break; 03339 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break; 03340 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break; 03341 } 03342 } else { 03343 switch (Lex.getKind()) { 03344 default: return TokError("expected icmp predicate (e.g. 'eq')"); 03345 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break; 03346 case lltok::kw_ne: P = CmpInst::ICMP_NE; break; 03347 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break; 03348 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break; 03349 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break; 03350 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break; 03351 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break; 03352 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break; 03353 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break; 03354 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break; 03355 } 03356 } 03357 Lex.Lex(); 03358 return false; 03359 } 03360 03361 //===----------------------------------------------------------------------===// 03362 // Terminator Instructions. 03363 //===----------------------------------------------------------------------===// 03364 03365 /// ParseRet - Parse a return instruction. 03366 /// ::= 'ret' void (',' !dbg, !1)* 03367 /// ::= 'ret' TypeAndValue (',' !dbg, !1)* 03368 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB, 03369 PerFunctionState &PFS) { 03370 SMLoc TypeLoc = Lex.getLoc(); 03371 Type *Ty = 0; 03372 if (ParseType(Ty, true /*void allowed*/)) return true; 03373 03374 Type *ResType = PFS.getFunction().getReturnType(); 03375 03376 if (Ty->isVoidTy()) { 03377 if (!ResType->isVoidTy()) 03378 return Error(TypeLoc, "value doesn't match function result type '" + 03379 getTypeString(ResType) + "'"); 03380 03381 Inst = ReturnInst::Create(Context); 03382 return false; 03383 } 03384 03385 Value *RV; 03386 if (ParseValue(Ty, RV, PFS)) return true; 03387 03388 if (ResType != RV->getType()) 03389 return Error(TypeLoc, "value doesn't match function result type '" + 03390 getTypeString(ResType) + "'"); 03391 03392 Inst = ReturnInst::Create(Context, RV); 03393 return false; 03394 } 03395 03396 03397 /// ParseBr 03398 /// ::= 'br' TypeAndValue 03399 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue 03400 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) { 03401 LocTy Loc, Loc2; 03402 Value *Op0; 03403 BasicBlock *Op1, *Op2; 03404 if (ParseTypeAndValue(Op0, Loc, PFS)) return true; 03405 03406 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) { 03407 Inst = BranchInst::Create(BB); 03408 return false; 03409 } 03410 03411 if (Op0->getType() != Type::getInt1Ty(Context)) 03412 return Error(Loc, "branch condition must have 'i1' type"); 03413 03414 if (ParseToken(lltok::comma, "expected ',' after branch condition") || 03415 ParseTypeAndBasicBlock(Op1, Loc, PFS) || 03416 ParseToken(lltok::comma, "expected ',' after true destination") || 03417 ParseTypeAndBasicBlock(Op2, Loc2, PFS)) 03418 return true; 03419 03420 Inst = BranchInst::Create(Op1, Op2, Op0); 03421 return false; 03422 } 03423 03424 /// ParseSwitch 03425 /// Instruction 03426 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']' 03427 /// JumpTable 03428 /// ::= (TypeAndValue ',' TypeAndValue)* 03429 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) { 03430 LocTy CondLoc, BBLoc; 03431 Value *Cond; 03432 BasicBlock *DefaultBB; 03433 if (ParseTypeAndValue(Cond, CondLoc, PFS) || 03434 ParseToken(lltok::comma, "expected ',' after switch condition") || 03435 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) || 03436 ParseToken(lltok::lsquare, "expected '[' with switch table")) 03437 return true; 03438 03439 if (!Cond->getType()->isIntegerTy()) 03440 return Error(CondLoc, "switch condition must have integer type"); 03441 03442 // Parse the jump table pairs. 03443 SmallPtrSet<Value*, 32> SeenCases; 03444 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table; 03445 while (Lex.getKind() != lltok::rsquare) { 03446 Value *Constant; 03447 BasicBlock *DestBB; 03448 03449 if (ParseTypeAndValue(Constant, CondLoc, PFS) || 03450 ParseToken(lltok::comma, "expected ',' after case value") || 03451 ParseTypeAndBasicBlock(DestBB, PFS)) 03452 return true; 03453 03454 if (!SeenCases.insert(Constant)) 03455 return Error(CondLoc, "duplicate case value in switch"); 03456 if (!isa<ConstantInt>(Constant)) 03457 return Error(CondLoc, "case value is not a constant integer"); 03458 03459 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB)); 03460 } 03461 03462 Lex.Lex(); // Eat the ']'. 03463 03464 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size()); 03465 for (unsigned i = 0, e = Table.size(); i != e; ++i) 03466 SI->addCase(Table[i].first, Table[i].second); 03467 Inst = SI; 03468 return false; 03469 } 03470 03471 /// ParseIndirectBr 03472 /// Instruction 03473 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']' 03474 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) { 03475 LocTy AddrLoc; 03476 Value *Address; 03477 if (ParseTypeAndValue(Address, AddrLoc, PFS) || 03478 ParseToken(lltok::comma, "expected ',' after indirectbr address") || 03479 ParseToken(lltok::lsquare, "expected '[' with indirectbr")) 03480 return true; 03481 03482 if (!Address->getType()->isPointerTy()) 03483 return Error(AddrLoc, "indirectbr address must have pointer type"); 03484 03485 // Parse the destination list. 03486 SmallVector<BasicBlock*, 16> DestList; 03487 03488 if (Lex.getKind() != lltok::rsquare) { 03489 BasicBlock *DestBB; 03490 if (ParseTypeAndBasicBlock(DestBB, PFS)) 03491 return true; 03492 DestList.push_back(DestBB); 03493 03494 while (EatIfPresent(lltok::comma)) { 03495 if (ParseTypeAndBasicBlock(DestBB, PFS)) 03496 return true; 03497 DestList.push_back(DestBB); 03498 } 03499 } 03500 03501 if (ParseToken(lltok::rsquare, "expected ']' at end of block list")) 03502 return true; 03503 03504 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size()); 03505 for (unsigned i = 0, e = DestList.size(); i != e; ++i) 03506 IBI->addDestination(DestList[i]); 03507 Inst = IBI; 03508 return false; 03509 } 03510 03511 03512 /// ParseInvoke 03513 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList 03514 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue 03515 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { 03516 LocTy CallLoc = Lex.getLoc(); 03517 AttrBuilder RetAttrs, FnAttrs; 03518 std::vector<unsigned> FwdRefAttrGrps; 03519 LocTy NoBuiltinLoc; 03520 CallingConv::ID CC; 03521 Type *RetType = 0; 03522 LocTy RetTypeLoc; 03523 ValID CalleeID; 03524 SmallVector<ParamInfo, 16> ArgList; 03525 03526 BasicBlock *NormalBB, *UnwindBB; 03527 if (ParseOptionalCallingConv(CC) || 03528 ParseOptionalReturnAttrs(RetAttrs) || 03529 ParseType(RetType, RetTypeLoc, true /*void allowed*/) || 03530 ParseValID(CalleeID) || 03531 ParseParameterList(ArgList, PFS) || 03532 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 03533 NoBuiltinLoc) || 03534 ParseToken(lltok::kw_to, "expected 'to' in invoke") || 03535 ParseTypeAndBasicBlock(NormalBB, PFS) || 03536 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") || 03537 ParseTypeAndBasicBlock(UnwindBB, PFS)) 03538 return true; 03539 03540 // If RetType is a non-function pointer type, then this is the short syntax 03541 // for the call, which means that RetType is just the return type. Infer the 03542 // rest of the function argument types from the arguments that are present. 03543 PointerType *PFTy = 0; 03544 FunctionType *Ty = 0; 03545 if (!(PFTy = dyn_cast<PointerType>(RetType)) || 03546 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) { 03547 // Pull out the types of all of the arguments... 03548 std::vector<Type*> ParamTypes; 03549 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 03550 ParamTypes.push_back(ArgList[i].V->getType()); 03551 03552 if (!FunctionType::isValidReturnType(RetType)) 03553 return Error(RetTypeLoc, "Invalid result type for LLVM function"); 03554 03555 Ty = FunctionType::get(RetType, ParamTypes, false); 03556 PFTy = PointerType::getUnqual(Ty); 03557 } 03558 03559 // Look up the callee. 03560 Value *Callee; 03561 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true; 03562 03563 // Set up the Attribute for the function. 03564 SmallVector<AttributeSet, 8> Attrs; 03565 if (RetAttrs.hasAttributes()) 03566 Attrs.push_back(AttributeSet::get(RetType->getContext(), 03567 AttributeSet::ReturnIndex, 03568 RetAttrs)); 03569 03570 SmallVector<Value*, 8> Args; 03571 03572 // Loop through FunctionType's arguments and ensure they are specified 03573 // correctly. Also, gather any parameter attributes. 03574 FunctionType::param_iterator I = Ty->param_begin(); 03575 FunctionType::param_iterator E = Ty->param_end(); 03576 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 03577 Type *ExpectedTy = 0; 03578 if (I != E) { 03579 ExpectedTy = *I++; 03580 } else if (!Ty->isVarArg()) { 03581 return Error(ArgList[i].Loc, "too many arguments specified"); 03582 } 03583 03584 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 03585 return Error(ArgList[i].Loc, "argument is not of expected type '" + 03586 getTypeString(ExpectedTy) + "'"); 03587 Args.push_back(ArgList[i].V); 03588 if (ArgList[i].Attrs.hasAttributes(i + 1)) { 03589 AttrBuilder B(ArgList[i].Attrs, i + 1); 03590 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B)); 03591 } 03592 } 03593 03594 if (I != E) 03595 return Error(CallLoc, "not enough parameters specified for call"); 03596 03597 if (FnAttrs.hasAttributes()) 03598 Attrs.push_back(AttributeSet::get(RetType->getContext(), 03599 AttributeSet::FunctionIndex, 03600 FnAttrs)); 03601 03602 // Finish off the Attribute and check them 03603 AttributeSet PAL = AttributeSet::get(Context, Attrs); 03604 03605 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args); 03606 II->setCallingConv(CC); 03607 II->setAttributes(PAL); 03608 ForwardRefAttrGroups[II] = FwdRefAttrGrps; 03609 Inst = II; 03610 return false; 03611 } 03612 03613 /// ParseResume 03614 /// ::= 'resume' TypeAndValue 03615 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) { 03616 Value *Exn; LocTy ExnLoc; 03617 if (ParseTypeAndValue(Exn, ExnLoc, PFS)) 03618 return true; 03619 03620 ResumeInst *RI = ResumeInst::Create(Exn); 03621 Inst = RI; 03622 return false; 03623 } 03624 03625 //===----------------------------------------------------------------------===// 03626 // Binary Operators. 03627 //===----------------------------------------------------------------------===// 03628 03629 /// ParseArithmetic 03630 /// ::= ArithmeticOps TypeAndValue ',' Value 03631 /// 03632 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1, 03633 /// then any integer operand is allowed, if it is 2, any fp operand is allowed. 03634 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS, 03635 unsigned Opc, unsigned OperandType) { 03636 LocTy Loc; Value *LHS, *RHS; 03637 if (ParseTypeAndValue(LHS, Loc, PFS) || 03638 ParseToken(lltok::comma, "expected ',' in arithmetic operation") || 03639 ParseValue(LHS->getType(), RHS, PFS)) 03640 return true; 03641 03642 bool Valid; 03643 switch (OperandType) { 03644 default: llvm_unreachable("Unknown operand type!"); 03645 case 0: // int or FP. 03646 Valid = LHS->getType()->isIntOrIntVectorTy() || 03647 LHS->getType()->isFPOrFPVectorTy(); 03648 break; 03649 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break; 03650 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break; 03651 } 03652 03653 if (!Valid) 03654 return Error(Loc, "invalid operand type for instruction"); 03655 03656 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 03657 return false; 03658 } 03659 03660 /// ParseLogical 03661 /// ::= ArithmeticOps TypeAndValue ',' Value { 03662 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS, 03663 unsigned Opc) { 03664 LocTy Loc; Value *LHS, *RHS; 03665 if (ParseTypeAndValue(LHS, Loc, PFS) || 03666 ParseToken(lltok::comma, "expected ',' in logical operation") || 03667 ParseValue(LHS->getType(), RHS, PFS)) 03668 return true; 03669 03670 if (!LHS->getType()->isIntOrIntVectorTy()) 03671 return Error(Loc,"instruction requires integer or integer vector operands"); 03672 03673 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 03674 return false; 03675 } 03676 03677 03678 /// ParseCompare 03679 /// ::= 'icmp' IPredicates TypeAndValue ',' Value 03680 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value 03681 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS, 03682 unsigned Opc) { 03683 // Parse the integer/fp comparison predicate. 03684 LocTy Loc; 03685 unsigned Pred; 03686 Value *LHS, *RHS; 03687 if (ParseCmpPredicate(Pred, Opc) || 03688 ParseTypeAndValue(LHS, Loc, PFS) || 03689 ParseToken(lltok::comma, "expected ',' after compare value") || 03690 ParseValue(LHS->getType(), RHS, PFS)) 03691 return true; 03692 03693 if (Opc == Instruction::FCmp) { 03694 if (!LHS->getType()->isFPOrFPVectorTy()) 03695 return Error(Loc, "fcmp requires floating point operands"); 03696 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS); 03697 } else { 03698 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!"); 03699 if (!LHS->getType()->isIntOrIntVectorTy() && 03700 !LHS->getType()->getScalarType()->isPointerTy()) 03701 return Error(Loc, "icmp requires integer operands"); 03702 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS); 03703 } 03704 return false; 03705 } 03706 03707 //===----------------------------------------------------------------------===// 03708 // Other Instructions. 03709 //===----------------------------------------------------------------------===// 03710 03711 03712 /// ParseCast 03713 /// ::= CastOpc TypeAndValue 'to' Type 03714 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS, 03715 unsigned Opc) { 03716 LocTy Loc; 03717 Value *Op; 03718 Type *DestTy = 0; 03719 if (ParseTypeAndValue(Op, Loc, PFS) || 03720 ParseToken(lltok::kw_to, "expected 'to' after cast value") || 03721 ParseType(DestTy)) 03722 return true; 03723 03724 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) { 03725 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy); 03726 return Error(Loc, "invalid cast opcode for cast from '" + 03727 getTypeString(Op->getType()) + "' to '" + 03728 getTypeString(DestTy) + "'"); 03729 } 03730 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy); 03731 return false; 03732 } 03733 03734 /// ParseSelect 03735 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue 03736 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) { 03737 LocTy Loc; 03738 Value *Op0, *Op1, *Op2; 03739 if (ParseTypeAndValue(Op0, Loc, PFS) || 03740 ParseToken(lltok::comma, "expected ',' after select condition") || 03741 ParseTypeAndValue(Op1, PFS) || 03742 ParseToken(lltok::comma, "expected ',' after select value") || 03743 ParseTypeAndValue(Op2, PFS)) 03744 return true; 03745 03746 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2)) 03747 return Error(Loc, Reason); 03748 03749 Inst = SelectInst::Create(Op0, Op1, Op2); 03750 return false; 03751 } 03752 03753 /// ParseVA_Arg 03754 /// ::= 'va_arg' TypeAndValue ',' Type 03755 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) { 03756 Value *Op; 03757 Type *EltTy = 0; 03758 LocTy TypeLoc; 03759 if (ParseTypeAndValue(Op, PFS) || 03760 ParseToken(lltok::comma, "expected ',' after vaarg operand") || 03761 ParseType(EltTy, TypeLoc)) 03762 return true; 03763 03764 if (!EltTy->isFirstClassType()) 03765 return Error(TypeLoc, "va_arg requires operand with first class type"); 03766 03767 Inst = new VAArgInst(Op, EltTy); 03768 return false; 03769 } 03770 03771 /// ParseExtractElement 03772 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue 03773 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) { 03774 LocTy Loc; 03775 Value *Op0, *Op1; 03776 if (ParseTypeAndValue(Op0, Loc, PFS) || 03777 ParseToken(lltok::comma, "expected ',' after extract value") || 03778 ParseTypeAndValue(Op1, PFS)) 03779 return true; 03780 03781 if (!ExtractElementInst::isValidOperands(Op0, Op1)) 03782 return Error(Loc, "invalid extractelement operands"); 03783 03784 Inst = ExtractElementInst::Create(Op0, Op1); 03785 return false; 03786 } 03787 03788 /// ParseInsertElement 03789 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue 03790 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { 03791 LocTy Loc; 03792 Value *Op0, *Op1, *Op2; 03793 if (ParseTypeAndValue(Op0, Loc, PFS) || 03794 ParseToken(lltok::comma, "expected ',' after insertelement value") || 03795 ParseTypeAndValue(Op1, PFS) || 03796 ParseToken(lltok::comma, "expected ',' after insertelement value") || 03797 ParseTypeAndValue(Op2, PFS)) 03798 return true; 03799 03800 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2)) 03801 return Error(Loc, "invalid insertelement operands"); 03802 03803 Inst = InsertElementInst::Create(Op0, Op1, Op2); 03804 return false; 03805 } 03806 03807 /// ParseShuffleVector 03808 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue 03809 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { 03810 LocTy Loc; 03811 Value *Op0, *Op1, *Op2; 03812 if (ParseTypeAndValue(Op0, Loc, PFS) || 03813 ParseToken(lltok::comma, "expected ',' after shuffle mask") || 03814 ParseTypeAndValue(Op1, PFS) || 03815 ParseToken(lltok::comma, "expected ',' after shuffle value") || 03816 ParseTypeAndValue(Op2, PFS)) 03817 return true; 03818 03819 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) 03820 return Error(Loc, "invalid shufflevector operands"); 03821 03822 Inst = new ShuffleVectorInst(Op0, Op1, Op2); 03823 return false; 03824 } 03825 03826 /// ParsePHI 03827 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')* 03828 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) { 03829 Type *Ty = 0; LocTy TypeLoc; 03830 Value *Op0, *Op1; 03831 03832 if (ParseType(Ty, TypeLoc) || 03833 ParseToken(lltok::lsquare, "expected '[' in phi value list") || 03834 ParseValue(Ty, Op0, PFS) || 03835 ParseToken(lltok::comma, "expected ',' after insertelement value") || 03836 ParseValue(Type::getLabelTy(Context), Op1, PFS) || 03837 ParseToken(lltok::rsquare, "expected ']' in phi value list")) 03838 return true; 03839 03840 bool AteExtraComma = false; 03841 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals; 03842 while (1) { 03843 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1))); 03844 03845 if (!EatIfPresent(lltok::comma)) 03846 break; 03847 03848 if (Lex.getKind() == lltok::MetadataVar) { 03849 AteExtraComma = true; 03850 break; 03851 } 03852 03853 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") || 03854 ParseValue(Ty, Op0, PFS) || 03855 ParseToken(lltok::comma, "expected ',' after insertelement value") || 03856 ParseValue(Type::getLabelTy(Context), Op1, PFS) || 03857 ParseToken(lltok::rsquare, "expected ']' in phi value list")) 03858 return true; 03859 } 03860 03861 if (!Ty->isFirstClassType()) 03862 return Error(TypeLoc, "phi node must have first class type"); 03863 03864 PHINode *PN = PHINode::Create(Ty, PHIVals.size()); 03865 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i) 03866 PN->addIncoming(PHIVals[i].first, PHIVals[i].second); 03867 Inst = PN; 03868 return AteExtraComma ? InstExtraComma : InstNormal; 03869 } 03870 03871 /// ParseLandingPad 03872 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+ 03873 /// Clause 03874 /// ::= 'catch' TypeAndValue 03875 /// ::= 'filter' 03876 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )* 03877 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) { 03878 Type *Ty = 0; LocTy TyLoc; 03879 Value *PersFn; LocTy PersFnLoc; 03880 03881 if (ParseType(Ty, TyLoc) || 03882 ParseToken(lltok::kw_personality, "expected 'personality'") || 03883 ParseTypeAndValue(PersFn, PersFnLoc, PFS)) 03884 return true; 03885 03886 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0); 03887 LP->setCleanup(EatIfPresent(lltok::kw_cleanup)); 03888 03889 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){ 03890 LandingPadInst::ClauseType CT; 03891 if (EatIfPresent(lltok::kw_catch)) 03892 CT = LandingPadInst::Catch; 03893 else if (EatIfPresent(lltok::kw_filter)) 03894 CT = LandingPadInst::Filter; 03895 else 03896 return TokError("expected 'catch' or 'filter' clause type"); 03897 03898 Value *V; LocTy VLoc; 03899 if (ParseTypeAndValue(V, VLoc, PFS)) { 03900 delete LP; 03901 return true; 03902 } 03903 03904 // A 'catch' type expects a non-array constant. A filter clause expects an 03905 // array constant. 03906 if (CT == LandingPadInst::Catch) { 03907 if (isa<ArrayType>(V->getType())) 03908 Error(VLoc, "'catch' clause has an invalid type"); 03909 } else { 03910 if (!isa<ArrayType>(V->getType())) 03911 Error(VLoc, "'filter' clause has an invalid type"); 03912 } 03913 03914 LP->addClause(V); 03915 } 03916 03917 Inst = LP; 03918 return false; 03919 } 03920 03921 /// ParseCall 03922 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value 03923 /// ParameterList OptionalAttrs 03924 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, 03925 bool isTail) { 03926 AttrBuilder RetAttrs, FnAttrs; 03927 std::vector<unsigned> FwdRefAttrGrps; 03928 LocTy NoBuiltinLoc; 03929 CallingConv::ID CC; 03930 Type *RetType = 0; 03931 LocTy RetTypeLoc; 03932 ValID CalleeID; 03933 SmallVector<ParamInfo, 16> ArgList; 03934 LocTy CallLoc = Lex.getLoc(); 03935 03936 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) || 03937 ParseOptionalCallingConv(CC) || 03938 ParseOptionalReturnAttrs(RetAttrs) || 03939 ParseType(RetType, RetTypeLoc, true /*void allowed*/) || 03940 ParseValID(CalleeID) || 03941 ParseParameterList(ArgList, PFS) || 03942 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 03943 NoBuiltinLoc)) 03944 return true; 03945 03946 // If RetType is a non-function pointer type, then this is the short syntax 03947 // for the call, which means that RetType is just the return type. Infer the 03948 // rest of the function argument types from the arguments that are present. 03949 PointerType *PFTy = 0; 03950 FunctionType *Ty = 0; 03951 if (!(PFTy = dyn_cast<PointerType>(RetType)) || 03952 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) { 03953 // Pull out the types of all of the arguments... 03954 std::vector<Type*> ParamTypes; 03955 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 03956 ParamTypes.push_back(ArgList[i].V->getType()); 03957 03958 if (!FunctionType::isValidReturnType(RetType)) 03959 return Error(RetTypeLoc, "Invalid result type for LLVM function"); 03960 03961 Ty = FunctionType::get(RetType, ParamTypes, false); 03962 PFTy = PointerType::getUnqual(Ty); 03963 } 03964 03965 // Look up the callee. 03966 Value *Callee; 03967 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true; 03968 03969 // Set up the Attribute for the function. 03970 SmallVector<AttributeSet, 8> Attrs; 03971 if (RetAttrs.hasAttributes()) 03972 Attrs.push_back(AttributeSet::get(RetType->getContext(), 03973 AttributeSet::ReturnIndex, 03974 RetAttrs)); 03975 03976 SmallVector<Value*, 8> Args; 03977 03978 // Loop through FunctionType's arguments and ensure they are specified 03979 // correctly. Also, gather any parameter attributes. 03980 FunctionType::param_iterator I = Ty->param_begin(); 03981 FunctionType::param_iterator E = Ty->param_end(); 03982 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 03983 Type *ExpectedTy = 0; 03984 if (I != E) { 03985 ExpectedTy = *I++; 03986 } else if (!Ty->isVarArg()) { 03987 return Error(ArgList[i].Loc, "too many arguments specified"); 03988 } 03989 03990 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 03991 return Error(ArgList[i].Loc, "argument is not of expected type '" + 03992 getTypeString(ExpectedTy) + "'"); 03993 Args.push_back(ArgList[i].V); 03994 if (ArgList[i].Attrs.hasAttributes(i + 1)) { 03995 AttrBuilder B(ArgList[i].Attrs, i + 1); 03996 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B)); 03997 } 03998 } 03999 04000 if (I != E) 04001 return Error(CallLoc, "not enough parameters specified for call"); 04002 04003 if (FnAttrs.hasAttributes()) 04004 Attrs.push_back(AttributeSet::get(RetType->getContext(), 04005 AttributeSet::FunctionIndex, 04006 FnAttrs)); 04007 04008 // Finish off the Attribute and check them 04009 AttributeSet PAL = AttributeSet::get(Context, Attrs); 04010 04011 CallInst *CI = CallInst::Create(Callee, Args); 04012 CI->setTailCall(isTail); 04013 CI->setCallingConv(CC); 04014 CI->setAttributes(PAL); 04015 ForwardRefAttrGroups[CI] = FwdRefAttrGrps; 04016 Inst = CI; 04017 return false; 04018 } 04019 04020 //===----------------------------------------------------------------------===// 04021 // Memory Instructions. 04022 //===----------------------------------------------------------------------===// 04023 04024 /// ParseAlloc 04025 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)? 04026 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) { 04027 Value *Size = 0; 04028 LocTy SizeLoc; 04029 unsigned Alignment = 0; 04030 Type *Ty = 0; 04031 if (ParseType(Ty)) return true; 04032 04033 bool AteExtraComma = false; 04034 if (EatIfPresent(lltok::comma)) { 04035 if (Lex.getKind() == lltok::kw_align) { 04036 if (ParseOptionalAlignment(Alignment)) return true; 04037 } else if (Lex.getKind() == lltok::MetadataVar) { 04038 AteExtraComma = true; 04039 } else { 04040 if (ParseTypeAndValue(Size, SizeLoc, PFS) || 04041 ParseOptionalCommaAlign(Alignment, AteExtraComma)) 04042 return true; 04043 } 04044 } 04045 04046 if (Size && !Size->getType()->isIntegerTy()) 04047 return Error(SizeLoc, "element count must have integer type"); 04048 04049 Inst = new AllocaInst(Ty, Size, Alignment); 04050 return AteExtraComma ? InstExtraComma : InstNormal; 04051 } 04052 04053 /// ParseLoad 04054 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)? 04055 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue 04056 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 04057 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) { 04058 Value *Val; LocTy Loc; 04059 unsigned Alignment = 0; 04060 bool AteExtraComma = false; 04061 bool isAtomic = false; 04062 AtomicOrdering Ordering = NotAtomic; 04063 SynchronizationScope Scope = CrossThread; 04064 04065 if (Lex.getKind() == lltok::kw_atomic) { 04066 isAtomic = true; 04067 Lex.Lex(); 04068 } 04069 04070 bool isVolatile = false; 04071 if (Lex.getKind() == lltok::kw_volatile) { 04072 isVolatile = true; 04073 Lex.Lex(); 04074 } 04075 04076 if (ParseTypeAndValue(Val, Loc, PFS) || 04077 ParseScopeAndOrdering(isAtomic, Scope, Ordering) || 04078 ParseOptionalCommaAlign(Alignment, AteExtraComma)) 04079 return true; 04080 04081 if (!Val->getType()->isPointerTy() || 04082 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType()) 04083 return Error(Loc, "load operand must be a pointer to a first class type"); 04084 if (isAtomic && !Alignment) 04085 return Error(Loc, "atomic load must have explicit non-zero alignment"); 04086 if (Ordering == Release || Ordering == AcquireRelease) 04087 return Error(Loc, "atomic load cannot use Release ordering"); 04088 04089 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope); 04090 return AteExtraComma ? InstExtraComma : InstNormal; 04091 } 04092 04093 /// ParseStore 04094 04095 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)? 04096 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue 04097 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 04098 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) { 04099 Value *Val, *Ptr; LocTy Loc, PtrLoc; 04100 unsigned Alignment = 0; 04101 bool AteExtraComma = false; 04102 bool isAtomic = false; 04103 AtomicOrdering Ordering = NotAtomic; 04104 SynchronizationScope Scope = CrossThread; 04105 04106 if (Lex.getKind() == lltok::kw_atomic) { 04107 isAtomic = true; 04108 Lex.Lex(); 04109 } 04110 04111 bool isVolatile = false; 04112 if (Lex.getKind() == lltok::kw_volatile) { 04113 isVolatile = true; 04114 Lex.Lex(); 04115 } 04116 04117 if (ParseTypeAndValue(Val, Loc, PFS) || 04118 ParseToken(lltok::comma, "expected ',' after store operand") || 04119 ParseTypeAndValue(Ptr, PtrLoc, PFS) || 04120 ParseScopeAndOrdering(isAtomic, Scope, Ordering) || 04121 ParseOptionalCommaAlign(Alignment, AteExtraComma)) 04122 return true; 04123 04124 if (!Ptr->getType()->isPointerTy()) 04125 return Error(PtrLoc, "store operand must be a pointer"); 04126 if (!Val->getType()->isFirstClassType()) 04127 return Error(Loc, "store operand must be a first class value"); 04128 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 04129 return Error(Loc, "stored value and pointer type do not match"); 04130 if (isAtomic && !Alignment) 04131 return Error(Loc, "atomic store must have explicit non-zero alignment"); 04132 if (Ordering == Acquire || Ordering == AcquireRelease) 04133 return Error(Loc, "atomic store cannot use Acquire ordering"); 04134 04135 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope); 04136 return AteExtraComma ? InstExtraComma : InstNormal; 04137 } 04138 04139 /// ParseCmpXchg 04140 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue 04141 /// 'singlethread'? AtomicOrdering 04142 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) { 04143 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc; 04144 bool AteExtraComma = false; 04145 AtomicOrdering Ordering = NotAtomic; 04146 SynchronizationScope Scope = CrossThread; 04147 bool isVolatile = false; 04148 04149 if (EatIfPresent(lltok::kw_volatile)) 04150 isVolatile = true; 04151 04152 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) || 04153 ParseToken(lltok::comma, "expected ',' after cmpxchg address") || 04154 ParseTypeAndValue(Cmp, CmpLoc, PFS) || 04155 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") || 04156 ParseTypeAndValue(New, NewLoc, PFS) || 04157 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering)) 04158 return true; 04159 04160 if (Ordering == Unordered) 04161 return TokError("cmpxchg cannot be unordered"); 04162 if (!Ptr->getType()->isPointerTy()) 04163 return Error(PtrLoc, "cmpxchg operand must be a pointer"); 04164 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType()) 04165 return Error(CmpLoc, "compare value and pointer type do not match"); 04166 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType()) 04167 return Error(NewLoc, "new value and pointer type do not match"); 04168 if (!New->getType()->isIntegerTy()) 04169 return Error(NewLoc, "cmpxchg operand must be an integer"); 04170 unsigned Size = New->getType()->getPrimitiveSizeInBits(); 04171 if (Size < 8 || (Size & (Size - 1))) 04172 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized" 04173 " integer"); 04174 04175 AtomicCmpXchgInst *CXI = 04176 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope); 04177 CXI->setVolatile(isVolatile); 04178 Inst = CXI; 04179 return AteExtraComma ? InstExtraComma : InstNormal; 04180 } 04181 04182 /// ParseAtomicRMW 04183 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue 04184 /// 'singlethread'? AtomicOrdering 04185 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) { 04186 Value *Ptr, *Val; LocTy PtrLoc, ValLoc; 04187 bool AteExtraComma = false; 04188 AtomicOrdering Ordering = NotAtomic; 04189 SynchronizationScope Scope = CrossThread; 04190 bool isVolatile = false; 04191 AtomicRMWInst::BinOp Operation; 04192 04193 if (EatIfPresent(lltok::kw_volatile)) 04194 isVolatile = true; 04195 04196 switch (Lex.getKind()) { 04197 default: return TokError("expected binary operation in atomicrmw"); 04198 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break; 04199 case lltok::kw_add: Operation = AtomicRMWInst::Add; break; 04200 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break; 04201 case lltok::kw_and: Operation = AtomicRMWInst::And; break; 04202 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break; 04203 case lltok::kw_or: Operation = AtomicRMWInst::Or; break; 04204 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break; 04205 case lltok::kw_max: Operation = AtomicRMWInst::Max; break; 04206 case lltok::kw_min: Operation = AtomicRMWInst::Min; break; 04207 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break; 04208 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break; 04209 } 04210 Lex.Lex(); // Eat the operation. 04211 04212 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) || 04213 ParseToken(lltok::comma, "expected ',' after atomicrmw address") || 04214 ParseTypeAndValue(Val, ValLoc, PFS) || 04215 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering)) 04216 return true; 04217 04218 if (Ordering == Unordered) 04219 return TokError("atomicrmw cannot be unordered"); 04220 if (!Ptr->getType()->isPointerTy()) 04221 return Error(PtrLoc, "atomicrmw operand must be a pointer"); 04222 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 04223 return Error(ValLoc, "atomicrmw value and pointer type do not match"); 04224 if (!Val->getType()->isIntegerTy()) 04225 return Error(ValLoc, "atomicrmw operand must be an integer"); 04226 unsigned Size = Val->getType()->getPrimitiveSizeInBits(); 04227 if (Size < 8 || (Size & (Size - 1))) 04228 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized" 04229 " integer"); 04230 04231 AtomicRMWInst *RMWI = 04232 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope); 04233 RMWI->setVolatile(isVolatile); 04234 Inst = RMWI; 04235 return AteExtraComma ? InstExtraComma : InstNormal; 04236 } 04237 04238 /// ParseFence 04239 /// ::= 'fence' 'singlethread'? AtomicOrdering 04240 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) { 04241 AtomicOrdering Ordering = NotAtomic; 04242 SynchronizationScope Scope = CrossThread; 04243 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering)) 04244 return true; 04245 04246 if (Ordering == Unordered) 04247 return TokError("fence cannot be unordered"); 04248 if (Ordering == Monotonic) 04249 return TokError("fence cannot be monotonic"); 04250 04251 Inst = new FenceInst(Context, Ordering, Scope); 04252 return InstNormal; 04253 } 04254 04255 /// ParseGetElementPtr 04256 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)* 04257 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { 04258 Value *Ptr = 0; 04259 Value *Val = 0; 04260 LocTy Loc, EltLoc; 04261 04262 bool InBounds = EatIfPresent(lltok::kw_inbounds); 04263 04264 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true; 04265 04266 Type *BaseType = Ptr->getType(); 04267 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType()); 04268 if (!BasePointerType) 04269 return Error(Loc, "base of getelementptr must be a pointer"); 04270 04271 SmallVector<Value*, 16> Indices; 04272 bool AteExtraComma = false; 04273 while (EatIfPresent(lltok::comma)) { 04274 if (Lex.getKind() == lltok::MetadataVar) { 04275 AteExtraComma = true; 04276 break; 04277 } 04278 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true; 04279 if (!Val->getType()->getScalarType()->isIntegerTy()) 04280 return Error(EltLoc, "getelementptr index must be an integer"); 04281 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy()) 04282 return Error(EltLoc, "getelementptr index type missmatch"); 04283 if (Val->getType()->isVectorTy()) { 04284 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements(); 04285 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements(); 04286 if (ValNumEl != PtrNumEl) 04287 return Error(EltLoc, 04288 "getelementptr vector index has a wrong number of elements"); 04289 } 04290 Indices.push_back(Val); 04291 } 04292 04293 if (!Indices.empty() && !BasePointerType->getElementType()->isSized()) 04294 return Error(Loc, "base element of getelementptr must be sized"); 04295 04296 if (!GetElementPtrInst::getIndexedType(BaseType, Indices)) 04297 return Error(Loc, "invalid getelementptr indices"); 04298 Inst = GetElementPtrInst::Create(Ptr, Indices); 04299 if (InBounds) 04300 cast<GetElementPtrInst>(Inst)->setIsInBounds(true); 04301 return AteExtraComma ? InstExtraComma : InstNormal; 04302 } 04303 04304 /// ParseExtractValue 04305 /// ::= 'extractvalue' TypeAndValue (',' uint32)+ 04306 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { 04307 Value *Val; LocTy Loc; 04308 SmallVector<unsigned, 4> Indices; 04309 bool AteExtraComma; 04310 if (ParseTypeAndValue(Val, Loc, PFS) || 04311 ParseIndexList(Indices, AteExtraComma)) 04312 return true; 04313 04314 if (!Val->getType()->isAggregateType()) 04315 return Error(Loc, "extractvalue operand must be aggregate type"); 04316 04317 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 04318 return Error(Loc, "invalid indices for extractvalue"); 04319 Inst = ExtractValueInst::Create(Val, Indices); 04320 return AteExtraComma ? InstExtraComma : InstNormal; 04321 } 04322 04323 /// ParseInsertValue 04324 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+ 04325 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { 04326 Value *Val0, *Val1; LocTy Loc0, Loc1; 04327 SmallVector<unsigned, 4> Indices; 04328 bool AteExtraComma; 04329 if (ParseTypeAndValue(Val0, Loc0, PFS) || 04330 ParseToken(lltok::comma, "expected comma after insertvalue operand") || 04331 ParseTypeAndValue(Val1, Loc1, PFS) || 04332 ParseIndexList(Indices, AteExtraComma)) 04333 return true; 04334 04335 if (!Val0->getType()->isAggregateType()) 04336 return Error(Loc0, "insertvalue operand must be aggregate type"); 04337 04338 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices)) 04339 return Error(Loc0, "invalid indices for insertvalue"); 04340 Inst = InsertValueInst::Create(Val0, Val1, Indices); 04341 return AteExtraComma ? InstExtraComma : InstNormal; 04342 } 04343 04344 //===----------------------------------------------------------------------===// 04345 // Embedded metadata. 04346 //===----------------------------------------------------------------------===// 04347 04348 /// ParseMDNodeVector 04349 /// ::= Element (',' Element)* 04350 /// Element 04351 /// ::= 'null' | TypeAndValue 04352 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts, 04353 PerFunctionState *PFS) { 04354 // Check for an empty list. 04355 if (Lex.getKind() == lltok::rbrace) 04356 return false; 04357 04358 do { 04359 // Null is a special case since it is typeless. 04360 if (EatIfPresent(lltok::kw_null)) { 04361 Elts.push_back(0); 04362 continue; 04363 } 04364 04365 Value *V = 0; 04366 if (ParseTypeAndValue(V, PFS)) return true; 04367 Elts.push_back(V); 04368 } while (EatIfPresent(lltok::comma)); 04369 04370 return false; 04371 }