LLParser.cpp 117 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351
  1. //===-- LLParser.cpp - Parser Class ---------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the parser class for .ll files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "LLParser.h"
  14. #include "llvm/AutoUpgrade.h"
  15. #include "llvm/CallingConv.h"
  16. #include "llvm/Constants.h"
  17. #include "llvm/DerivedTypes.h"
  18. #include "llvm/InlineAsm.h"
  19. #include "llvm/Instructions.h"
  20. #include "llvm/LLVMContext.h"
  21. #include "llvm/MDNode.h"
  22. #include "llvm/Module.h"
  23. #include "llvm/ValueSymbolTable.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/StringExtras.h"
  26. #include "llvm/Support/ErrorHandling.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. using namespace llvm;
  29. namespace llvm {
  30. /// ValID - Represents a reference of a definition of some sort with no type.
  31. /// There are several cases where we have to parse the value but where the
  32. /// type can depend on later context. This may either be a numeric reference
  33. /// or a symbolic (%var) reference. This is just a discriminated union.
  34. struct ValID {
  35. enum {
  36. t_LocalID, t_GlobalID, // ID in UIntVal.
  37. t_LocalName, t_GlobalName, // Name in StrVal.
  38. t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
  39. t_Null, t_Undef, t_Zero, // No value.
  40. t_EmptyArray, // No value: []
  41. t_Constant, // Value in ConstantVal.
  42. t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
  43. } Kind;
  44. LLParser::LocTy Loc;
  45. unsigned UIntVal;
  46. std::string StrVal, StrVal2;
  47. APSInt APSIntVal;
  48. APFloat APFloatVal;
  49. Constant *ConstantVal;
  50. ValID() : APFloatVal(0.0) {}
  51. };
  52. }
  53. /// Run: module ::= toplevelentity*
  54. bool LLParser::Run() {
  55. // Prime the lexer.
  56. Lex.Lex();
  57. return ParseTopLevelEntities() ||
  58. ValidateEndOfModule();
  59. }
  60. /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
  61. /// module.
  62. bool LLParser::ValidateEndOfModule() {
  63. if (!ForwardRefTypes.empty())
  64. return Error(ForwardRefTypes.begin()->second.second,
  65. "use of undefined type named '" +
  66. ForwardRefTypes.begin()->first + "'");
  67. if (!ForwardRefTypeIDs.empty())
  68. return Error(ForwardRefTypeIDs.begin()->second.second,
  69. "use of undefined type '%" +
  70. utostr(ForwardRefTypeIDs.begin()->first) + "'");
  71. if (!ForwardRefVals.empty())
  72. return Error(ForwardRefVals.begin()->second.second,
  73. "use of undefined value '@" + ForwardRefVals.begin()->first +
  74. "'");
  75. if (!ForwardRefValIDs.empty())
  76. return Error(ForwardRefValIDs.begin()->second.second,
  77. "use of undefined value '@" +
  78. utostr(ForwardRefValIDs.begin()->first) + "'");
  79. if (!ForwardRefMDNodes.empty())
  80. return Error(ForwardRefMDNodes.begin()->second.second,
  81. "use of undefined metadata '!" +
  82. utostr(ForwardRefMDNodes.begin()->first) + "'");
  83. // Look for intrinsic functions and CallInst that need to be upgraded
  84. for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
  85. UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
  86. return false;
  87. }
  88. //===----------------------------------------------------------------------===//
  89. // Top-Level Entities
  90. //===----------------------------------------------------------------------===//
  91. bool LLParser::ParseTopLevelEntities() {
  92. while (1) {
  93. switch (Lex.getKind()) {
  94. default: return TokError("expected top-level entity");
  95. case lltok::Eof: return false;
  96. //case lltok::kw_define:
  97. case lltok::kw_declare: if (ParseDeclare()) return true; break;
  98. case lltok::kw_define: if (ParseDefine()) return true; break;
  99. case lltok::kw_module: if (ParseModuleAsm()) return true; break;
  100. case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
  101. case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
  102. case lltok::kw_type: if (ParseUnnamedType()) return true; break;
  103. case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
  104. case lltok::LocalVar: if (ParseNamedType()) return true; break;
  105. case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
  106. case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
  107. // The Global variable production with no name can have many different
  108. // optional leading prefixes, the production is:
  109. // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
  110. // OptionalAddrSpace ('constant'|'global') ...
  111. case lltok::kw_private: // OptionalLinkage
  112. case lltok::kw_internal: // OptionalLinkage
  113. case lltok::kw_weak: // OptionalLinkage
  114. case lltok::kw_weak_odr: // OptionalLinkage
  115. case lltok::kw_linkonce: // OptionalLinkage
  116. case lltok::kw_linkonce_odr: // OptionalLinkage
  117. case lltok::kw_appending: // OptionalLinkage
  118. case lltok::kw_dllexport: // OptionalLinkage
  119. case lltok::kw_common: // OptionalLinkage
  120. case lltok::kw_dllimport: // OptionalLinkage
  121. case lltok::kw_extern_weak: // OptionalLinkage
  122. case lltok::kw_external: { // OptionalLinkage
  123. unsigned Linkage, Visibility;
  124. if (ParseOptionalLinkage(Linkage) ||
  125. ParseOptionalVisibility(Visibility) ||
  126. ParseGlobal("", SMLoc(), Linkage, true, Visibility))
  127. return true;
  128. break;
  129. }
  130. case lltok::kw_default: // OptionalVisibility
  131. case lltok::kw_hidden: // OptionalVisibility
  132. case lltok::kw_protected: { // OptionalVisibility
  133. unsigned Visibility;
  134. if (ParseOptionalVisibility(Visibility) ||
  135. ParseGlobal("", SMLoc(), 0, false, Visibility))
  136. return true;
  137. break;
  138. }
  139. case lltok::kw_thread_local: // OptionalThreadLocal
  140. case lltok::kw_addrspace: // OptionalAddrSpace
  141. case lltok::kw_constant: // GlobalType
  142. case lltok::kw_global: // GlobalType
  143. if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
  144. break;
  145. }
  146. }
  147. }
  148. /// toplevelentity
  149. /// ::= 'module' 'asm' STRINGCONSTANT
  150. bool LLParser::ParseModuleAsm() {
  151. assert(Lex.getKind() == lltok::kw_module);
  152. Lex.Lex();
  153. std::string AsmStr;
  154. if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
  155. ParseStringConstant(AsmStr)) return true;
  156. const std::string &AsmSoFar = M->getModuleInlineAsm();
  157. if (AsmSoFar.empty())
  158. M->setModuleInlineAsm(AsmStr);
  159. else
  160. M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
  161. return false;
  162. }
  163. /// toplevelentity
  164. /// ::= 'target' 'triple' '=' STRINGCONSTANT
  165. /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
  166. bool LLParser::ParseTargetDefinition() {
  167. assert(Lex.getKind() == lltok::kw_target);
  168. std::string Str;
  169. switch (Lex.Lex()) {
  170. default: return TokError("unknown target property");
  171. case lltok::kw_triple:
  172. Lex.Lex();
  173. if (ParseToken(lltok::equal, "expected '=' after target triple") ||
  174. ParseStringConstant(Str))
  175. return true;
  176. M->setTargetTriple(Str);
  177. return false;
  178. case lltok::kw_datalayout:
  179. Lex.Lex();
  180. if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
  181. ParseStringConstant(Str))
  182. return true;
  183. M->setDataLayout(Str);
  184. return false;
  185. }
  186. }
  187. /// toplevelentity
  188. /// ::= 'deplibs' '=' '[' ']'
  189. /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
  190. bool LLParser::ParseDepLibs() {
  191. assert(Lex.getKind() == lltok::kw_deplibs);
  192. Lex.Lex();
  193. if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
  194. ParseToken(lltok::lsquare, "expected '=' after deplibs"))
  195. return true;
  196. if (EatIfPresent(lltok::rsquare))
  197. return false;
  198. std::string Str;
  199. if (ParseStringConstant(Str)) return true;
  200. M->addLibrary(Str);
  201. while (EatIfPresent(lltok::comma)) {
  202. if (ParseStringConstant(Str)) return true;
  203. M->addLibrary(Str);
  204. }
  205. return ParseToken(lltok::rsquare, "expected ']' at end of list");
  206. }
  207. /// toplevelentity
  208. /// ::= 'type' type
  209. bool LLParser::ParseUnnamedType() {
  210. assert(Lex.getKind() == lltok::kw_type);
  211. LocTy TypeLoc = Lex.getLoc();
  212. Lex.Lex(); // eat kw_type
  213. PATypeHolder Ty(Type::VoidTy);
  214. if (ParseType(Ty)) return true;
  215. unsigned TypeID = NumberedTypes.size();
  216. // See if this type was previously referenced.
  217. std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
  218. FI = ForwardRefTypeIDs.find(TypeID);
  219. if (FI != ForwardRefTypeIDs.end()) {
  220. if (FI->second.first.get() == Ty)
  221. return Error(TypeLoc, "self referential type is invalid");
  222. cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
  223. Ty = FI->second.first.get();
  224. ForwardRefTypeIDs.erase(FI);
  225. }
  226. NumberedTypes.push_back(Ty);
  227. return false;
  228. }
  229. /// toplevelentity
  230. /// ::= LocalVar '=' 'type' type
  231. bool LLParser::ParseNamedType() {
  232. std::string Name = Lex.getStrVal();
  233. LocTy NameLoc = Lex.getLoc();
  234. Lex.Lex(); // eat LocalVar.
  235. PATypeHolder Ty(Type::VoidTy);
  236. if (ParseToken(lltok::equal, "expected '=' after name") ||
  237. ParseToken(lltok::kw_type, "expected 'type' after name") ||
  238. ParseType(Ty))
  239. return true;
  240. // Set the type name, checking for conflicts as we do so.
  241. bool AlreadyExists = M->addTypeName(Name, Ty);
  242. if (!AlreadyExists) return false;
  243. // See if this type is a forward reference. We need to eagerly resolve
  244. // types to allow recursive type redefinitions below.
  245. std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
  246. FI = ForwardRefTypes.find(Name);
  247. if (FI != ForwardRefTypes.end()) {
  248. if (FI->second.first.get() == Ty)
  249. return Error(NameLoc, "self referential type is invalid");
  250. cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
  251. Ty = FI->second.first.get();
  252. ForwardRefTypes.erase(FI);
  253. }
  254. // Inserting a name that is already defined, get the existing name.
  255. const Type *Existing = M->getTypeByName(Name);
  256. assert(Existing && "Conflict but no matching type?!");
  257. // Otherwise, this is an attempt to redefine a type. That's okay if
  258. // the redefinition is identical to the original.
  259. // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
  260. if (Existing == Ty) return false;
  261. // Any other kind of (non-equivalent) redefinition is an error.
  262. return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
  263. Ty->getDescription() + "'");
  264. }
  265. /// toplevelentity
  266. /// ::= 'declare' FunctionHeader
  267. bool LLParser::ParseDeclare() {
  268. assert(Lex.getKind() == lltok::kw_declare);
  269. Lex.Lex();
  270. Function *F;
  271. return ParseFunctionHeader(F, false);
  272. }
  273. /// toplevelentity
  274. /// ::= 'define' FunctionHeader '{' ...
  275. bool LLParser::ParseDefine() {
  276. assert(Lex.getKind() == lltok::kw_define);
  277. Lex.Lex();
  278. Function *F;
  279. return ParseFunctionHeader(F, true) ||
  280. ParseFunctionBody(*F);
  281. }
  282. /// ParseGlobalType
  283. /// ::= 'constant'
  284. /// ::= 'global'
  285. bool LLParser::ParseGlobalType(bool &IsConstant) {
  286. if (Lex.getKind() == lltok::kw_constant)
  287. IsConstant = true;
  288. else if (Lex.getKind() == lltok::kw_global)
  289. IsConstant = false;
  290. else {
  291. IsConstant = false;
  292. return TokError("expected 'global' or 'constant'");
  293. }
  294. Lex.Lex();
  295. return false;
  296. }
  297. /// ParseNamedGlobal:
  298. /// GlobalVar '=' OptionalVisibility ALIAS ...
  299. /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
  300. bool LLParser::ParseNamedGlobal() {
  301. assert(Lex.getKind() == lltok::GlobalVar);
  302. LocTy NameLoc = Lex.getLoc();
  303. std::string Name = Lex.getStrVal();
  304. Lex.Lex();
  305. bool HasLinkage;
  306. unsigned Linkage, Visibility;
  307. if (ParseToken(lltok::equal, "expected '=' in global variable") ||
  308. ParseOptionalLinkage(Linkage, HasLinkage) ||
  309. ParseOptionalVisibility(Visibility))
  310. return true;
  311. if (HasLinkage || Lex.getKind() != lltok::kw_alias)
  312. return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
  313. return ParseAlias(Name, NameLoc, Visibility);
  314. }
  315. /// ParseStandaloneMetadata:
  316. /// !42 = !{...}
  317. bool LLParser::ParseStandaloneMetadata() {
  318. assert(Lex.getKind() == lltok::Metadata);
  319. Lex.Lex();
  320. unsigned MetadataID = 0;
  321. if (ParseUInt32(MetadataID))
  322. return true;
  323. if (MetadataCache.find(MetadataID) != MetadataCache.end())
  324. return TokError("Metadata id is already used");
  325. if (ParseToken(lltok::equal, "expected '=' here"))
  326. return true;
  327. LocTy TyLoc;
  328. PATypeHolder Ty(Type::VoidTy);
  329. if (ParseType(Ty, TyLoc))
  330. return true;
  331. Constant *Init = 0;
  332. if (ParseGlobalValue(Ty, Init))
  333. return true;
  334. MetadataCache[MetadataID] = Init;
  335. std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
  336. FI = ForwardRefMDNodes.find(MetadataID);
  337. if (FI != ForwardRefMDNodes.end()) {
  338. Constant *FwdNode = FI->second.first;
  339. FwdNode->replaceAllUsesWith(Init);
  340. ForwardRefMDNodes.erase(FI);
  341. }
  342. return false;
  343. }
  344. /// ParseAlias:
  345. /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
  346. /// Aliasee
  347. /// ::= TypeAndValue
  348. /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
  349. /// ::= 'getelementptr' '(' ... ')'
  350. ///
  351. /// Everything through visibility has already been parsed.
  352. ///
  353. bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
  354. unsigned Visibility) {
  355. assert(Lex.getKind() == lltok::kw_alias);
  356. Lex.Lex();
  357. unsigned Linkage;
  358. LocTy LinkageLoc = Lex.getLoc();
  359. if (ParseOptionalLinkage(Linkage))
  360. return true;
  361. if (Linkage != GlobalValue::ExternalLinkage &&
  362. Linkage != GlobalValue::WeakAnyLinkage &&
  363. Linkage != GlobalValue::WeakODRLinkage &&
  364. Linkage != GlobalValue::InternalLinkage &&
  365. Linkage != GlobalValue::PrivateLinkage)
  366. return Error(LinkageLoc, "invalid linkage type for alias");
  367. Constant *Aliasee;
  368. LocTy AliaseeLoc = Lex.getLoc();
  369. if (Lex.getKind() != lltok::kw_bitcast &&
  370. Lex.getKind() != lltok::kw_getelementptr) {
  371. if (ParseGlobalTypeAndValue(Aliasee)) return true;
  372. } else {
  373. // The bitcast dest type is not present, it is implied by the dest type.
  374. ValID ID;
  375. if (ParseValID(ID)) return true;
  376. if (ID.Kind != ValID::t_Constant)
  377. return Error(AliaseeLoc, "invalid aliasee");
  378. Aliasee = ID.ConstantVal;
  379. }
  380. if (!isa<PointerType>(Aliasee->getType()))
  381. return Error(AliaseeLoc, "alias must have pointer type");
  382. // Okay, create the alias but do not insert it into the module yet.
  383. GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
  384. (GlobalValue::LinkageTypes)Linkage, Name,
  385. Aliasee);
  386. GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
  387. // See if this value already exists in the symbol table. If so, it is either
  388. // a redefinition or a definition of a forward reference.
  389. if (GlobalValue *Val =
  390. cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
  391. // See if this was a redefinition. If so, there is no entry in
  392. // ForwardRefVals.
  393. std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
  394. I = ForwardRefVals.find(Name);
  395. if (I == ForwardRefVals.end())
  396. return Error(NameLoc, "redefinition of global named '@" + Name + "'");
  397. // Otherwise, this was a definition of forward ref. Verify that types
  398. // agree.
  399. if (Val->getType() != GA->getType())
  400. return Error(NameLoc,
  401. "forward reference and definition of alias have different types");
  402. // If they agree, just RAUW the old value with the alias and remove the
  403. // forward ref info.
  404. Val->replaceAllUsesWith(GA);
  405. Val->eraseFromParent();
  406. ForwardRefVals.erase(I);
  407. }
  408. // Insert into the module, we know its name won't collide now.
  409. M->getAliasList().push_back(GA);
  410. assert(GA->getNameStr() == Name && "Should not be a name conflict!");
  411. return false;
  412. }
  413. /// ParseGlobal
  414. /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
  415. /// OptionalAddrSpace GlobalType Type Const
  416. /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
  417. /// OptionalAddrSpace GlobalType Type Const
  418. ///
  419. /// Everything through visibility has been parsed already.
  420. ///
  421. bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
  422. unsigned Linkage, bool HasLinkage,
  423. unsigned Visibility) {
  424. unsigned AddrSpace;
  425. bool ThreadLocal, IsConstant;
  426. LocTy TyLoc;
  427. PATypeHolder Ty(Type::VoidTy);
  428. if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
  429. ParseOptionalAddrSpace(AddrSpace) ||
  430. ParseGlobalType(IsConstant) ||
  431. ParseType(Ty, TyLoc))
  432. return true;
  433. // If the linkage is specified and is external, then no initializer is
  434. // present.
  435. Constant *Init = 0;
  436. if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
  437. Linkage != GlobalValue::ExternalWeakLinkage &&
  438. Linkage != GlobalValue::ExternalLinkage)) {
  439. if (ParseGlobalValue(Ty, Init))
  440. return true;
  441. }
  442. if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
  443. return Error(TyLoc, "invalid type for global variable");
  444. GlobalVariable *GV = 0;
  445. // See if the global was forward referenced, if so, use the global.
  446. if (!Name.empty()) {
  447. if ((GV = M->getGlobalVariable(Name, true)) &&
  448. !ForwardRefVals.erase(Name))
  449. return Error(NameLoc, "redefinition of global '@" + Name + "'");
  450. } else {
  451. std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
  452. I = ForwardRefValIDs.find(NumberedVals.size());
  453. if (I != ForwardRefValIDs.end()) {
  454. GV = cast<GlobalVariable>(I->second.first);
  455. ForwardRefValIDs.erase(I);
  456. }
  457. }
  458. if (GV == 0) {
  459. GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
  460. Name, 0, false, AddrSpace);
  461. } else {
  462. if (GV->getType()->getElementType() != Ty)
  463. return Error(TyLoc,
  464. "forward reference and definition of global have different types");
  465. // Move the forward-reference to the correct spot in the module.
  466. M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
  467. }
  468. if (Name.empty())
  469. NumberedVals.push_back(GV);
  470. // Set the parsed properties on the global.
  471. if (Init)
  472. GV->setInitializer(Init);
  473. GV->setConstant(IsConstant);
  474. GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
  475. GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
  476. GV->setThreadLocal(ThreadLocal);
  477. // Parse attributes on the global.
  478. while (Lex.getKind() == lltok::comma) {
  479. Lex.Lex();
  480. if (Lex.getKind() == lltok::kw_section) {
  481. Lex.Lex();
  482. GV->setSection(Lex.getStrVal());
  483. if (ParseToken(lltok::StringConstant, "expected global section string"))
  484. return true;
  485. } else if (Lex.getKind() == lltok::kw_align) {
  486. unsigned Alignment;
  487. if (ParseOptionalAlignment(Alignment)) return true;
  488. GV->setAlignment(Alignment);
  489. } else {
  490. TokError("unknown global variable property!");
  491. }
  492. }
  493. return false;
  494. }
  495. //===----------------------------------------------------------------------===//
  496. // GlobalValue Reference/Resolution Routines.
  497. //===----------------------------------------------------------------------===//
  498. /// GetGlobalVal - Get a value with the specified name or ID, creating a
  499. /// forward reference record if needed. This can return null if the value
  500. /// exists but does not have the right type.
  501. GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
  502. LocTy Loc) {
  503. const PointerType *PTy = dyn_cast<PointerType>(Ty);
  504. if (PTy == 0) {
  505. Error(Loc, "global variable reference must have pointer type");
  506. return 0;
  507. }
  508. // Look this name up in the normal function symbol table.
  509. GlobalValue *Val =
  510. cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
  511. // If this is a forward reference for the value, see if we already created a
  512. // forward ref record.
  513. if (Val == 0) {
  514. std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
  515. I = ForwardRefVals.find(Name);
  516. if (I != ForwardRefVals.end())
  517. Val = I->second.first;
  518. }
  519. // If we have the value in the symbol table or fwd-ref table, return it.
  520. if (Val) {
  521. if (Val->getType() == Ty) return Val;
  522. Error(Loc, "'@" + Name + "' defined with type '" +
  523. Val->getType()->getDescription() + "'");
  524. return 0;
  525. }
  526. // Otherwise, create a new forward reference for this value and remember it.
  527. GlobalValue *FwdVal;
  528. if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
  529. // Function types can return opaque but functions can't.
  530. if (isa<OpaqueType>(FT->getReturnType())) {
  531. Error(Loc, "function may not return opaque type");
  532. return 0;
  533. }
  534. FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
  535. } else {
  536. FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
  537. GlobalValue::ExternalWeakLinkage, 0, Name);
  538. }
  539. ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
  540. return FwdVal;
  541. }
  542. GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
  543. const PointerType *PTy = dyn_cast<PointerType>(Ty);
  544. if (PTy == 0) {
  545. Error(Loc, "global variable reference must have pointer type");
  546. return 0;
  547. }
  548. GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
  549. // If this is a forward reference for the value, see if we already created a
  550. // forward ref record.
  551. if (Val == 0) {
  552. std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
  553. I = ForwardRefValIDs.find(ID);
  554. if (I != ForwardRefValIDs.end())
  555. Val = I->second.first;
  556. }
  557. // If we have the value in the symbol table or fwd-ref table, return it.
  558. if (Val) {
  559. if (Val->getType() == Ty) return Val;
  560. Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
  561. Val->getType()->getDescription() + "'");
  562. return 0;
  563. }
  564. // Otherwise, create a new forward reference for this value and remember it.
  565. GlobalValue *FwdVal;
  566. if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
  567. // Function types can return opaque but functions can't.
  568. if (isa<OpaqueType>(FT->getReturnType())) {
  569. Error(Loc, "function may not return opaque type");
  570. return 0;
  571. }
  572. FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
  573. } else {
  574. FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
  575. GlobalValue::ExternalWeakLinkage, 0, "");
  576. }
  577. ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
  578. return FwdVal;
  579. }
  580. //===----------------------------------------------------------------------===//
  581. // Helper Routines.
  582. //===----------------------------------------------------------------------===//
  583. /// ParseToken - If the current token has the specified kind, eat it and return
  584. /// success. Otherwise, emit the specified error and return failure.
  585. bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
  586. if (Lex.getKind() != T)
  587. return TokError(ErrMsg);
  588. Lex.Lex();
  589. return false;
  590. }
  591. /// ParseStringConstant
  592. /// ::= StringConstant
  593. bool LLParser::ParseStringConstant(std::string &Result) {
  594. if (Lex.getKind() != lltok::StringConstant)
  595. return TokError("expected string constant");
  596. Result = Lex.getStrVal();
  597. Lex.Lex();
  598. return false;
  599. }
  600. /// ParseUInt32
  601. /// ::= uint32
  602. bool LLParser::ParseUInt32(unsigned &Val) {
  603. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
  604. return TokError("expected integer");
  605. uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
  606. if (Val64 != unsigned(Val64))
  607. return TokError("expected 32-bit integer (too large)");
  608. Val = Val64;
  609. Lex.Lex();
  610. return false;
  611. }
  612. /// ParseOptionalAddrSpace
  613. /// := /*empty*/
  614. /// := 'addrspace' '(' uint32 ')'
  615. bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
  616. AddrSpace = 0;
  617. if (!EatIfPresent(lltok::kw_addrspace))
  618. return false;
  619. return ParseToken(lltok::lparen, "expected '(' in address space") ||
  620. ParseUInt32(AddrSpace) ||
  621. ParseToken(lltok::rparen, "expected ')' in address space");
  622. }
  623. /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
  624. /// indicates what kind of attribute list this is: 0: function arg, 1: result,
  625. /// 2: function attr.
  626. /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
  627. bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
  628. Attrs = Attribute::None;
  629. LocTy AttrLoc = Lex.getLoc();
  630. while (1) {
  631. switch (Lex.getKind()) {
  632. case lltok::kw_sext:
  633. case lltok::kw_zext:
  634. // Treat these as signext/zeroext if they occur in the argument list after
  635. // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
  636. // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
  637. // expr.
  638. // FIXME: REMOVE THIS IN LLVM 3.0
  639. if (AttrKind == 3) {
  640. if (Lex.getKind() == lltok::kw_sext)
  641. Attrs |= Attribute::SExt;
  642. else
  643. Attrs |= Attribute::ZExt;
  644. break;
  645. }
  646. // FALL THROUGH.
  647. default: // End of attributes.
  648. if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
  649. return Error(AttrLoc, "invalid use of function-only attribute");
  650. if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
  651. return Error(AttrLoc, "invalid use of parameter-only attribute");
  652. return false;
  653. case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
  654. case lltok::kw_signext: Attrs |= Attribute::SExt; break;
  655. case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
  656. case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
  657. case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
  658. case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
  659. case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
  660. case lltok::kw_nest: Attrs |= Attribute::Nest; break;
  661. case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
  662. case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
  663. case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
  664. case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
  665. case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
  666. case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
  667. case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
  668. case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
  669. case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
  670. case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
  671. case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
  672. case lltok::kw_align: {
  673. unsigned Alignment;
  674. if (ParseOptionalAlignment(Alignment))
  675. return true;
  676. Attrs |= Attribute::constructAlignmentFromInt(Alignment);
  677. continue;
  678. }
  679. }
  680. Lex.Lex();
  681. }
  682. }
  683. /// ParseOptionalLinkage
  684. /// ::= /*empty*/
  685. /// ::= 'private'
  686. /// ::= 'internal'
  687. /// ::= 'weak'
  688. /// ::= 'weak_odr'
  689. /// ::= 'linkonce'
  690. /// ::= 'linkonce_odr'
  691. /// ::= 'appending'
  692. /// ::= 'dllexport'
  693. /// ::= 'common'
  694. /// ::= 'dllimport'
  695. /// ::= 'extern_weak'
  696. /// ::= 'external'
  697. bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
  698. HasLinkage = false;
  699. switch (Lex.getKind()) {
  700. default: Res = GlobalValue::ExternalLinkage; return false;
  701. case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
  702. case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
  703. case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
  704. case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
  705. case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
  706. case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
  707. case lltok::kw_available_externally:
  708. Res = GlobalValue::AvailableExternallyLinkage;
  709. break;
  710. case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
  711. case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
  712. case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
  713. case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
  714. case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
  715. case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
  716. }
  717. Lex.Lex();
  718. HasLinkage = true;
  719. return false;
  720. }
  721. /// ParseOptionalVisibility
  722. /// ::= /*empty*/
  723. /// ::= 'default'
  724. /// ::= 'hidden'
  725. /// ::= 'protected'
  726. ///
  727. bool LLParser::ParseOptionalVisibility(unsigned &Res) {
  728. switch (Lex.getKind()) {
  729. default: Res = GlobalValue::DefaultVisibility; return false;
  730. case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
  731. case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
  732. case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
  733. }
  734. Lex.Lex();
  735. return false;
  736. }
  737. /// ParseOptionalCallingConv
  738. /// ::= /*empty*/
  739. /// ::= 'ccc'
  740. /// ::= 'fastcc'
  741. /// ::= 'coldcc'
  742. /// ::= 'x86_stdcallcc'
  743. /// ::= 'x86_fastcallcc'
  744. /// ::= 'arm_apcscc'
  745. /// ::= 'arm_aapcscc'
  746. /// ::= 'arm_aapcs_vfpcc'
  747. /// ::= 'cc' UINT
  748. ///
  749. bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
  750. switch (Lex.getKind()) {
  751. default: CC = CallingConv::C; return false;
  752. case lltok::kw_ccc: CC = CallingConv::C; break;
  753. case lltok::kw_fastcc: CC = CallingConv::Fast; break;
  754. case lltok::kw_coldcc: CC = CallingConv::Cold; break;
  755. case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
  756. case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
  757. case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
  758. case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
  759. case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
  760. case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
  761. }
  762. Lex.Lex();
  763. return false;
  764. }
  765. /// ParseOptionalAlignment
  766. /// ::= /* empty */
  767. /// ::= 'align' 4
  768. bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
  769. Alignment = 0;
  770. if (!EatIfPresent(lltok::kw_align))
  771. return false;
  772. LocTy AlignLoc = Lex.getLoc();
  773. if (ParseUInt32(Alignment)) return true;
  774. if (!isPowerOf2_32(Alignment))
  775. return Error(AlignLoc, "alignment is not a power of two");
  776. return false;
  777. }
  778. /// ParseOptionalCommaAlignment
  779. /// ::= /* empty */
  780. /// ::= ',' 'align' 4
  781. bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
  782. Alignment = 0;
  783. if (!EatIfPresent(lltok::comma))
  784. return false;
  785. return ParseToken(lltok::kw_align, "expected 'align'") ||
  786. ParseUInt32(Alignment);
  787. }
  788. /// ParseIndexList
  789. /// ::= (',' uint32)+
  790. bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
  791. if (Lex.getKind() != lltok::comma)
  792. return TokError("expected ',' as start of index list");
  793. while (EatIfPresent(lltok::comma)) {
  794. unsigned Idx;
  795. if (ParseUInt32(Idx)) return true;
  796. Indices.push_back(Idx);
  797. }
  798. return false;
  799. }
  800. //===----------------------------------------------------------------------===//
  801. // Type Parsing.
  802. //===----------------------------------------------------------------------===//
  803. /// ParseType - Parse and resolve a full type.
  804. bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
  805. LocTy TypeLoc = Lex.getLoc();
  806. if (ParseTypeRec(Result)) return true;
  807. // Verify no unresolved uprefs.
  808. if (!UpRefs.empty())
  809. return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
  810. if (!AllowVoid && Result.get() == Type::VoidTy)
  811. return Error(TypeLoc, "void type only allowed for function results");
  812. return false;
  813. }
  814. /// HandleUpRefs - Every time we finish a new layer of types, this function is
  815. /// called. It loops through the UpRefs vector, which is a list of the
  816. /// currently active types. For each type, if the up-reference is contained in
  817. /// the newly completed type, we decrement the level count. When the level
  818. /// count reaches zero, the up-referenced type is the type that is passed in:
  819. /// thus we can complete the cycle.
  820. ///
  821. PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
  822. // If Ty isn't abstract, or if there are no up-references in it, then there is
  823. // nothing to resolve here.
  824. if (!ty->isAbstract() || UpRefs.empty()) return ty;
  825. PATypeHolder Ty(ty);
  826. #if 0
  827. errs() << "Type '" << Ty->getDescription()
  828. << "' newly formed. Resolving upreferences.\n"
  829. << UpRefs.size() << " upreferences active!\n";
  830. #endif
  831. // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
  832. // to zero), we resolve them all together before we resolve them to Ty. At
  833. // the end of the loop, if there is anything to resolve to Ty, it will be in
  834. // this variable.
  835. OpaqueType *TypeToResolve = 0;
  836. for (unsigned i = 0; i != UpRefs.size(); ++i) {
  837. // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
  838. bool ContainsType =
  839. std::find(Ty->subtype_begin(), Ty->subtype_end(),
  840. UpRefs[i].LastContainedTy) != Ty->subtype_end();
  841. #if 0
  842. errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
  843. << UpRefs[i].LastContainedTy->getDescription() << ") = "
  844. << (ContainsType ? "true" : "false")
  845. << " level=" << UpRefs[i].NestingLevel << "\n";
  846. #endif
  847. if (!ContainsType)
  848. continue;
  849. // Decrement level of upreference
  850. unsigned Level = --UpRefs[i].NestingLevel;
  851. UpRefs[i].LastContainedTy = Ty;
  852. // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
  853. if (Level != 0)
  854. continue;
  855. #if 0
  856. errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
  857. #endif
  858. if (!TypeToResolve)
  859. TypeToResolve = UpRefs[i].UpRefTy;
  860. else
  861. UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
  862. UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
  863. --i; // Do not skip the next element.
  864. }
  865. if (TypeToResolve)
  866. TypeToResolve->refineAbstractTypeTo(Ty);
  867. return Ty;
  868. }
  869. /// ParseTypeRec - The recursive function used to process the internal
  870. /// implementation details of types.
  871. bool LLParser::ParseTypeRec(PATypeHolder &Result) {
  872. switch (Lex.getKind()) {
  873. default:
  874. return TokError("expected type");
  875. case lltok::Type:
  876. // TypeRec ::= 'float' | 'void' (etc)
  877. Result = Lex.getTyVal();
  878. Lex.Lex();
  879. break;
  880. case lltok::kw_opaque:
  881. // TypeRec ::= 'opaque'
  882. Result = Context.getOpaqueType();
  883. Lex.Lex();
  884. break;
  885. case lltok::lbrace:
  886. // TypeRec ::= '{' ... '}'
  887. if (ParseStructType(Result, false))
  888. return true;
  889. break;
  890. case lltok::lsquare:
  891. // TypeRec ::= '[' ... ']'
  892. Lex.Lex(); // eat the lsquare.
  893. if (ParseArrayVectorType(Result, false))
  894. return true;
  895. break;
  896. case lltok::less: // Either vector or packed struct.
  897. // TypeRec ::= '<' ... '>'
  898. Lex.Lex();
  899. if (Lex.getKind() == lltok::lbrace) {
  900. if (ParseStructType(Result, true) ||
  901. ParseToken(lltok::greater, "expected '>' at end of packed struct"))
  902. return true;
  903. } else if (ParseArrayVectorType(Result, true))
  904. return true;
  905. break;
  906. case lltok::LocalVar:
  907. case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
  908. // TypeRec ::= %foo
  909. if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
  910. Result = T;
  911. } else {
  912. Result = Context.getOpaqueType();
  913. ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
  914. std::make_pair(Result,
  915. Lex.getLoc())));
  916. M->addTypeName(Lex.getStrVal(), Result.get());
  917. }
  918. Lex.Lex();
  919. break;
  920. case lltok::LocalVarID:
  921. // TypeRec ::= %4
  922. if (Lex.getUIntVal() < NumberedTypes.size())
  923. Result = NumberedTypes[Lex.getUIntVal()];
  924. else {
  925. std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
  926. I = ForwardRefTypeIDs.find(Lex.getUIntVal());
  927. if (I != ForwardRefTypeIDs.end())
  928. Result = I->second.first;
  929. else {
  930. Result = Context.getOpaqueType();
  931. ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
  932. std::make_pair(Result,
  933. Lex.getLoc())));
  934. }
  935. }
  936. Lex.Lex();
  937. break;
  938. case lltok::backslash: {
  939. // TypeRec ::= '\' 4
  940. Lex.Lex();
  941. unsigned Val;
  942. if (ParseUInt32(Val)) return true;
  943. OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
  944. UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
  945. Result = OT;
  946. break;
  947. }
  948. }
  949. // Parse the type suffixes.
  950. while (1) {
  951. switch (Lex.getKind()) {
  952. // End of type.
  953. default: return false;
  954. // TypeRec ::= TypeRec '*'
  955. case lltok::star:
  956. if (Result.get() == Type::LabelTy)
  957. return TokError("basic block pointers are invalid");
  958. if (Result.get() == Type::VoidTy)
  959. return TokError("pointers to void are invalid; use i8* instead");
  960. if (!PointerType::isValidElementType(Result.get()))
  961. return TokError("pointer to this type is invalid");
  962. Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
  963. Lex.Lex();
  964. break;
  965. // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
  966. case lltok::kw_addrspace: {
  967. if (Result.get() == Type::LabelTy)
  968. return TokError("basic block pointers are invalid");
  969. if (Result.get() == Type::VoidTy)
  970. return TokError("pointers to void are invalid; use i8* instead");
  971. if (!PointerType::isValidElementType(Result.get()))
  972. return TokError("pointer to this type is invalid");
  973. unsigned AddrSpace;
  974. if (ParseOptionalAddrSpace(AddrSpace) ||
  975. ParseToken(lltok::star, "expected '*' in address space"))
  976. return true;
  977. Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
  978. break;
  979. }
  980. /// Types '(' ArgTypeListI ')' OptFuncAttrs
  981. case lltok::lparen:
  982. if (ParseFunctionType(Result))
  983. return true;
  984. break;
  985. }
  986. }
  987. }
  988. /// ParseParameterList
  989. /// ::= '(' ')'
  990. /// ::= '(' Arg (',' Arg)* ')'
  991. /// Arg
  992. /// ::= Type OptionalAttributes Value OptionalAttributes
  993. bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
  994. PerFunctionState &PFS) {
  995. if (ParseToken(lltok::lparen, "expected '(' in call"))
  996. return true;
  997. while (Lex.getKind() != lltok::rparen) {
  998. // If this isn't the first argument, we need a comma.
  999. if (!ArgList.empty() &&
  1000. ParseToken(lltok::comma, "expected ',' in argument list"))
  1001. return true;
  1002. // Parse the argument.
  1003. LocTy ArgLoc;
  1004. PATypeHolder ArgTy(Type::VoidTy);
  1005. unsigned ArgAttrs1, ArgAttrs2;
  1006. Value *V;
  1007. if (ParseType(ArgTy, ArgLoc) ||
  1008. ParseOptionalAttrs(ArgAttrs1, 0) ||
  1009. ParseValue(ArgTy, V, PFS) ||
  1010. // FIXME: Should not allow attributes after the argument, remove this in
  1011. // LLVM 3.0.
  1012. ParseOptionalAttrs(ArgAttrs2, 3))
  1013. return true;
  1014. ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
  1015. }
  1016. Lex.Lex(); // Lex the ')'.
  1017. return false;
  1018. }
  1019. /// ParseArgumentList - Parse the argument list for a function type or function
  1020. /// prototype. If 'inType' is true then we are parsing a FunctionType.
  1021. /// ::= '(' ArgTypeListI ')'
  1022. /// ArgTypeListI
  1023. /// ::= /*empty*/
  1024. /// ::= '...'
  1025. /// ::= ArgTypeList ',' '...'
  1026. /// ::= ArgType (',' ArgType)*
  1027. ///
  1028. bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
  1029. bool &isVarArg, bool inType) {
  1030. isVarArg = false;
  1031. assert(Lex.getKind() == lltok::lparen);
  1032. Lex.Lex(); // eat the (.
  1033. if (Lex.getKind() == lltok::rparen) {
  1034. // empty
  1035. } else if (Lex.getKind() == lltok::dotdotdot) {
  1036. isVarArg = true;
  1037. Lex.Lex();
  1038. } else {
  1039. LocTy TypeLoc = Lex.getLoc();
  1040. PATypeHolder ArgTy(Type::VoidTy);
  1041. unsigned Attrs;
  1042. std::string Name;
  1043. // If we're parsing a type, use ParseTypeRec, because we allow recursive
  1044. // types (such as a function returning a pointer to itself). If parsing a
  1045. // function prototype, we require fully resolved types.
  1046. if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
  1047. ParseOptionalAttrs(Attrs, 0)) return true;
  1048. if (ArgTy == Type::VoidTy)
  1049. return Error(TypeLoc, "argument can not have void type");
  1050. if (Lex.getKind() == lltok::LocalVar ||
  1051. Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
  1052. Name = Lex.getStrVal();
  1053. Lex.Lex();
  1054. }
  1055. if (!FunctionType::isValidArgumentType(ArgTy))
  1056. return Error(TypeLoc, "invalid type for function argument");
  1057. ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
  1058. while (EatIfPresent(lltok::comma)) {
  1059. // Handle ... at end of arg list.
  1060. if (EatIfPresent(lltok::dotdotdot)) {
  1061. isVarArg = true;
  1062. break;
  1063. }
  1064. // Otherwise must be an argument type.
  1065. TypeLoc = Lex.getLoc();
  1066. if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
  1067. ParseOptionalAttrs(Attrs, 0)) return true;
  1068. if (ArgTy == Type::VoidTy)
  1069. return Error(TypeLoc, "argument can not have void type");
  1070. if (Lex.getKind() == lltok::LocalVar ||
  1071. Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
  1072. Name = Lex.getStrVal();
  1073. Lex.Lex();
  1074. } else {
  1075. Name = "";
  1076. }
  1077. if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
  1078. return Error(TypeLoc, "invalid type for function argument");
  1079. ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
  1080. }
  1081. }
  1082. return ParseToken(lltok::rparen, "expected ')' at end of argument list");
  1083. }
  1084. /// ParseFunctionType
  1085. /// ::= Type ArgumentList OptionalAttrs
  1086. bool LLParser::ParseFunctionType(PATypeHolder &Result) {
  1087. assert(Lex.getKind() == lltok::lparen);
  1088. if (!FunctionType::isValidReturnType(Result))
  1089. return TokError("invalid function return type");
  1090. std::vector<ArgInfo> ArgList;
  1091. bool isVarArg;
  1092. unsigned Attrs;
  1093. if (ParseArgumentList(ArgList, isVarArg, true) ||
  1094. // FIXME: Allow, but ignore attributes on function types!
  1095. // FIXME: Remove in LLVM 3.0
  1096. ParseOptionalAttrs(Attrs, 2))
  1097. return true;
  1098. // Reject names on the arguments lists.
  1099. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  1100. if (!ArgList[i].Name.empty())
  1101. return Error(ArgList[i].Loc, "argument name invalid in function type");
  1102. if (!ArgList[i].Attrs != 0) {
  1103. // Allow but ignore attributes on function types; this permits
  1104. // auto-upgrade.
  1105. // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
  1106. }
  1107. }
  1108. std::vector<const Type*> ArgListTy;
  1109. for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
  1110. ArgListTy.push_back(ArgList[i].Type);
  1111. Result = HandleUpRefs(Context.getFunctionType(Result.get(),
  1112. ArgListTy, isVarArg));
  1113. return false;
  1114. }
  1115. /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
  1116. /// TypeRec
  1117. /// ::= '{' '}'
  1118. /// ::= '{' TypeRec (',' TypeRec)* '}'
  1119. /// ::= '<' '{' '}' '>'
  1120. /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
  1121. bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
  1122. assert(Lex.getKind() == lltok::lbrace);
  1123. Lex.Lex(); // Consume the '{'
  1124. if (EatIfPresent(lltok::rbrace)) {
  1125. Result = Context.getStructType(Packed);
  1126. return false;
  1127. }
  1128. std::vector<PATypeHolder> ParamsList;
  1129. LocTy EltTyLoc = Lex.getLoc();
  1130. if (ParseTypeRec(Result)) return true;
  1131. ParamsList.push_back(Result);
  1132. if (Result == Type::VoidTy)
  1133. return Error(EltTyLoc, "struct element can not have void type");
  1134. if (!StructType::isValidElementType(Result))
  1135. return Error(EltTyLoc, "invalid element type for struct");
  1136. while (EatIfPresent(lltok::comma)) {
  1137. EltTyLoc = Lex.getLoc();
  1138. if (ParseTypeRec(Result)) return true;
  1139. if (Result == Type::VoidTy)
  1140. return Error(EltTyLoc, "struct element can not have void type");
  1141. if (!StructType::isValidElementType(Result))
  1142. return Error(EltTyLoc, "invalid element type for struct");
  1143. ParamsList.push_back(Result);
  1144. }
  1145. if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
  1146. return true;
  1147. std::vector<const Type*> ParamsListTy;
  1148. for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
  1149. ParamsListTy.push_back(ParamsList[i].get());
  1150. Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
  1151. return false;
  1152. }
  1153. /// ParseArrayVectorType - Parse an array or vector type, assuming the first
  1154. /// token has already been consumed.
  1155. /// TypeRec
  1156. /// ::= '[' APSINTVAL 'x' Types ']'
  1157. /// ::= '<' APSINTVAL 'x' Types '>'
  1158. bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
  1159. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
  1160. Lex.getAPSIntVal().getBitWidth() > 64)
  1161. return TokError("expected number in address space");
  1162. LocTy SizeLoc = Lex.getLoc();
  1163. uint64_t Size = Lex.getAPSIntVal().getZExtValue();
  1164. Lex.Lex();
  1165. if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
  1166. return true;
  1167. LocTy TypeLoc = Lex.getLoc();
  1168. PATypeHolder EltTy(Type::VoidTy);
  1169. if (ParseTypeRec(EltTy)) return true;
  1170. if (EltTy == Type::VoidTy)
  1171. return Error(TypeLoc, "array and vector element type cannot be void");
  1172. if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
  1173. "expected end of sequential type"))
  1174. return true;
  1175. if (isVector) {
  1176. if (Size == 0)
  1177. return Error(SizeLoc, "zero element vector is illegal");
  1178. if ((unsigned)Size != Size)
  1179. return Error(SizeLoc, "size too large for vector");
  1180. if (!VectorType::isValidElementType(EltTy))
  1181. return Error(TypeLoc, "vector element type must be fp or integer");
  1182. Result = Context.getVectorType(EltTy, unsigned(Size));
  1183. } else {
  1184. if (!ArrayType::isValidElementType(EltTy))
  1185. return Error(TypeLoc, "invalid array element type");
  1186. Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
  1187. }
  1188. return false;
  1189. }
  1190. //===----------------------------------------------------------------------===//
  1191. // Function Semantic Analysis.
  1192. //===----------------------------------------------------------------------===//
  1193. LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
  1194. : P(p), F(f) {
  1195. // Insert unnamed arguments into the NumberedVals list.
  1196. for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
  1197. AI != E; ++AI)
  1198. if (!AI->hasName())
  1199. NumberedVals.push_back(AI);
  1200. }
  1201. LLParser::PerFunctionState::~PerFunctionState() {
  1202. // If there were any forward referenced non-basicblock values, delete them.
  1203. for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
  1204. I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
  1205. if (!isa<BasicBlock>(I->second.first)) {
  1206. I->second.first->replaceAllUsesWith(
  1207. P.getContext().getUndef(I->second.first->getType()));
  1208. delete I->second.first;
  1209. I->second.first = 0;
  1210. }
  1211. for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
  1212. I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
  1213. if (!isa<BasicBlock>(I->second.first)) {
  1214. I->second.first->replaceAllUsesWith(
  1215. P.getContext().getUndef(I->second.first->getType()));
  1216. delete I->second.first;
  1217. I->second.first = 0;
  1218. }
  1219. }
  1220. bool LLParser::PerFunctionState::VerifyFunctionComplete() {
  1221. if (!ForwardRefVals.empty())
  1222. return P.Error(ForwardRefVals.begin()->second.second,
  1223. "use of undefined value '%" + ForwardRefVals.begin()->first +
  1224. "'");
  1225. if (!ForwardRefValIDs.empty())
  1226. return P.Error(ForwardRefValIDs.begin()->second.second,
  1227. "use of undefined value '%" +
  1228. utostr(ForwardRefValIDs.begin()->first) + "'");
  1229. return false;
  1230. }
  1231. /// GetVal - Get a value with the specified name or ID, creating a
  1232. /// forward reference record if needed. This can return null if the value
  1233. /// exists but does not have the right type.
  1234. Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
  1235. const Type *Ty, LocTy Loc) {
  1236. // Look this name up in the normal function symbol table.
  1237. Value *Val = F.getValueSymbolTable().lookup(Name);
  1238. // If this is a forward reference for the value, see if we already created a
  1239. // forward ref record.
  1240. if (Val == 0) {
  1241. std::map<std::string, std::pair<Value*, LocTy> >::iterator
  1242. I = ForwardRefVals.find(Name);
  1243. if (I != ForwardRefVals.end())
  1244. Val = I->second.first;
  1245. }
  1246. // If we have the value in the symbol table or fwd-ref table, return it.
  1247. if (Val) {
  1248. if (Val->getType() == Ty) return Val;
  1249. if (Ty == Type::LabelTy)
  1250. P.Error(Loc, "'%" + Name + "' is not a basic block");
  1251. else
  1252. P.Error(Loc, "'%" + Name + "' defined with type '" +
  1253. Val->getType()->getDescription() + "'");
  1254. return 0;
  1255. }
  1256. // Don't make placeholders with invalid type.
  1257. if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
  1258. P.Error(Loc, "invalid use of a non-first-class type");
  1259. return 0;
  1260. }
  1261. // Otherwise, create a new forward reference for this value and remember it.
  1262. Value *FwdVal;
  1263. if (Ty == Type::LabelTy)
  1264. FwdVal = BasicBlock::Create(Name, &F);
  1265. else
  1266. FwdVal = new Argument(Ty, Name);
  1267. ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
  1268. return FwdVal;
  1269. }
  1270. Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
  1271. LocTy Loc) {
  1272. // Look this name up in the normal function symbol table.
  1273. Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
  1274. // If this is a forward reference for the value, see if we already created a
  1275. // forward ref record.
  1276. if (Val == 0) {
  1277. std::map<unsigned, std::pair<Value*, LocTy> >::iterator
  1278. I = ForwardRefValIDs.find(ID);
  1279. if (I != ForwardRefValIDs.end())
  1280. Val = I->second.first;
  1281. }
  1282. // If we have the value in the symbol table or fwd-ref table, return it.
  1283. if (Val) {
  1284. if (Val->getType() == Ty) return Val;
  1285. if (Ty == Type::LabelTy)
  1286. P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
  1287. else
  1288. P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
  1289. Val->getType()->getDescription() + "'");
  1290. return 0;
  1291. }
  1292. if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
  1293. P.Error(Loc, "invalid use of a non-first-class type");
  1294. return 0;
  1295. }
  1296. // Otherwise, create a new forward reference for this value and remember it.
  1297. Value *FwdVal;
  1298. if (Ty == Type::LabelTy)
  1299. FwdVal = BasicBlock::Create("", &F);
  1300. else
  1301. FwdVal = new Argument(Ty);
  1302. ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
  1303. return FwdVal;
  1304. }
  1305. /// SetInstName - After an instruction is parsed and inserted into its
  1306. /// basic block, this installs its name.
  1307. bool LLParser::PerFunctionState::SetInstName(int NameID,
  1308. const std::string &NameStr,
  1309. LocTy NameLoc, Instruction *Inst) {
  1310. // If this instruction has void type, it cannot have a name or ID specified.
  1311. if (Inst->getType() == Type::VoidTy) {
  1312. if (NameID != -1 || !NameStr.empty())
  1313. return P.Error(NameLoc, "instructions returning void cannot have a name");
  1314. return false;
  1315. }
  1316. // If this was a numbered instruction, verify that the instruction is the
  1317. // expected value and resolve any forward references.
  1318. if (NameStr.empty()) {
  1319. // If neither a name nor an ID was specified, just use the next ID.
  1320. if (NameID == -1)
  1321. NameID = NumberedVals.size();
  1322. if (unsigned(NameID) != NumberedVals.size())
  1323. return P.Error(NameLoc, "instruction expected to be numbered '%" +
  1324. utostr(NumberedVals.size()) + "'");
  1325. std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
  1326. ForwardRefValIDs.find(NameID);
  1327. if (FI != ForwardRefValIDs.end()) {
  1328. if (FI->second.first->getType() != Inst->getType())
  1329. return P.Error(NameLoc, "instruction forward referenced with type '" +
  1330. FI->second.first->getType()->getDescription() + "'");
  1331. FI->second.first->replaceAllUsesWith(Inst);
  1332. ForwardRefValIDs.erase(FI);
  1333. }
  1334. NumberedVals.push_back(Inst);
  1335. return false;
  1336. }
  1337. // Otherwise, the instruction had a name. Resolve forward refs and set it.
  1338. std::map<std::string, std::pair<Value*, LocTy> >::iterator
  1339. FI = ForwardRefVals.find(NameStr);
  1340. if (FI != ForwardRefVals.end()) {
  1341. if (FI->second.first->getType() != Inst->getType())
  1342. return P.Error(NameLoc, "instruction forward referenced with type '" +
  1343. FI->second.first->getType()->getDescription() + "'");
  1344. FI->second.first->replaceAllUsesWith(Inst);
  1345. ForwardRefVals.erase(FI);
  1346. }
  1347. // Set the name on the instruction.
  1348. Inst->setName(NameStr);
  1349. if (Inst->getNameStr() != NameStr)
  1350. return P.Error(NameLoc, "multiple definition of local value named '" +
  1351. NameStr + "'");
  1352. return false;
  1353. }
  1354. /// GetBB - Get a basic block with the specified name or ID, creating a
  1355. /// forward reference record if needed.
  1356. BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
  1357. LocTy Loc) {
  1358. return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
  1359. }
  1360. BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
  1361. return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
  1362. }
  1363. /// DefineBB - Define the specified basic block, which is either named or
  1364. /// unnamed. If there is an error, this returns null otherwise it returns
  1365. /// the block being defined.
  1366. BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
  1367. LocTy Loc) {
  1368. BasicBlock *BB;
  1369. if (Name.empty())
  1370. BB = GetBB(NumberedVals.size(), Loc);
  1371. else
  1372. BB = GetBB(Name, Loc);
  1373. if (BB == 0) return 0; // Already diagnosed error.
  1374. // Move the block to the end of the function. Forward ref'd blocks are
  1375. // inserted wherever they happen to be referenced.
  1376. F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
  1377. // Remove the block from forward ref sets.
  1378. if (Name.empty()) {
  1379. ForwardRefValIDs.erase(NumberedVals.size());
  1380. NumberedVals.push_back(BB);
  1381. } else {
  1382. // BB forward references are already in the function symbol table.
  1383. ForwardRefVals.erase(Name);
  1384. }
  1385. return BB;
  1386. }
  1387. //===----------------------------------------------------------------------===//
  1388. // Constants.
  1389. //===----------------------------------------------------------------------===//
  1390. /// ParseValID - Parse an abstract value that doesn't necessarily have a
  1391. /// type implied. For example, if we parse "4" we don't know what integer type
  1392. /// it has. The value will later be combined with its type and checked for
  1393. /// sanity.
  1394. bool LLParser::ParseValID(ValID &ID) {
  1395. ID.Loc = Lex.getLoc();
  1396. switch (Lex.getKind()) {
  1397. default: return TokError("expected value token");
  1398. case lltok::GlobalID: // @42
  1399. ID.UIntVal = Lex.getUIntVal();
  1400. ID.Kind = ValID::t_GlobalID;
  1401. break;
  1402. case lltok::GlobalVar: // @foo
  1403. ID.StrVal = Lex.getStrVal();
  1404. ID.Kind = ValID::t_GlobalName;
  1405. break;
  1406. case lltok::LocalVarID: // %42
  1407. ID.UIntVal = Lex.getUIntVal();
  1408. ID.Kind = ValID::t_LocalID;
  1409. break;
  1410. case lltok::LocalVar: // %foo
  1411. case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
  1412. ID.StrVal = Lex.getStrVal();
  1413. ID.Kind = ValID::t_LocalName;
  1414. break;
  1415. case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
  1416. ID.Kind = ValID::t_Constant;
  1417. Lex.Lex();
  1418. if (Lex.getKind() == lltok::lbrace) {
  1419. SmallVector<Value*, 16> Elts;
  1420. if (ParseMDNodeVector(Elts) ||
  1421. ParseToken(lltok::rbrace, "expected end of metadata node"))
  1422. return true;
  1423. ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
  1424. return false;
  1425. }
  1426. // Standalone metadata reference
  1427. // !{ ..., !42, ... }
  1428. unsigned MID = 0;
  1429. if (!ParseUInt32(MID)) {
  1430. std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
  1431. if (I != MetadataCache.end())
  1432. ID.ConstantVal = I->second;
  1433. else {
  1434. std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
  1435. FI = ForwardRefMDNodes.find(MID);
  1436. if (FI != ForwardRefMDNodes.end())
  1437. ID.ConstantVal = FI->second.first;
  1438. else {
  1439. // Create MDNode forward reference
  1440. SmallVector<Value *, 1> Elts;
  1441. std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
  1442. Elts.push_back(Context.getMDString(FwdRefName));
  1443. MDNode *FwdNode = Context.getMDNode(Elts.data(), Elts.size());
  1444. ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
  1445. ID.ConstantVal = FwdNode;
  1446. }
  1447. }
  1448. return false;
  1449. }
  1450. // MDString:
  1451. // ::= '!' STRINGCONSTANT
  1452. std::string Str;
  1453. if (ParseStringConstant(Str)) return true;
  1454. ID.ConstantVal = Context.getMDString(Str.data(), Str.data() + Str.size());
  1455. return false;
  1456. }
  1457. case lltok::APSInt:
  1458. ID.APSIntVal = Lex.getAPSIntVal();
  1459. ID.Kind = ValID::t_APSInt;
  1460. break;
  1461. case lltok::APFloat:
  1462. ID.APFloatVal = Lex.getAPFloatVal();
  1463. ID.Kind = ValID::t_APFloat;
  1464. break;
  1465. case lltok::kw_true:
  1466. ID.ConstantVal = Context.getConstantIntTrue();
  1467. ID.Kind = ValID::t_Constant;
  1468. break;
  1469. case lltok::kw_false:
  1470. ID.ConstantVal = Context.getConstantIntFalse();
  1471. ID.Kind = ValID::t_Constant;
  1472. break;
  1473. case lltok::kw_null: ID.Kind = ValID::t_Null; break;
  1474. case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
  1475. case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
  1476. case lltok::lbrace: {
  1477. // ValID ::= '{' ConstVector '}'
  1478. Lex.Lex();
  1479. SmallVector<Constant*, 16> Elts;
  1480. if (ParseGlobalValueVector(Elts) ||
  1481. ParseToken(lltok::rbrace, "expected end of struct constant"))
  1482. return true;
  1483. ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
  1484. ID.Kind = ValID::t_Constant;
  1485. return false;
  1486. }
  1487. case lltok::less: {
  1488. // ValID ::= '<' ConstVector '>' --> Vector.
  1489. // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
  1490. Lex.Lex();
  1491. bool isPackedStruct = EatIfPresent(lltok::lbrace);
  1492. SmallVector<Constant*, 16> Elts;
  1493. LocTy FirstEltLoc = Lex.getLoc();
  1494. if (ParseGlobalValueVector(Elts) ||
  1495. (isPackedStruct &&
  1496. ParseToken(lltok::rbrace, "expected end of packed struct")) ||
  1497. ParseToken(lltok::greater, "expected end of constant"))
  1498. return true;
  1499. if (isPackedStruct) {
  1500. ID.ConstantVal =
  1501. Context.getConstantStruct(Elts.data(), Elts.size(), true);
  1502. ID.Kind = ValID::t_Constant;
  1503. return false;
  1504. }
  1505. if (Elts.empty())
  1506. return Error(ID.Loc, "constant vector must not be empty");
  1507. if (!Elts[0]->getType()->isInteger() &&
  1508. !Elts[0]->getType()->isFloatingPoint())
  1509. return Error(FirstEltLoc,
  1510. "vector elements must have integer or floating point type");
  1511. // Verify that all the vector elements have the same type.
  1512. for (unsigned i = 1, e = Elts.size(); i != e; ++i)
  1513. if (Elts[i]->getType() != Elts[0]->getType())
  1514. return Error(FirstEltLoc,
  1515. "vector element #" + utostr(i) +
  1516. " is not of type '" + Elts[0]->getType()->getDescription());
  1517. ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
  1518. ID.Kind = ValID::t_Constant;
  1519. return false;
  1520. }
  1521. case lltok::lsquare: { // Array Constant
  1522. Lex.Lex();
  1523. SmallVector<Constant*, 16> Elts;
  1524. LocTy FirstEltLoc = Lex.getLoc();
  1525. if (ParseGlobalValueVector(Elts) ||
  1526. ParseToken(lltok::rsquare, "expected end of array constant"))
  1527. return true;
  1528. // Handle empty element.
  1529. if (Elts.empty()) {
  1530. // Use undef instead of an array because it's inconvenient to determine
  1531. // the element type at this point, there being no elements to examine.
  1532. ID.Kind = ValID::t_EmptyArray;
  1533. return false;
  1534. }
  1535. if (!Elts[0]->getType()->isFirstClassType())
  1536. return Error(FirstEltLoc, "invalid array element type: " +
  1537. Elts[0]->getType()->getDescription());
  1538. ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
  1539. // Verify all elements are correct type!
  1540. for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
  1541. if (Elts[i]->getType() != Elts[0]->getType())
  1542. return Error(FirstEltLoc,
  1543. "array element #" + utostr(i) +
  1544. " is not of type '" +Elts[0]->getType()->getDescription());
  1545. }
  1546. ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
  1547. ID.Kind = ValID::t_Constant;
  1548. return false;
  1549. }
  1550. case lltok::kw_c: // c "foo"
  1551. Lex.Lex();
  1552. ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
  1553. if (ParseToken(lltok::StringConstant, "expected string")) return true;
  1554. ID.Kind = ValID::t_Constant;
  1555. return false;
  1556. case lltok::kw_asm: {
  1557. // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
  1558. bool HasSideEffect;
  1559. Lex.Lex();
  1560. if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
  1561. ParseStringConstant(ID.StrVal) ||
  1562. ParseToken(lltok::comma, "expected comma in inline asm expression") ||
  1563. ParseToken(lltok::StringConstant, "expected constraint string"))
  1564. return true;
  1565. ID.StrVal2 = Lex.getStrVal();
  1566. ID.UIntVal = HasSideEffect;
  1567. ID.Kind = ValID::t_InlineAsm;
  1568. return false;
  1569. }
  1570. case lltok::kw_trunc:
  1571. case lltok::kw_zext:
  1572. case lltok::kw_sext:
  1573. case lltok::kw_fptrunc:
  1574. case lltok::kw_fpext:
  1575. case lltok::kw_bitcast:
  1576. case lltok::kw_uitofp:
  1577. case lltok::kw_sitofp:
  1578. case lltok::kw_fptoui:
  1579. case lltok::kw_fptosi:
  1580. case lltok::kw_inttoptr:
  1581. case lltok::kw_ptrtoint: {
  1582. unsigned Opc = Lex.getUIntVal();
  1583. PATypeHolder DestTy(Type::VoidTy);
  1584. Constant *SrcVal;
  1585. Lex.Lex();
  1586. if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
  1587. ParseGlobalTypeAndValue(SrcVal) ||
  1588. ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
  1589. ParseType(DestTy) ||
  1590. ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
  1591. return true;
  1592. if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
  1593. return Error(ID.Loc, "invalid cast opcode for cast from '" +
  1594. SrcVal->getType()->getDescription() + "' to '" +
  1595. DestTy->getDescription() + "'");
  1596. ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
  1597. SrcVal, DestTy);
  1598. ID.Kind = ValID::t_Constant;
  1599. return false;
  1600. }
  1601. case lltok::kw_extractvalue: {
  1602. Lex.Lex();
  1603. Constant *Val;
  1604. SmallVector<unsigned, 4> Indices;
  1605. if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
  1606. ParseGlobalTypeAndValue(Val) ||
  1607. ParseIndexList(Indices) ||
  1608. ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
  1609. return true;
  1610. if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
  1611. return Error(ID.Loc, "extractvalue operand must be array or struct");
  1612. if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
  1613. Indices.end()))
  1614. return Error(ID.Loc, "invalid indices for extractvalue");
  1615. ID.ConstantVal =
  1616. Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
  1617. ID.Kind = ValID::t_Constant;
  1618. return false;
  1619. }
  1620. case lltok::kw_insertvalue: {
  1621. Lex.Lex();
  1622. Constant *Val0, *Val1;
  1623. SmallVector<unsigned, 4> Indices;
  1624. if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
  1625. ParseGlobalTypeAndValue(Val0) ||
  1626. ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
  1627. ParseGlobalTypeAndValue(Val1) ||
  1628. ParseIndexList(Indices) ||
  1629. ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
  1630. return true;
  1631. if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
  1632. return Error(ID.Loc, "extractvalue operand must be array or struct");
  1633. if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
  1634. Indices.end()))
  1635. return Error(ID.Loc, "invalid indices for insertvalue");
  1636. ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
  1637. Indices.data(), Indices.size());
  1638. ID.Kind = ValID::t_Constant;
  1639. return false;
  1640. }
  1641. case lltok::kw_icmp:
  1642. case lltok::kw_fcmp: {
  1643. unsigned PredVal, Opc = Lex.getUIntVal();
  1644. Constant *Val0, *Val1;
  1645. Lex.Lex();
  1646. if (ParseCmpPredicate(PredVal, Opc) ||
  1647. ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
  1648. ParseGlobalTypeAndValue(Val0) ||
  1649. ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
  1650. ParseGlobalTypeAndValue(Val1) ||
  1651. ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
  1652. return true;
  1653. if (Val0->getType() != Val1->getType())
  1654. return Error(ID.Loc, "compare operands must have the same type");
  1655. CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
  1656. if (Opc == Instruction::FCmp) {
  1657. if (!Val0->getType()->isFPOrFPVector())
  1658. return Error(ID.Loc, "fcmp requires floating point operands");
  1659. ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
  1660. } else {
  1661. assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
  1662. if (!Val0->getType()->isIntOrIntVector() &&
  1663. !isa<PointerType>(Val0->getType()))
  1664. return Error(ID.Loc, "icmp requires pointer or integer operands");
  1665. ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
  1666. }
  1667. ID.Kind = ValID::t_Constant;
  1668. return false;
  1669. }
  1670. // Binary Operators.
  1671. case lltok::kw_add:
  1672. case lltok::kw_fadd:
  1673. case lltok::kw_sub:
  1674. case lltok::kw_fsub:
  1675. case lltok::kw_mul:
  1676. case lltok::kw_fmul:
  1677. case lltok::kw_udiv:
  1678. case lltok::kw_sdiv:
  1679. case lltok::kw_fdiv:
  1680. case lltok::kw_urem:
  1681. case lltok::kw_srem:
  1682. case lltok::kw_frem: {
  1683. unsigned Opc = Lex.getUIntVal();
  1684. Constant *Val0, *Val1;
  1685. Lex.Lex();
  1686. if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
  1687. ParseGlobalTypeAndValue(Val0) ||
  1688. ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
  1689. ParseGlobalTypeAndValue(Val1) ||
  1690. ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
  1691. return true;
  1692. if (Val0->getType() != Val1->getType())
  1693. return Error(ID.Loc, "operands of constexpr must have same type");
  1694. if (!Val0->getType()->isIntOrIntVector() &&
  1695. !Val0->getType()->isFPOrFPVector())
  1696. return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
  1697. ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
  1698. ID.Kind = ValID::t_Constant;
  1699. return false;
  1700. }
  1701. // Logical Operations
  1702. case lltok::kw_shl:
  1703. case lltok::kw_lshr:
  1704. case lltok::kw_ashr:
  1705. case lltok::kw_and:
  1706. case lltok::kw_or:
  1707. case lltok::kw_xor: {
  1708. unsigned Opc = Lex.getUIntVal();
  1709. Constant *Val0, *Val1;
  1710. Lex.Lex();
  1711. if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
  1712. ParseGlobalTypeAndValue(Val0) ||
  1713. ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
  1714. ParseGlobalTypeAndValue(Val1) ||
  1715. ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
  1716. return true;
  1717. if (Val0->getType() != Val1->getType())
  1718. return Error(ID.Loc, "operands of constexpr must have same type");
  1719. if (!Val0->getType()->isIntOrIntVector())
  1720. return Error(ID.Loc,
  1721. "constexpr requires integer or integer vector operands");
  1722. ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
  1723. ID.Kind = ValID::t_Constant;
  1724. return false;
  1725. }
  1726. case lltok::kw_getelementptr:
  1727. case lltok::kw_shufflevector:
  1728. case lltok::kw_insertelement:
  1729. case lltok::kw_extractelement:
  1730. case lltok::kw_select: {
  1731. unsigned Opc = Lex.getUIntVal();
  1732. SmallVector<Constant*, 16> Elts;
  1733. Lex.Lex();
  1734. if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
  1735. ParseGlobalValueVector(Elts) ||
  1736. ParseToken(lltok::rparen, "expected ')' in constantexpr"))
  1737. return true;
  1738. if (Opc == Instruction::GetElementPtr) {
  1739. if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
  1740. return Error(ID.Loc, "getelementptr requires pointer operand");
  1741. if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
  1742. (Value**)&Elts[1], Elts.size()-1))
  1743. return Error(ID.Loc, "invalid indices for getelementptr");
  1744. ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
  1745. &Elts[1], Elts.size()-1);
  1746. } else if (Opc == Instruction::Select) {
  1747. if (Elts.size() != 3)
  1748. return Error(ID.Loc, "expected three operands to select");
  1749. if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
  1750. Elts[2]))
  1751. return Error(ID.Loc, Reason);
  1752. ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
  1753. } else if (Opc == Instruction::ShuffleVector) {
  1754. if (Elts.size() != 3)
  1755. return Error(ID.Loc, "expected three operands to shufflevector");
  1756. if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
  1757. return Error(ID.Loc, "invalid operands to shufflevector");
  1758. ID.ConstantVal =
  1759. Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
  1760. } else if (Opc == Instruction::ExtractElement) {
  1761. if (Elts.size() != 2)
  1762. return Error(ID.Loc, "expected two operands to extractelement");
  1763. if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
  1764. return Error(ID.Loc, "invalid extractelement operands");
  1765. ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
  1766. } else {
  1767. assert(Opc == Instruction::InsertElement && "Unknown opcode");
  1768. if (Elts.size() != 3)
  1769. return Error(ID.Loc, "expected three operands to insertelement");
  1770. if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
  1771. return Error(ID.Loc, "invalid insertelement operands");
  1772. ID.ConstantVal =
  1773. Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
  1774. }
  1775. ID.Kind = ValID::t_Constant;
  1776. return false;
  1777. }
  1778. }
  1779. Lex.Lex();
  1780. return false;
  1781. }
  1782. /// ParseGlobalValue - Parse a global value with the specified type.
  1783. bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
  1784. V = 0;
  1785. ValID ID;
  1786. return ParseValID(ID) ||
  1787. ConvertGlobalValIDToValue(Ty, ID, V);
  1788. }
  1789. /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
  1790. /// constant.
  1791. bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
  1792. Constant *&V) {
  1793. if (isa<FunctionType>(Ty))
  1794. return Error(ID.Loc, "functions are not values, refer to them as pointers");
  1795. switch (ID.Kind) {
  1796. default: LLVM_UNREACHABLE("Unknown ValID!");
  1797. case ValID::t_LocalID:
  1798. case ValID::t_LocalName:
  1799. return Error(ID.Loc, "invalid use of function-local name");
  1800. case ValID::t_InlineAsm:
  1801. return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
  1802. case ValID::t_GlobalName:
  1803. V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
  1804. return V == 0;
  1805. case ValID::t_GlobalID:
  1806. V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
  1807. return V == 0;
  1808. case ValID::t_APSInt:
  1809. if (!isa<IntegerType>(Ty))
  1810. return Error(ID.Loc, "integer constant must have integer type");
  1811. ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
  1812. V = Context.getConstantInt(ID.APSIntVal);
  1813. return false;
  1814. case ValID::t_APFloat:
  1815. if (!Ty->isFloatingPoint() ||
  1816. !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
  1817. return Error(ID.Loc, "floating point constant invalid for type");
  1818. // The lexer has no type info, so builds all float and double FP constants
  1819. // as double. Fix this here. Long double does not need this.
  1820. if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
  1821. Ty == Type::FloatTy) {
  1822. bool Ignored;
  1823. ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
  1824. &Ignored);
  1825. }
  1826. V = Context.getConstantFP(ID.APFloatVal);
  1827. if (V->getType() != Ty)
  1828. return Error(ID.Loc, "floating point constant does not have type '" +
  1829. Ty->getDescription() + "'");
  1830. return false;
  1831. case ValID::t_Null:
  1832. if (!isa<PointerType>(Ty))
  1833. return Error(ID.Loc, "null must be a pointer type");
  1834. V = Context.getConstantPointerNull(cast<PointerType>(Ty));
  1835. return false;
  1836. case ValID::t_Undef:
  1837. // FIXME: LabelTy should not be a first-class type.
  1838. if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
  1839. !isa<OpaqueType>(Ty))
  1840. return Error(ID.Loc, "invalid type for undef constant");
  1841. V = Context.getUndef(Ty);
  1842. return false;
  1843. case ValID::t_EmptyArray:
  1844. if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
  1845. return Error(ID.Loc, "invalid empty array initializer");
  1846. V = Context.getUndef(Ty);
  1847. return false;
  1848. case ValID::t_Zero:
  1849. // FIXME: LabelTy should not be a first-class type.
  1850. if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
  1851. return Error(ID.Loc, "invalid type for null constant");
  1852. V = Context.getNullValue(Ty);
  1853. return false;
  1854. case ValID::t_Constant:
  1855. if (ID.ConstantVal->getType() != Ty)
  1856. return Error(ID.Loc, "constant expression type mismatch");
  1857. V = ID.ConstantVal;
  1858. return false;
  1859. }
  1860. }
  1861. bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
  1862. PATypeHolder Type(Type::VoidTy);
  1863. return ParseType(Type) ||
  1864. ParseGlobalValue(Type, V);
  1865. }
  1866. /// ParseGlobalValueVector
  1867. /// ::= /*empty*/
  1868. /// ::= TypeAndValue (',' TypeAndValue)*
  1869. bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
  1870. // Empty list.
  1871. if (Lex.getKind() == lltok::rbrace ||
  1872. Lex.getKind() == lltok::rsquare ||
  1873. Lex.getKind() == lltok::greater ||
  1874. Lex.getKind() == lltok::rparen)
  1875. return false;
  1876. Constant *C;
  1877. if (ParseGlobalTypeAndValue(C)) return true;
  1878. Elts.push_back(C);
  1879. while (EatIfPresent(lltok::comma)) {
  1880. if (ParseGlobalTypeAndValue(C)) return true;
  1881. Elts.push_back(C);
  1882. }
  1883. return false;
  1884. }
  1885. //===----------------------------------------------------------------------===//
  1886. // Function Parsing.
  1887. //===----------------------------------------------------------------------===//
  1888. bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
  1889. PerFunctionState &PFS) {
  1890. if (ID.Kind == ValID::t_LocalID)
  1891. V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
  1892. else if (ID.Kind == ValID::t_LocalName)
  1893. V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
  1894. else if (ID.Kind == ValID::t_InlineAsm) {
  1895. const PointerType *PTy = dyn_cast<PointerType>(Ty);
  1896. const FunctionType *FTy =
  1897. PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
  1898. if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
  1899. return Error(ID.Loc, "invalid type for inline asm constraint string");
  1900. V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
  1901. return false;
  1902. } else {
  1903. Constant *C;
  1904. if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
  1905. V = C;
  1906. return false;
  1907. }
  1908. return V == 0;
  1909. }
  1910. bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
  1911. V = 0;
  1912. ValID ID;
  1913. return ParseValID(ID) ||
  1914. ConvertValIDToValue(Ty, ID, V, PFS);
  1915. }
  1916. bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
  1917. PATypeHolder T(Type::VoidTy);
  1918. return ParseType(T) ||
  1919. ParseValue(T, V, PFS);
  1920. }
  1921. /// FunctionHeader
  1922. /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
  1923. /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
  1924. /// OptionalAlign OptGC
  1925. bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
  1926. // Parse the linkage.
  1927. LocTy LinkageLoc = Lex.getLoc();
  1928. unsigned Linkage;
  1929. unsigned Visibility, CC, RetAttrs;
  1930. PATypeHolder RetType(Type::VoidTy);
  1931. LocTy RetTypeLoc = Lex.getLoc();
  1932. if (ParseOptionalLinkage(Linkage) ||
  1933. ParseOptionalVisibility(Visibility) ||
  1934. ParseOptionalCallingConv(CC) ||
  1935. ParseOptionalAttrs(RetAttrs, 1) ||
  1936. ParseType(RetType, RetTypeLoc, true /*void allowed*/))
  1937. return true;
  1938. // Verify that the linkage is ok.
  1939. switch ((GlobalValue::LinkageTypes)Linkage) {
  1940. case GlobalValue::ExternalLinkage:
  1941. break; // always ok.
  1942. case GlobalValue::DLLImportLinkage:
  1943. case GlobalValue::ExternalWeakLinkage:
  1944. if (isDefine)
  1945. return Error(LinkageLoc, "invalid linkage for function definition");
  1946. break;
  1947. case GlobalValue::PrivateLinkage:
  1948. case GlobalValue::InternalLinkage:
  1949. case GlobalValue::AvailableExternallyLinkage:
  1950. case GlobalValue::LinkOnceAnyLinkage:
  1951. case GlobalValue::LinkOnceODRLinkage:
  1952. case GlobalValue::WeakAnyLinkage:
  1953. case GlobalValue::WeakODRLinkage:
  1954. case GlobalValue::DLLExportLinkage:
  1955. if (!isDefine)
  1956. return Error(LinkageLoc, "invalid linkage for function declaration");
  1957. break;
  1958. case GlobalValue::AppendingLinkage:
  1959. case GlobalValue::GhostLinkage:
  1960. case GlobalValue::CommonLinkage:
  1961. return Error(LinkageLoc, "invalid function linkage type");
  1962. }
  1963. if (!FunctionType::isValidReturnType(RetType) ||
  1964. isa<OpaqueType>(RetType))
  1965. return Error(RetTypeLoc, "invalid function return type");
  1966. LocTy NameLoc = Lex.getLoc();
  1967. std::string FunctionName;
  1968. if (Lex.getKind() == lltok::GlobalVar) {
  1969. FunctionName = Lex.getStrVal();
  1970. } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
  1971. unsigned NameID = Lex.getUIntVal();
  1972. if (NameID != NumberedVals.size())
  1973. return TokError("function expected to be numbered '%" +
  1974. utostr(NumberedVals.size()) + "'");
  1975. } else {
  1976. return TokError("expected function name");
  1977. }
  1978. Lex.Lex();
  1979. if (Lex.getKind() != lltok::lparen)
  1980. return TokError("expected '(' in function argument list");
  1981. std::vector<ArgInfo> ArgList;
  1982. bool isVarArg;
  1983. unsigned FuncAttrs;
  1984. std::string Section;
  1985. unsigned Alignment;
  1986. std::string GC;
  1987. if (ParseArgumentList(ArgList, isVarArg, false) ||
  1988. ParseOptionalAttrs(FuncAttrs, 2) ||
  1989. (EatIfPresent(lltok::kw_section) &&
  1990. ParseStringConstant(Section)) ||
  1991. ParseOptionalAlignment(Alignment) ||
  1992. (EatIfPresent(lltok::kw_gc) &&
  1993. ParseStringConstant(GC)))
  1994. return true;
  1995. // If the alignment was parsed as an attribute, move to the alignment field.
  1996. if (FuncAttrs & Attribute::Alignment) {
  1997. Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
  1998. FuncAttrs &= ~Attribute::Alignment;
  1999. }
  2000. // Okay, if we got here, the function is syntactically valid. Convert types
  2001. // and do semantic checks.
  2002. std::vector<const Type*> ParamTypeList;
  2003. SmallVector<AttributeWithIndex, 8> Attrs;
  2004. // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
  2005. // attributes.
  2006. unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
  2007. if (FuncAttrs & ObsoleteFuncAttrs) {
  2008. RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
  2009. FuncAttrs &= ~ObsoleteFuncAttrs;
  2010. }
  2011. if (RetAttrs != Attribute::None)
  2012. Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
  2013. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  2014. ParamTypeList.push_back(ArgList[i].Type);
  2015. if (ArgList[i].Attrs != Attribute::None)
  2016. Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
  2017. }
  2018. if (FuncAttrs != Attribute::None)
  2019. Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
  2020. AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
  2021. if (PAL.paramHasAttr(1, Attribute::StructRet) &&
  2022. RetType != Type::VoidTy)
  2023. return Error(RetTypeLoc, "functions with 'sret' argument must return void");
  2024. const FunctionType *FT =
  2025. Context.getFunctionType(RetType, ParamTypeList, isVarArg);
  2026. const PointerType *PFT = Context.getPointerTypeUnqual(FT);
  2027. Fn = 0;
  2028. if (!FunctionName.empty()) {
  2029. // If this was a definition of a forward reference, remove the definition
  2030. // from the forward reference table and fill in the forward ref.
  2031. std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
  2032. ForwardRefVals.find(FunctionName);
  2033. if (FRVI != ForwardRefVals.end()) {
  2034. Fn = M->getFunction(FunctionName);
  2035. ForwardRefVals.erase(FRVI);
  2036. } else if ((Fn = M->getFunction(FunctionName))) {
  2037. // If this function already exists in the symbol table, then it is
  2038. // multiply defined. We accept a few cases for old backwards compat.
  2039. // FIXME: Remove this stuff for LLVM 3.0.
  2040. if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
  2041. (!Fn->isDeclaration() && isDefine)) {
  2042. // If the redefinition has different type or different attributes,
  2043. // reject it. If both have bodies, reject it.
  2044. return Error(NameLoc, "invalid redefinition of function '" +
  2045. FunctionName + "'");
  2046. } else if (Fn->isDeclaration()) {
  2047. // Make sure to strip off any argument names so we can't get conflicts.
  2048. for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
  2049. AI != AE; ++AI)
  2050. AI->setName("");
  2051. }
  2052. }
  2053. } else if (FunctionName.empty()) {
  2054. // If this is a definition of a forward referenced function, make sure the
  2055. // types agree.
  2056. std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
  2057. = ForwardRefValIDs.find(NumberedVals.size());
  2058. if (I != ForwardRefValIDs.end()) {
  2059. Fn = cast<Function>(I->second.first);
  2060. if (Fn->getType() != PFT)
  2061. return Error(NameLoc, "type of definition and forward reference of '@" +
  2062. utostr(NumberedVals.size()) +"' disagree");
  2063. ForwardRefValIDs.erase(I);
  2064. }
  2065. }
  2066. if (Fn == 0)
  2067. Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
  2068. else // Move the forward-reference to the correct spot in the module.
  2069. M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
  2070. if (FunctionName.empty())
  2071. NumberedVals.push_back(Fn);
  2072. Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
  2073. Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
  2074. Fn->setCallingConv(CC);
  2075. Fn->setAttributes(PAL);
  2076. Fn->setAlignment(Alignment);
  2077. Fn->setSection(Section);
  2078. if (!GC.empty()) Fn->setGC(GC.c_str());
  2079. // Add all of the arguments we parsed to the function.
  2080. Function::arg_iterator ArgIt = Fn->arg_begin();
  2081. for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
  2082. // If the argument has a name, insert it into the argument symbol table.
  2083. if (ArgList[i].Name.empty()) continue;
  2084. // Set the name, if it conflicted, it will be auto-renamed.
  2085. ArgIt->setName(ArgList[i].Name);
  2086. if (ArgIt->getNameStr() != ArgList[i].Name)
  2087. return Error(ArgList[i].Loc, "redefinition of argument '%" +
  2088. ArgList[i].Name + "'");
  2089. }
  2090. return false;
  2091. }
  2092. /// ParseFunctionBody
  2093. /// ::= '{' BasicBlock+ '}'
  2094. /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
  2095. ///
  2096. bool LLParser::ParseFunctionBody(Function &Fn) {
  2097. if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
  2098. return TokError("expected '{' in function body");
  2099. Lex.Lex(); // eat the {.
  2100. PerFunctionState PFS(*this, Fn);
  2101. while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
  2102. if (ParseBasicBlock(PFS)) return true;
  2103. // Eat the }.
  2104. Lex.Lex();
  2105. // Verify function is ok.
  2106. return PFS.VerifyFunctionComplete();
  2107. }
  2108. /// ParseBasicBlock
  2109. /// ::= LabelStr? Instruction*
  2110. bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
  2111. // If this basic block starts out with a name, remember it.
  2112. std::string Name;
  2113. LocTy NameLoc = Lex.getLoc();
  2114. if (Lex.getKind() == lltok::LabelStr) {
  2115. Name = Lex.getStrVal();
  2116. Lex.Lex();
  2117. }
  2118. BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
  2119. if (BB == 0) return true;
  2120. std::string NameStr;
  2121. // Parse the instructions in this block until we get a terminator.
  2122. Instruction *Inst;
  2123. do {
  2124. // This instruction may have three possibilities for a name: a) none
  2125. // specified, b) name specified "%foo =", c) number specified: "%4 =".
  2126. LocTy NameLoc = Lex.getLoc();
  2127. int NameID = -1;
  2128. NameStr = "";
  2129. if (Lex.getKind() == lltok::LocalVarID) {
  2130. NameID = Lex.getUIntVal();
  2131. Lex.Lex();
  2132. if (ParseToken(lltok::equal, "expected '=' after instruction id"))
  2133. return true;
  2134. } else if (Lex.getKind() == lltok::LocalVar ||
  2135. // FIXME: REMOVE IN LLVM 3.0
  2136. Lex.getKind() == lltok::StringConstant) {
  2137. NameStr = Lex.getStrVal();
  2138. Lex.Lex();
  2139. if (ParseToken(lltok::equal, "expected '=' after instruction name"))
  2140. return true;
  2141. }
  2142. if (ParseInstruction(Inst, BB, PFS)) return true;
  2143. BB->getInstList().push_back(Inst);
  2144. // Set the name on the instruction.
  2145. if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
  2146. } while (!isa<TerminatorInst>(Inst));
  2147. return false;
  2148. }
  2149. //===----------------------------------------------------------------------===//
  2150. // Instruction Parsing.
  2151. //===----------------------------------------------------------------------===//
  2152. /// ParseInstruction - Parse one of the many different instructions.
  2153. ///
  2154. bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
  2155. PerFunctionState &PFS) {
  2156. lltok::Kind Token = Lex.getKind();
  2157. if (Token == lltok::Eof)
  2158. return TokError("found end of file when expecting more instructions");
  2159. LocTy Loc = Lex.getLoc();
  2160. unsigned KeywordVal = Lex.getUIntVal();
  2161. Lex.Lex(); // Eat the keyword.
  2162. switch (Token) {
  2163. default: return Error(Loc, "expected instruction opcode");
  2164. // Terminator Instructions.
  2165. case lltok::kw_unwind: Inst = new UnwindInst(); return false;
  2166. case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
  2167. case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
  2168. case lltok::kw_br: return ParseBr(Inst, PFS);
  2169. case lltok::kw_switch: return ParseSwitch(Inst, PFS);
  2170. case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
  2171. // Binary Operators.
  2172. case lltok::kw_add:
  2173. case lltok::kw_sub:
  2174. case lltok::kw_mul:
  2175. // API compatibility: Accept either integer or floating-point types.
  2176. return ParseArithmetic(Inst, PFS, KeywordVal, 0);
  2177. case lltok::kw_fadd:
  2178. case lltok::kw_fsub:
  2179. case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
  2180. case lltok::kw_udiv:
  2181. case lltok::kw_sdiv:
  2182. case lltok::kw_urem:
  2183. case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
  2184. case lltok::kw_fdiv:
  2185. case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
  2186. case lltok::kw_shl:
  2187. case lltok::kw_lshr:
  2188. case lltok::kw_ashr:
  2189. case lltok::kw_and:
  2190. case lltok::kw_or:
  2191. case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
  2192. case lltok::kw_icmp:
  2193. case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
  2194. // Casts.
  2195. case lltok::kw_trunc:
  2196. case lltok::kw_zext:
  2197. case lltok::kw_sext:
  2198. case lltok::kw_fptrunc:
  2199. case lltok::kw_fpext:
  2200. case lltok::kw_bitcast:
  2201. case lltok::kw_uitofp:
  2202. case lltok::kw_sitofp:
  2203. case lltok::kw_fptoui:
  2204. case lltok::kw_fptosi:
  2205. case lltok::kw_inttoptr:
  2206. case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
  2207. // Other.
  2208. case lltok::kw_select: return ParseSelect(Inst, PFS);
  2209. case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
  2210. case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
  2211. case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
  2212. case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
  2213. case lltok::kw_phi: return ParsePHI(Inst, PFS);
  2214. case lltok::kw_call: return ParseCall(Inst, PFS, false);
  2215. case lltok::kw_tail: return ParseCall(Inst, PFS, true);
  2216. // Memory.
  2217. case lltok::kw_alloca:
  2218. case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
  2219. case lltok::kw_free: return ParseFree(Inst, PFS);
  2220. case lltok::kw_load: return ParseLoad(Inst, PFS, false);
  2221. case lltok::kw_store: return ParseStore(Inst, PFS, false);
  2222. case lltok::kw_volatile:
  2223. if (EatIfPresent(lltok::kw_load))
  2224. return ParseLoad(Inst, PFS, true);
  2225. else if (EatIfPresent(lltok::kw_store))
  2226. return ParseStore(Inst, PFS, true);
  2227. else
  2228. return TokError("expected 'load' or 'store'");
  2229. case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
  2230. case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
  2231. case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
  2232. case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
  2233. }
  2234. }
  2235. /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
  2236. bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
  2237. if (Opc == Instruction::FCmp) {
  2238. switch (Lex.getKind()) {
  2239. default: TokError("expected fcmp predicate (e.g. 'oeq')");
  2240. case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
  2241. case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
  2242. case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
  2243. case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
  2244. case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
  2245. case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
  2246. case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
  2247. case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
  2248. case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
  2249. case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
  2250. case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
  2251. case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
  2252. case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
  2253. case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
  2254. case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
  2255. case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
  2256. }
  2257. } else {
  2258. switch (Lex.getKind()) {
  2259. default: TokError("expected icmp predicate (e.g. 'eq')");
  2260. case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
  2261. case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
  2262. case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
  2263. case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
  2264. case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
  2265. case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
  2266. case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
  2267. case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
  2268. case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
  2269. case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
  2270. }
  2271. }
  2272. Lex.Lex();
  2273. return false;
  2274. }
  2275. //===----------------------------------------------------------------------===//
  2276. // Terminator Instructions.
  2277. //===----------------------------------------------------------------------===//
  2278. /// ParseRet - Parse a return instruction.
  2279. /// ::= 'ret' void
  2280. /// ::= 'ret' TypeAndValue
  2281. /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
  2282. bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
  2283. PerFunctionState &PFS) {
  2284. PATypeHolder Ty(Type::VoidTy);
  2285. if (ParseType(Ty, true /*void allowed*/)) return true;
  2286. if (Ty == Type::VoidTy) {
  2287. Inst = ReturnInst::Create();
  2288. return false;
  2289. }
  2290. Value *RV;
  2291. if (ParseValue(Ty, RV, PFS)) return true;
  2292. // The normal case is one return value.
  2293. if (Lex.getKind() == lltok::comma) {
  2294. // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
  2295. // of 'ret {i32,i32} {i32 1, i32 2}'
  2296. SmallVector<Value*, 8> RVs;
  2297. RVs.push_back(RV);
  2298. while (EatIfPresent(lltok::comma)) {
  2299. if (ParseTypeAndValue(RV, PFS)) return true;
  2300. RVs.push_back(RV);
  2301. }
  2302. RV = Context.getUndef(PFS.getFunction().getReturnType());
  2303. for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
  2304. Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
  2305. BB->getInstList().push_back(I);
  2306. RV = I;
  2307. }
  2308. }
  2309. Inst = ReturnInst::Create(RV);
  2310. return false;
  2311. }
  2312. /// ParseBr
  2313. /// ::= 'br' TypeAndValue
  2314. /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  2315. bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
  2316. LocTy Loc, Loc2;
  2317. Value *Op0, *Op1, *Op2;
  2318. if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
  2319. if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
  2320. Inst = BranchInst::Create(BB);
  2321. return false;
  2322. }
  2323. if (Op0->getType() != Type::Int1Ty)
  2324. return Error(Loc, "branch condition must have 'i1' type");
  2325. if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
  2326. ParseTypeAndValue(Op1, Loc, PFS) ||
  2327. ParseToken(lltok::comma, "expected ',' after true destination") ||
  2328. ParseTypeAndValue(Op2, Loc2, PFS))
  2329. return true;
  2330. if (!isa<BasicBlock>(Op1))
  2331. return Error(Loc, "true destination of branch must be a basic block");
  2332. if (!isa<BasicBlock>(Op2))
  2333. return Error(Loc2, "true destination of branch must be a basic block");
  2334. Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
  2335. return false;
  2336. }
  2337. /// ParseSwitch
  2338. /// Instruction
  2339. /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
  2340. /// JumpTable
  2341. /// ::= (TypeAndValue ',' TypeAndValue)*
  2342. bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
  2343. LocTy CondLoc, BBLoc;
  2344. Value *Cond, *DefaultBB;
  2345. if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
  2346. ParseToken(lltok::comma, "expected ',' after switch condition") ||
  2347. ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
  2348. ParseToken(lltok::lsquare, "expected '[' with switch table"))
  2349. return true;
  2350. if (!isa<IntegerType>(Cond->getType()))
  2351. return Error(CondLoc, "switch condition must have integer type");
  2352. if (!isa<BasicBlock>(DefaultBB))
  2353. return Error(BBLoc, "default destination must be a basic block");
  2354. // Parse the jump table pairs.
  2355. SmallPtrSet<Value*, 32> SeenCases;
  2356. SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
  2357. while (Lex.getKind() != lltok::rsquare) {
  2358. Value *Constant, *DestBB;
  2359. if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
  2360. ParseToken(lltok::comma, "expected ',' after case value") ||
  2361. ParseTypeAndValue(DestBB, BBLoc, PFS))
  2362. return true;
  2363. if (!SeenCases.insert(Constant))
  2364. return Error(CondLoc, "duplicate case value in switch");
  2365. if (!isa<ConstantInt>(Constant))
  2366. return Error(CondLoc, "case value is not a constant integer");
  2367. if (!isa<BasicBlock>(DestBB))
  2368. return Error(BBLoc, "case destination is not a basic block");
  2369. Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
  2370. cast<BasicBlock>(DestBB)));
  2371. }
  2372. Lex.Lex(); // Eat the ']'.
  2373. SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
  2374. Table.size());
  2375. for (unsigned i = 0, e = Table.size(); i != e; ++i)
  2376. SI->addCase(Table[i].first, Table[i].second);
  2377. Inst = SI;
  2378. return false;
  2379. }
  2380. /// ParseInvoke
  2381. /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
  2382. /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
  2383. bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
  2384. LocTy CallLoc = Lex.getLoc();
  2385. unsigned CC, RetAttrs, FnAttrs;
  2386. PATypeHolder RetType(Type::VoidTy);
  2387. LocTy RetTypeLoc;
  2388. ValID CalleeID;
  2389. SmallVector<ParamInfo, 16> ArgList;
  2390. Value *NormalBB, *UnwindBB;
  2391. if (ParseOptionalCallingConv(CC) ||
  2392. ParseOptionalAttrs(RetAttrs, 1) ||
  2393. ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
  2394. ParseValID(CalleeID) ||
  2395. ParseParameterList(ArgList, PFS) ||
  2396. ParseOptionalAttrs(FnAttrs, 2) ||
  2397. ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
  2398. ParseTypeAndValue(NormalBB, PFS) ||
  2399. ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
  2400. ParseTypeAndValue(UnwindBB, PFS))
  2401. return true;
  2402. if (!isa<BasicBlock>(NormalBB))
  2403. return Error(CallLoc, "normal destination is not a basic block");
  2404. if (!isa<BasicBlock>(UnwindBB))
  2405. return Error(CallLoc, "unwind destination is not a basic block");
  2406. // If RetType is a non-function pointer type, then this is the short syntax
  2407. // for the call, which means that RetType is just the return type. Infer the
  2408. // rest of the function argument types from the arguments that are present.
  2409. const PointerType *PFTy = 0;
  2410. const FunctionType *Ty = 0;
  2411. if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
  2412. !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
  2413. // Pull out the types of all of the arguments...
  2414. std::vector<const Type*> ParamTypes;
  2415. for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
  2416. ParamTypes.push_back(ArgList[i].V->getType());
  2417. if (!FunctionType::isValidReturnType(RetType))
  2418. return Error(RetTypeLoc, "Invalid result type for LLVM function");
  2419. Ty = Context.getFunctionType(RetType, ParamTypes, false);
  2420. PFTy = Context.getPointerTypeUnqual(Ty);
  2421. }
  2422. // Look up the callee.
  2423. Value *Callee;
  2424. if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
  2425. // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
  2426. // function attributes.
  2427. unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
  2428. if (FnAttrs & ObsoleteFuncAttrs) {
  2429. RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
  2430. FnAttrs &= ~ObsoleteFuncAttrs;
  2431. }
  2432. // Set up the Attributes for the function.
  2433. SmallVector<AttributeWithIndex, 8> Attrs;
  2434. if (RetAttrs != Attribute::None)
  2435. Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
  2436. SmallVector<Value*, 8> Args;
  2437. // Loop through FunctionType's arguments and ensure they are specified
  2438. // correctly. Also, gather any parameter attributes.
  2439. FunctionType::param_iterator I = Ty->param_begin();
  2440. FunctionType::param_iterator E = Ty->param_end();
  2441. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  2442. const Type *ExpectedTy = 0;
  2443. if (I != E) {
  2444. ExpectedTy = *I++;
  2445. } else if (!Ty->isVarArg()) {
  2446. return Error(ArgList[i].Loc, "too many arguments specified");
  2447. }
  2448. if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
  2449. return Error(ArgList[i].Loc, "argument is not of expected type '" +
  2450. ExpectedTy->getDescription() + "'");
  2451. Args.push_back(ArgList[i].V);
  2452. if (ArgList[i].Attrs != Attribute::None)
  2453. Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
  2454. }
  2455. if (I != E)
  2456. return Error(CallLoc, "not enough parameters specified for call");
  2457. if (FnAttrs != Attribute::None)
  2458. Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
  2459. // Finish off the Attributes and check them
  2460. AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
  2461. InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
  2462. cast<BasicBlock>(UnwindBB),
  2463. Args.begin(), Args.end());
  2464. II->setCallingConv(CC);
  2465. II->setAttributes(PAL);
  2466. Inst = II;
  2467. return false;
  2468. }
  2469. //===----------------------------------------------------------------------===//
  2470. // Binary Operators.
  2471. //===----------------------------------------------------------------------===//
  2472. /// ParseArithmetic
  2473. /// ::= ArithmeticOps TypeAndValue ',' Value
  2474. ///
  2475. /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
  2476. /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
  2477. bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
  2478. unsigned Opc, unsigned OperandType) {
  2479. LocTy Loc; Value *LHS, *RHS;
  2480. if (ParseTypeAndValue(LHS, Loc, PFS) ||
  2481. ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
  2482. ParseValue(LHS->getType(), RHS, PFS))
  2483. return true;
  2484. bool Valid;
  2485. switch (OperandType) {
  2486. default: LLVM_UNREACHABLE("Unknown operand type!");
  2487. case 0: // int or FP.
  2488. Valid = LHS->getType()->isIntOrIntVector() ||
  2489. LHS->getType()->isFPOrFPVector();
  2490. break;
  2491. case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
  2492. case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
  2493. }
  2494. if (!Valid)
  2495. return Error(Loc, "invalid operand type for instruction");
  2496. Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  2497. return false;
  2498. }
  2499. /// ParseLogical
  2500. /// ::= ArithmeticOps TypeAndValue ',' Value {
  2501. bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
  2502. unsigned Opc) {
  2503. LocTy Loc; Value *LHS, *RHS;
  2504. if (ParseTypeAndValue(LHS, Loc, PFS) ||
  2505. ParseToken(lltok::comma, "expected ',' in logical operation") ||
  2506. ParseValue(LHS->getType(), RHS, PFS))
  2507. return true;
  2508. if (!LHS->getType()->isIntOrIntVector())
  2509. return Error(Loc,"instruction requires integer or integer vector operands");
  2510. Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  2511. return false;
  2512. }
  2513. /// ParseCompare
  2514. /// ::= 'icmp' IPredicates TypeAndValue ',' Value
  2515. /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
  2516. bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
  2517. unsigned Opc) {
  2518. // Parse the integer/fp comparison predicate.
  2519. LocTy Loc;
  2520. unsigned Pred;
  2521. Value *LHS, *RHS;
  2522. if (ParseCmpPredicate(Pred, Opc) ||
  2523. ParseTypeAndValue(LHS, Loc, PFS) ||
  2524. ParseToken(lltok::comma, "expected ',' after compare value") ||
  2525. ParseValue(LHS->getType(), RHS, PFS))
  2526. return true;
  2527. if (Opc == Instruction::FCmp) {
  2528. if (!LHS->getType()->isFPOrFPVector())
  2529. return Error(Loc, "fcmp requires floating point operands");
  2530. Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
  2531. } else {
  2532. assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
  2533. if (!LHS->getType()->isIntOrIntVector() &&
  2534. !isa<PointerType>(LHS->getType()))
  2535. return Error(Loc, "icmp requires integer operands");
  2536. Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
  2537. }
  2538. return false;
  2539. }
  2540. //===----------------------------------------------------------------------===//
  2541. // Other Instructions.
  2542. //===----------------------------------------------------------------------===//
  2543. /// ParseCast
  2544. /// ::= CastOpc TypeAndValue 'to' Type
  2545. bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
  2546. unsigned Opc) {
  2547. LocTy Loc; Value *Op;
  2548. PATypeHolder DestTy(Type::VoidTy);
  2549. if (ParseTypeAndValue(Op, Loc, PFS) ||
  2550. ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
  2551. ParseType(DestTy))
  2552. return true;
  2553. if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
  2554. CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
  2555. return Error(Loc, "invalid cast opcode for cast from '" +
  2556. Op->getType()->getDescription() + "' to '" +
  2557. DestTy->getDescription() + "'");
  2558. }
  2559. Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
  2560. return false;
  2561. }
  2562. /// ParseSelect
  2563. /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  2564. bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
  2565. LocTy Loc;
  2566. Value *Op0, *Op1, *Op2;
  2567. if (ParseTypeAndValue(Op0, Loc, PFS) ||
  2568. ParseToken(lltok::comma, "expected ',' after select condition") ||
  2569. ParseTypeAndValue(Op1, PFS) ||
  2570. ParseToken(lltok::comma, "expected ',' after select value") ||
  2571. ParseTypeAndValue(Op2, PFS))
  2572. return true;
  2573. if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
  2574. return Error(Loc, Reason);
  2575. Inst = SelectInst::Create(Op0, Op1, Op2);
  2576. return false;
  2577. }
  2578. /// ParseVA_Arg
  2579. /// ::= 'va_arg' TypeAndValue ',' Type
  2580. bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
  2581. Value *Op;
  2582. PATypeHolder EltTy(Type::VoidTy);
  2583. LocTy TypeLoc;
  2584. if (ParseTypeAndValue(Op, PFS) ||
  2585. ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
  2586. ParseType(EltTy, TypeLoc))
  2587. return true;
  2588. if (!EltTy->isFirstClassType())
  2589. return Error(TypeLoc, "va_arg requires operand with first class type");
  2590. Inst = new VAArgInst(Op, EltTy);
  2591. return false;
  2592. }
  2593. /// ParseExtractElement
  2594. /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
  2595. bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
  2596. LocTy Loc;
  2597. Value *Op0, *Op1;
  2598. if (ParseTypeAndValue(Op0, Loc, PFS) ||
  2599. ParseToken(lltok::comma, "expected ',' after extract value") ||
  2600. ParseTypeAndValue(Op1, PFS))
  2601. return true;
  2602. if (!ExtractElementInst::isValidOperands(Op0, Op1))
  2603. return Error(Loc, "invalid extractelement operands");
  2604. Inst = new ExtractElementInst(Op0, Op1);
  2605. return false;
  2606. }
  2607. /// ParseInsertElement
  2608. /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  2609. bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
  2610. LocTy Loc;
  2611. Value *Op0, *Op1, *Op2;
  2612. if (ParseTypeAndValue(Op0, Loc, PFS) ||
  2613. ParseToken(lltok::comma, "expected ',' after insertelement value") ||
  2614. ParseTypeAndValue(Op1, PFS) ||
  2615. ParseToken(lltok::comma, "expected ',' after insertelement value") ||
  2616. ParseTypeAndValue(Op2, PFS))
  2617. return true;
  2618. if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
  2619. return Error(Loc, "invalid extractelement operands");
  2620. Inst = InsertElementInst::Create(Op0, Op1, Op2);
  2621. return false;
  2622. }
  2623. /// ParseShuffleVector
  2624. /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  2625. bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
  2626. LocTy Loc;
  2627. Value *Op0, *Op1, *Op2;
  2628. if (ParseTypeAndValue(Op0, Loc, PFS) ||
  2629. ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
  2630. ParseTypeAndValue(Op1, PFS) ||
  2631. ParseToken(lltok::comma, "expected ',' after shuffle value") ||
  2632. ParseTypeAndValue(Op2, PFS))
  2633. return true;
  2634. if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
  2635. return Error(Loc, "invalid extractelement operands");
  2636. Inst = new ShuffleVectorInst(Op0, Op1, Op2);
  2637. return false;
  2638. }
  2639. /// ParsePHI
  2640. /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
  2641. bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
  2642. PATypeHolder Ty(Type::VoidTy);
  2643. Value *Op0, *Op1;
  2644. LocTy TypeLoc = Lex.getLoc();
  2645. if (ParseType(Ty) ||
  2646. ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
  2647. ParseValue(Ty, Op0, PFS) ||
  2648. ParseToken(lltok::comma, "expected ',' after insertelement value") ||
  2649. ParseValue(Type::LabelTy, Op1, PFS) ||
  2650. ParseToken(lltok::rsquare, "expected ']' in phi value list"))
  2651. return true;
  2652. SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
  2653. while (1) {
  2654. PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
  2655. if (!EatIfPresent(lltok::comma))
  2656. break;
  2657. if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
  2658. ParseValue(Ty, Op0, PFS) ||
  2659. ParseToken(lltok::comma, "expected ',' after insertelement value") ||
  2660. ParseValue(Type::LabelTy, Op1, PFS) ||
  2661. ParseToken(lltok::rsquare, "expected ']' in phi value list"))
  2662. return true;
  2663. }
  2664. if (!Ty->isFirstClassType())
  2665. return Error(TypeLoc, "phi node must have first class type");
  2666. PHINode *PN = PHINode::Create(Ty);
  2667. PN->reserveOperandSpace(PHIVals.size());
  2668. for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
  2669. PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
  2670. Inst = PN;
  2671. return false;
  2672. }
  2673. /// ParseCall
  2674. /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
  2675. /// ParameterList OptionalAttrs
  2676. bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
  2677. bool isTail) {
  2678. unsigned CC, RetAttrs, FnAttrs;
  2679. PATypeHolder RetType(Type::VoidTy);
  2680. LocTy RetTypeLoc;
  2681. ValID CalleeID;
  2682. SmallVector<ParamInfo, 16> ArgList;
  2683. LocTy CallLoc = Lex.getLoc();
  2684. if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
  2685. ParseOptionalCallingConv(CC) ||
  2686. ParseOptionalAttrs(RetAttrs, 1) ||
  2687. ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
  2688. ParseValID(CalleeID) ||
  2689. ParseParameterList(ArgList, PFS) ||
  2690. ParseOptionalAttrs(FnAttrs, 2))
  2691. return true;
  2692. // If RetType is a non-function pointer type, then this is the short syntax
  2693. // for the call, which means that RetType is just the return type. Infer the
  2694. // rest of the function argument types from the arguments that are present.
  2695. const PointerType *PFTy = 0;
  2696. const FunctionType *Ty = 0;
  2697. if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
  2698. !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
  2699. // Pull out the types of all of the arguments...
  2700. std::vector<const Type*> ParamTypes;
  2701. for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
  2702. ParamTypes.push_back(ArgList[i].V->getType());
  2703. if (!FunctionType::isValidReturnType(RetType))
  2704. return Error(RetTypeLoc, "Invalid result type for LLVM function");
  2705. Ty = Context.getFunctionType(RetType, ParamTypes, false);
  2706. PFTy = Context.getPointerTypeUnqual(Ty);
  2707. }
  2708. // Look up the callee.
  2709. Value *Callee;
  2710. if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
  2711. // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
  2712. // function attributes.
  2713. unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
  2714. if (FnAttrs & ObsoleteFuncAttrs) {
  2715. RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
  2716. FnAttrs &= ~ObsoleteFuncAttrs;
  2717. }
  2718. // Set up the Attributes for the function.
  2719. SmallVector<AttributeWithIndex, 8> Attrs;
  2720. if (RetAttrs != Attribute::None)
  2721. Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
  2722. SmallVector<Value*, 8> Args;
  2723. // Loop through FunctionType's arguments and ensure they are specified
  2724. // correctly. Also, gather any parameter attributes.
  2725. FunctionType::param_iterator I = Ty->param_begin();
  2726. FunctionType::param_iterator E = Ty->param_end();
  2727. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  2728. const Type *ExpectedTy = 0;
  2729. if (I != E) {
  2730. ExpectedTy = *I++;
  2731. } else if (!Ty->isVarArg()) {
  2732. return Error(ArgList[i].Loc, "too many arguments specified");
  2733. }
  2734. if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
  2735. return Error(ArgList[i].Loc, "argument is not of expected type '" +
  2736. ExpectedTy->getDescription() + "'");
  2737. Args.push_back(ArgList[i].V);
  2738. if (ArgList[i].Attrs != Attribute::None)
  2739. Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
  2740. }
  2741. if (I != E)
  2742. return Error(CallLoc, "not enough parameters specified for call");
  2743. if (FnAttrs != Attribute::None)
  2744. Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
  2745. // Finish off the Attributes and check them
  2746. AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
  2747. CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
  2748. CI->setTailCall(isTail);
  2749. CI->setCallingConv(CC);
  2750. CI->setAttributes(PAL);
  2751. Inst = CI;
  2752. return false;
  2753. }
  2754. //===----------------------------------------------------------------------===//
  2755. // Memory Instructions.
  2756. //===----------------------------------------------------------------------===//
  2757. /// ParseAlloc
  2758. /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
  2759. /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
  2760. bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
  2761. unsigned Opc) {
  2762. PATypeHolder Ty(Type::VoidTy);
  2763. Value *Size = 0;
  2764. LocTy SizeLoc;
  2765. unsigned Alignment = 0;
  2766. if (ParseType(Ty)) return true;
  2767. if (EatIfPresent(lltok::comma)) {
  2768. if (Lex.getKind() == lltok::kw_align) {
  2769. if (ParseOptionalAlignment(Alignment)) return true;
  2770. } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
  2771. ParseOptionalCommaAlignment(Alignment)) {
  2772. return true;
  2773. }
  2774. }
  2775. if (Size && Size->getType() != Type::Int32Ty)
  2776. return Error(SizeLoc, "element count must be i32");
  2777. if (Opc == Instruction::Malloc)
  2778. Inst = new MallocInst(Ty, Size, Alignment);
  2779. else
  2780. Inst = new AllocaInst(Ty, Size, Alignment);
  2781. return false;
  2782. }
  2783. /// ParseFree
  2784. /// ::= 'free' TypeAndValue
  2785. bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
  2786. Value *Val; LocTy Loc;
  2787. if (ParseTypeAndValue(Val, Loc, PFS)) return true;
  2788. if (!isa<PointerType>(Val->getType()))
  2789. return Error(Loc, "operand to free must be a pointer");
  2790. Inst = new FreeInst(Val);
  2791. return false;
  2792. }
  2793. /// ParseLoad
  2794. /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
  2795. bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
  2796. bool isVolatile) {
  2797. Value *Val; LocTy Loc;
  2798. unsigned Alignment;
  2799. if (ParseTypeAndValue(Val, Loc, PFS) ||
  2800. ParseOptionalCommaAlignment(Alignment))
  2801. return true;
  2802. if (!isa<PointerType>(Val->getType()) ||
  2803. !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
  2804. return Error(Loc, "load operand must be a pointer to a first class type");
  2805. Inst = new LoadInst(Val, "", isVolatile, Alignment);
  2806. return false;
  2807. }
  2808. /// ParseStore
  2809. /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
  2810. bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
  2811. bool isVolatile) {
  2812. Value *Val, *Ptr; LocTy Loc, PtrLoc;
  2813. unsigned Alignment;
  2814. if (ParseTypeAndValue(Val, Loc, PFS) ||
  2815. ParseToken(lltok::comma, "expected ',' after store operand") ||
  2816. ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
  2817. ParseOptionalCommaAlignment(Alignment))
  2818. return true;
  2819. if (!isa<PointerType>(Ptr->getType()))
  2820. return Error(PtrLoc, "store operand must be a pointer");
  2821. if (!Val->getType()->isFirstClassType())
  2822. return Error(Loc, "store operand must be a first class value");
  2823. if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
  2824. return Error(Loc, "stored value and pointer type do not match");
  2825. Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
  2826. return false;
  2827. }
  2828. /// ParseGetResult
  2829. /// ::= 'getresult' TypeAndValue ',' i32
  2830. /// FIXME: Remove support for getresult in LLVM 3.0
  2831. bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
  2832. Value *Val; LocTy ValLoc, EltLoc;
  2833. unsigned Element;
  2834. if (ParseTypeAndValue(Val, ValLoc, PFS) ||
  2835. ParseToken(lltok::comma, "expected ',' after getresult operand") ||
  2836. ParseUInt32(Element, EltLoc))
  2837. return true;
  2838. if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
  2839. return Error(ValLoc, "getresult inst requires an aggregate operand");
  2840. if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
  2841. return Error(EltLoc, "invalid getresult index for value");
  2842. Inst = ExtractValueInst::Create(Val, Element);
  2843. return false;
  2844. }
  2845. /// ParseGetElementPtr
  2846. /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
  2847. bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
  2848. Value *Ptr, *Val; LocTy Loc, EltLoc;
  2849. if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
  2850. if (!isa<PointerType>(Ptr->getType()))
  2851. return Error(Loc, "base of getelementptr must be a pointer");
  2852. SmallVector<Value*, 16> Indices;
  2853. while (EatIfPresent(lltok::comma)) {
  2854. if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
  2855. if (!isa<IntegerType>(Val->getType()))
  2856. return Error(EltLoc, "getelementptr index must be an integer");
  2857. Indices.push_back(Val);
  2858. }
  2859. if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
  2860. Indices.begin(), Indices.end()))
  2861. return Error(Loc, "invalid getelementptr indices");
  2862. Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
  2863. return false;
  2864. }
  2865. /// ParseExtractValue
  2866. /// ::= 'extractvalue' TypeAndValue (',' uint32)+
  2867. bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
  2868. Value *Val; LocTy Loc;
  2869. SmallVector<unsigned, 4> Indices;
  2870. if (ParseTypeAndValue(Val, Loc, PFS) ||
  2871. ParseIndexList(Indices))
  2872. return true;
  2873. if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
  2874. return Error(Loc, "extractvalue operand must be array or struct");
  2875. if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
  2876. Indices.end()))
  2877. return Error(Loc, "invalid indices for extractvalue");
  2878. Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
  2879. return false;
  2880. }
  2881. /// ParseInsertValue
  2882. /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
  2883. bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
  2884. Value *Val0, *Val1; LocTy Loc0, Loc1;
  2885. SmallVector<unsigned, 4> Indices;
  2886. if (ParseTypeAndValue(Val0, Loc0, PFS) ||
  2887. ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
  2888. ParseTypeAndValue(Val1, Loc1, PFS) ||
  2889. ParseIndexList(Indices))
  2890. return true;
  2891. if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
  2892. return Error(Loc0, "extractvalue operand must be array or struct");
  2893. if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
  2894. Indices.end()))
  2895. return Error(Loc0, "invalid indices for insertvalue");
  2896. Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
  2897. return false;
  2898. }
  2899. //===----------------------------------------------------------------------===//
  2900. // Embedded metadata.
  2901. //===----------------------------------------------------------------------===//
  2902. /// ParseMDNodeVector
  2903. /// ::= Element (',' Element)*
  2904. /// Element
  2905. /// ::= 'null' | TypeAndValue
  2906. bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
  2907. assert(Lex.getKind() == lltok::lbrace);
  2908. Lex.Lex();
  2909. do {
  2910. Value *V;
  2911. if (Lex.getKind() == lltok::kw_null) {
  2912. Lex.Lex();
  2913. V = 0;
  2914. } else {
  2915. Constant *C;
  2916. if (ParseGlobalTypeAndValue(C)) return true;
  2917. V = C;
  2918. }
  2919. Elts.push_back(V);
  2920. } while (EatIfPresent(lltok::comma));
  2921. return false;
  2922. }