blob: d92957a6eff4cd58d90b4f764742a267431fe1e7 [file] [log] [blame]
Chris Lattnerdf986172009-01-02 07:01:27 +00001//===-- 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
14#include "LLParser.h"
15#include "llvm/AutoUpgrade.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/InlineAsm.h"
20#include "llvm/Instructions.h"
21#include "llvm/Module.h"
22#include "llvm/ValueSymbolTable.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/Support/raw_ostream.h"
26using namespace llvm;
27
Chris Lattnerdf986172009-01-02 07:01:27 +000028namespace llvm {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000029 /// ValID - Represents a reference of a definition of some sort with no type.
30 /// There are several cases where we have to parse the value but where the
31 /// type can depend on later context. This may either be a numeric reference
32 /// or a symbolic (%var) reference. This is just a discriminated union.
Chris Lattnerdf986172009-01-02 07:01:27 +000033 struct ValID {
34 enum {
35 t_LocalID, t_GlobalID, // ID in UIntVal.
36 t_LocalName, t_GlobalName, // Name in StrVal.
37 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
38 t_Null, t_Undef, t_Zero, // No value.
Chris Lattner081b5052009-01-05 07:52:51 +000039 t_EmptyArray, // No value: []
Chris Lattnerdf986172009-01-02 07:01:27 +000040 t_Constant, // Value in ConstantVal.
41 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
42 } Kind;
43
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
Chris Lattner3ed88ef2009-01-02 08:05:26 +000054/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000055bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000056 // Prime the lexer.
57 Lex.Lex();
58
Chris Lattnerad7d1e22009-01-04 20:44:11 +000059 return ParseTopLevelEntities() ||
60 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000061}
62
63/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
64/// module.
65bool LLParser::ValidateEndOfModule() {
66 if (!ForwardRefTypes.empty())
67 return Error(ForwardRefTypes.begin()->second.second,
68 "use of undefined type named '" +
69 ForwardRefTypes.begin()->first + "'");
70 if (!ForwardRefTypeIDs.empty())
71 return Error(ForwardRefTypeIDs.begin()->second.second,
72 "use of undefined type '%" +
73 utostr(ForwardRefTypeIDs.begin()->first) + "'");
74
75 if (!ForwardRefVals.empty())
76 return Error(ForwardRefVals.begin()->second.second,
77 "use of undefined value '@" + ForwardRefVals.begin()->first +
78 "'");
79
80 if (!ForwardRefValIDs.empty())
81 return Error(ForwardRefValIDs.begin()->second.second,
82 "use of undefined value '@" +
83 utostr(ForwardRefValIDs.begin()->first) + "'");
84
85 // Look for intrinsic functions and CallInst that need to be upgraded
86 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
87 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
88
89 return false;
90}
91
92//===----------------------------------------------------------------------===//
93// Top-Level Entities
94//===----------------------------------------------------------------------===//
95
96bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +000097 while (1) {
98 switch (Lex.getKind()) {
99 default: return TokError("expected top-level entity");
100 case lltok::Eof: return false;
101 //case lltok::kw_define:
102 case lltok::kw_declare: if (ParseDeclare()) return true; break;
103 case lltok::kw_define: if (ParseDefine()) return true; break;
104 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
105 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
106 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
107 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
108 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
109 case lltok::LocalVar: if (ParseNamedType()) return true; break;
110 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
111
112 // The Global variable production with no name can have many different
113 // optional leading prefixes, the production is:
114 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
115 // OptionalAddrSpace ('constant'|'global') ...
Rafael Espindolabb46f522009-01-15 20:18:42 +0000116 case lltok::kw_private: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000117 case lltok::kw_internal: // OptionalLinkage
118 case lltok::kw_weak: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000119 case lltok::kw_weak_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000120 case lltok::kw_linkonce: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000121 case lltok::kw_linkonce_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000122 case lltok::kw_appending: // OptionalLinkage
123 case lltok::kw_dllexport: // OptionalLinkage
124 case lltok::kw_common: // OptionalLinkage
125 case lltok::kw_dllimport: // OptionalLinkage
126 case lltok::kw_extern_weak: // OptionalLinkage
127 case lltok::kw_external: { // OptionalLinkage
128 unsigned Linkage, Visibility;
129 if (ParseOptionalLinkage(Linkage) ||
130 ParseOptionalVisibility(Visibility) ||
131 ParseGlobal("", 0, Linkage, true, Visibility))
132 return true;
133 break;
134 }
135 case lltok::kw_default: // OptionalVisibility
136 case lltok::kw_hidden: // OptionalVisibility
137 case lltok::kw_protected: { // OptionalVisibility
138 unsigned Visibility;
139 if (ParseOptionalVisibility(Visibility) ||
140 ParseGlobal("", 0, 0, false, Visibility))
141 return true;
142 break;
143 }
144
145 case lltok::kw_thread_local: // OptionalThreadLocal
146 case lltok::kw_addrspace: // OptionalAddrSpace
147 case lltok::kw_constant: // GlobalType
148 case lltok::kw_global: // GlobalType
149 if (ParseGlobal("", 0, 0, false, 0)) return true;
150 break;
151 }
152 }
153}
154
155
156/// toplevelentity
157/// ::= 'module' 'asm' STRINGCONSTANT
158bool LLParser::ParseModuleAsm() {
159 assert(Lex.getKind() == lltok::kw_module);
160 Lex.Lex();
161
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000162 std::string AsmStr;
163 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
164 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000165
166 const std::string &AsmSoFar = M->getModuleInlineAsm();
167 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000168 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000169 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000170 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000171 return false;
172}
173
174/// toplevelentity
175/// ::= 'target' 'triple' '=' STRINGCONSTANT
176/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
177bool LLParser::ParseTargetDefinition() {
178 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000179 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000180 switch (Lex.Lex()) {
181 default: return TokError("unknown target property");
182 case lltok::kw_triple:
183 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000184 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
185 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000186 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000187 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000188 return false;
189 case lltok::kw_datalayout:
190 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000191 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
192 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000193 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000194 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000195 return false;
196 }
197}
198
199/// toplevelentity
200/// ::= 'deplibs' '=' '[' ']'
201/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
202bool LLParser::ParseDepLibs() {
203 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000204 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000205 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
206 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
207 return true;
208
209 if (EatIfPresent(lltok::rsquare))
210 return false;
211
212 std::string Str;
213 if (ParseStringConstant(Str)) return true;
214 M->addLibrary(Str);
215
216 while (EatIfPresent(lltok::comma)) {
217 if (ParseStringConstant(Str)) return true;
218 M->addLibrary(Str);
219 }
220
221 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000222}
223
224/// toplevelentity
225/// ::= 'type' type
226bool LLParser::ParseUnnamedType() {
227 assert(Lex.getKind() == lltok::kw_type);
228 LocTy TypeLoc = Lex.getLoc();
229 Lex.Lex(); // eat kw_type
230
231 PATypeHolder Ty(Type::VoidTy);
232 if (ParseType(Ty)) return true;
233
234 unsigned TypeID = NumberedTypes.size();
235
Chris Lattnerdf986172009-01-02 07:01:27 +0000236 // See if this type was previously referenced.
237 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
238 FI = ForwardRefTypeIDs.find(TypeID);
239 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000240 if (FI->second.first.get() == Ty)
241 return Error(TypeLoc, "self referential type is invalid");
242
Chris Lattnerdf986172009-01-02 07:01:27 +0000243 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
244 Ty = FI->second.first.get();
245 ForwardRefTypeIDs.erase(FI);
246 }
247
248 NumberedTypes.push_back(Ty);
249
250 return false;
251}
252
253/// toplevelentity
254/// ::= LocalVar '=' 'type' type
255bool LLParser::ParseNamedType() {
256 std::string Name = Lex.getStrVal();
257 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000258 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000259
260 PATypeHolder Ty(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000261
262 if (ParseToken(lltok::equal, "expected '=' after name") ||
263 ParseToken(lltok::kw_type, "expected 'type' after name") ||
264 ParseType(Ty))
265 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000266
Chris Lattnerdf986172009-01-02 07:01:27 +0000267 // Set the type name, checking for conflicts as we do so.
268 bool AlreadyExists = M->addTypeName(Name, Ty);
269 if (!AlreadyExists) return false;
270
271 // See if this type is a forward reference. We need to eagerly resolve
272 // types to allow recursive type redefinitions below.
273 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
274 FI = ForwardRefTypes.find(Name);
275 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000276 if (FI->second.first.get() == Ty)
277 return Error(NameLoc, "self referential type is invalid");
278
Chris Lattnerdf986172009-01-02 07:01:27 +0000279 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
280 Ty = FI->second.first.get();
281 ForwardRefTypes.erase(FI);
282 }
283
284 // Inserting a name that is already defined, get the existing name.
285 const Type *Existing = M->getTypeByName(Name);
286 assert(Existing && "Conflict but no matching type?!");
287
288 // Otherwise, this is an attempt to redefine a type. That's okay if
289 // the redefinition is identical to the original.
290 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
291 if (Existing == Ty) return false;
292
293 // Any other kind of (non-equivalent) redefinition is an error.
294 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
295 Ty->getDescription() + "'");
296}
297
298
299/// toplevelentity
300/// ::= 'declare' FunctionHeader
301bool LLParser::ParseDeclare() {
302 assert(Lex.getKind() == lltok::kw_declare);
303 Lex.Lex();
304
305 Function *F;
306 return ParseFunctionHeader(F, false);
307}
308
309/// toplevelentity
310/// ::= 'define' FunctionHeader '{' ...
311bool LLParser::ParseDefine() {
312 assert(Lex.getKind() == lltok::kw_define);
313 Lex.Lex();
314
315 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000316 return ParseFunctionHeader(F, true) ||
317 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000318}
319
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000320/// ParseGlobalType
321/// ::= 'constant'
322/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000323bool LLParser::ParseGlobalType(bool &IsConstant) {
324 if (Lex.getKind() == lltok::kw_constant)
325 IsConstant = true;
326 else if (Lex.getKind() == lltok::kw_global)
327 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000328 else {
329 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000330 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000331 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000332 Lex.Lex();
333 return false;
334}
335
336/// ParseNamedGlobal:
337/// GlobalVar '=' OptionalVisibility ALIAS ...
338/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
339bool LLParser::ParseNamedGlobal() {
340 assert(Lex.getKind() == lltok::GlobalVar);
341 LocTy NameLoc = Lex.getLoc();
342 std::string Name = Lex.getStrVal();
343 Lex.Lex();
344
345 bool HasLinkage;
346 unsigned Linkage, Visibility;
347 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
348 ParseOptionalLinkage(Linkage, HasLinkage) ||
349 ParseOptionalVisibility(Visibility))
350 return true;
351
352 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
353 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
354 return ParseAlias(Name, NameLoc, Visibility);
355}
356
357/// ParseAlias:
358/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
359/// Aliasee
360/// ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')'
361///
362/// Everything through visibility has already been parsed.
363///
364bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
365 unsigned Visibility) {
366 assert(Lex.getKind() == lltok::kw_alias);
367 Lex.Lex();
368 unsigned Linkage;
369 LocTy LinkageLoc = Lex.getLoc();
370 if (ParseOptionalLinkage(Linkage))
371 return true;
372
373 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000374 Linkage != GlobalValue::WeakAnyLinkage &&
375 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000376 Linkage != GlobalValue::InternalLinkage &&
377 Linkage != GlobalValue::PrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000378 return Error(LinkageLoc, "invalid linkage type for alias");
379
380 Constant *Aliasee;
381 LocTy AliaseeLoc = Lex.getLoc();
382 if (Lex.getKind() != lltok::kw_bitcast) {
383 if (ParseGlobalTypeAndValue(Aliasee)) return true;
384 } else {
385 // The bitcast dest type is not present, it is implied by the dest type.
386 ValID ID;
387 if (ParseValID(ID)) return true;
388 if (ID.Kind != ValID::t_Constant)
389 return Error(AliaseeLoc, "invalid aliasee");
390 Aliasee = ID.ConstantVal;
391 }
392
393 if (!isa<PointerType>(Aliasee->getType()))
394 return Error(AliaseeLoc, "alias must have pointer type");
395
396 // Okay, create the alias but do not insert it into the module yet.
397 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
398 (GlobalValue::LinkageTypes)Linkage, Name,
399 Aliasee);
400 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
401
402 // See if this value already exists in the symbol table. If so, it is either
403 // a redefinition or a definition of a forward reference.
404 if (GlobalValue *Val =
405 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
406 // See if this was a redefinition. If so, there is no entry in
407 // ForwardRefVals.
408 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
409 I = ForwardRefVals.find(Name);
410 if (I == ForwardRefVals.end())
411 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
412
413 // Otherwise, this was a definition of forward ref. Verify that types
414 // agree.
415 if (Val->getType() != GA->getType())
416 return Error(NameLoc,
417 "forward reference and definition of alias have different types");
418
419 // If they agree, just RAUW the old value with the alias and remove the
420 // forward ref info.
421 Val->replaceAllUsesWith(GA);
422 Val->eraseFromParent();
423 ForwardRefVals.erase(I);
424 }
425
426 // Insert into the module, we know its name won't collide now.
427 M->getAliasList().push_back(GA);
428 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
429
430 return false;
431}
432
433/// ParseGlobal
434/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
435/// OptionalAddrSpace GlobalType Type Const
436/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
437/// OptionalAddrSpace GlobalType Type Const
438///
439/// Everything through visibility has been parsed already.
440///
441bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
442 unsigned Linkage, bool HasLinkage,
443 unsigned Visibility) {
444 unsigned AddrSpace;
445 bool ThreadLocal, IsConstant;
446 LocTy TyLoc;
447
448 PATypeHolder Ty(Type::VoidTy);
449 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
450 ParseOptionalAddrSpace(AddrSpace) ||
451 ParseGlobalType(IsConstant) ||
452 ParseType(Ty, TyLoc))
453 return true;
454
455 // If the linkage is specified and is external, then no initializer is
456 // present.
457 Constant *Init = 0;
458 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000459 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000460 Linkage != GlobalValue::ExternalLinkage)) {
461 if (ParseGlobalValue(Ty, Init))
462 return true;
463 }
464
Chris Lattnera9a9e072009-03-09 04:49:14 +0000465 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
Chris Lattner4a2f1122009-02-08 20:00:15 +0000466 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000467
468 GlobalVariable *GV = 0;
469
470 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000471 if (!Name.empty()) {
472 if ((GV = M->getGlobalVariable(Name, true)) &&
473 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000474 return Error(NameLoc, "redefinition of global '@" + Name + "'");
475 } else {
476 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
477 I = ForwardRefValIDs.find(NumberedVals.size());
478 if (I != ForwardRefValIDs.end()) {
479 GV = cast<GlobalVariable>(I->second.first);
480 ForwardRefValIDs.erase(I);
481 }
482 }
483
484 if (GV == 0) {
485 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
486 M, false, AddrSpace);
487 } else {
488 if (GV->getType()->getElementType() != Ty)
489 return Error(TyLoc,
490 "forward reference and definition of global have different types");
491
492 // Move the forward-reference to the correct spot in the module.
493 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
494 }
495
496 if (Name.empty())
497 NumberedVals.push_back(GV);
498
499 // Set the parsed properties on the global.
500 if (Init)
501 GV->setInitializer(Init);
502 GV->setConstant(IsConstant);
503 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
504 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
505 GV->setThreadLocal(ThreadLocal);
506
507 // Parse attributes on the global.
508 while (Lex.getKind() == lltok::comma) {
509 Lex.Lex();
510
511 if (Lex.getKind() == lltok::kw_section) {
512 Lex.Lex();
513 GV->setSection(Lex.getStrVal());
514 if (ParseToken(lltok::StringConstant, "expected global section string"))
515 return true;
516 } else if (Lex.getKind() == lltok::kw_align) {
517 unsigned Alignment;
518 if (ParseOptionalAlignment(Alignment)) return true;
519 GV->setAlignment(Alignment);
520 } else {
521 TokError("unknown global variable property!");
522 }
523 }
524
525 return false;
526}
527
528
529//===----------------------------------------------------------------------===//
530// GlobalValue Reference/Resolution Routines.
531//===----------------------------------------------------------------------===//
532
533/// GetGlobalVal - Get a value with the specified name or ID, creating a
534/// forward reference record if needed. This can return null if the value
535/// exists but does not have the right type.
536GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
537 LocTy Loc) {
538 const PointerType *PTy = dyn_cast<PointerType>(Ty);
539 if (PTy == 0) {
540 Error(Loc, "global variable reference must have pointer type");
541 return 0;
542 }
543
544 // Look this name up in the normal function symbol table.
545 GlobalValue *Val =
546 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
547
548 // If this is a forward reference for the value, see if we already created a
549 // forward ref record.
550 if (Val == 0) {
551 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
552 I = ForwardRefVals.find(Name);
553 if (I != ForwardRefVals.end())
554 Val = I->second.first;
555 }
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, "'@" + Name + "' defined with type '" +
561 Val->getType()->getDescription() + "'");
562 return 0;
563 }
564
565 // Otherwise, create a new forward reference for this value and remember it.
566 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000567 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
568 // Function types can return opaque but functions can't.
569 if (isa<OpaqueType>(FT->getReturnType())) {
570 Error(Loc, "function may not return opaque type");
571 return 0;
572 }
573
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000574 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000575 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000576 FwdVal = new GlobalVariable(PTy->getElementType(), false,
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000577 GlobalValue::ExternalWeakLinkage, 0, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000578 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000579
580 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
581 return FwdVal;
582}
583
584GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
585 const PointerType *PTy = dyn_cast<PointerType>(Ty);
586 if (PTy == 0) {
587 Error(Loc, "global variable reference must have pointer type");
588 return 0;
589 }
590
591 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
592
593 // If this is a forward reference for the value, see if we already created a
594 // forward ref record.
595 if (Val == 0) {
596 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
597 I = ForwardRefValIDs.find(ID);
598 if (I != ForwardRefValIDs.end())
599 Val = I->second.first;
600 }
601
602 // If we have the value in the symbol table or fwd-ref table, return it.
603 if (Val) {
604 if (Val->getType() == Ty) return Val;
605 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
606 Val->getType()->getDescription() + "'");
607 return 0;
608 }
609
610 // Otherwise, create a new forward reference for this value and remember it.
611 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000612 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
613 // Function types can return opaque but functions can't.
614 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000615 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000616 return 0;
617 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000618 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000619 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000620 FwdVal = new GlobalVariable(PTy->getElementType(), false,
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000621 GlobalValue::ExternalWeakLinkage, 0, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000622 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000623
624 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
625 return FwdVal;
626}
627
628
629//===----------------------------------------------------------------------===//
630// Helper Routines.
631//===----------------------------------------------------------------------===//
632
633/// ParseToken - If the current token has the specified kind, eat it and return
634/// success. Otherwise, emit the specified error and return failure.
635bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
636 if (Lex.getKind() != T)
637 return TokError(ErrMsg);
638 Lex.Lex();
639 return false;
640}
641
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000642/// ParseStringConstant
643/// ::= StringConstant
644bool LLParser::ParseStringConstant(std::string &Result) {
645 if (Lex.getKind() != lltok::StringConstant)
646 return TokError("expected string constant");
647 Result = Lex.getStrVal();
648 Lex.Lex();
649 return false;
650}
651
652/// ParseUInt32
653/// ::= uint32
654bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000655 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
656 return TokError("expected integer");
657 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
658 if (Val64 != unsigned(Val64))
659 return TokError("expected 32-bit integer (too large)");
660 Val = Val64;
661 Lex.Lex();
662 return false;
663}
664
665
666/// ParseOptionalAddrSpace
667/// := /*empty*/
668/// := 'addrspace' '(' uint32 ')'
669bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
670 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000671 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000672 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000673 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000674 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000675 ParseToken(lltok::rparen, "expected ')' in address space");
676}
677
678/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
679/// indicates what kind of attribute list this is: 0: function arg, 1: result,
680/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000681/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000682bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
683 Attrs = Attribute::None;
684 LocTy AttrLoc = Lex.getLoc();
685
686 while (1) {
687 switch (Lex.getKind()) {
688 case lltok::kw_sext:
689 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000690 // Treat these as signext/zeroext if they occur in the argument list after
691 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
692 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
693 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000694 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000695 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000696 if (Lex.getKind() == lltok::kw_sext)
697 Attrs |= Attribute::SExt;
698 else
699 Attrs |= Attribute::ZExt;
700 break;
701 }
702 // FALL THROUGH.
703 default: // End of attributes.
704 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
705 return Error(AttrLoc, "invalid use of function-only attribute");
706
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000707 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000708 return Error(AttrLoc, "invalid use of parameter-only attribute");
709
710 return false;
711 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
712 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
713 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
714 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
715 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
716 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
717 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
718 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
719
720 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
721 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
722 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
723 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
724 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
725 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
726 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
727 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
728 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
729
730
731 case lltok::kw_align: {
732 unsigned Alignment;
733 if (ParseOptionalAlignment(Alignment))
734 return true;
735 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
736 continue;
737 }
738 }
739 Lex.Lex();
740 }
741}
742
743/// ParseOptionalLinkage
744/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000745/// ::= 'private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000746/// ::= 'internal'
747/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000748/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000749/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000750/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000751/// ::= 'appending'
752/// ::= 'dllexport'
753/// ::= 'common'
754/// ::= 'dllimport'
755/// ::= 'extern_weak'
756/// ::= 'external'
757bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
758 HasLinkage = false;
759 switch (Lex.getKind()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000760 default: Res = GlobalValue::ExternalLinkage; return false;
761 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
762 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
763 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
764 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
765 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
766 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000767 case lltok::kw_available_externally:
768 Res = GlobalValue::AvailableExternallyLinkage;
769 break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000770 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
771 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
Duncan Sands4dc2b392009-03-11 20:14:15 +0000772 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000773 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000774 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000775 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000776 }
777 Lex.Lex();
778 HasLinkage = true;
779 return false;
780}
781
782/// ParseOptionalVisibility
783/// ::= /*empty*/
784/// ::= 'default'
785/// ::= 'hidden'
786/// ::= 'protected'
787///
788bool LLParser::ParseOptionalVisibility(unsigned &Res) {
789 switch (Lex.getKind()) {
790 default: Res = GlobalValue::DefaultVisibility; return false;
791 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
792 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
793 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
794 }
795 Lex.Lex();
796 return false;
797}
798
799/// ParseOptionalCallingConv
800/// ::= /*empty*/
801/// ::= 'ccc'
802/// ::= 'fastcc'
803/// ::= 'coldcc'
804/// ::= 'x86_stdcallcc'
805/// ::= 'x86_fastcallcc'
806/// ::= 'cc' UINT
807///
808bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
809 switch (Lex.getKind()) {
810 default: CC = CallingConv::C; return false;
811 case lltok::kw_ccc: CC = CallingConv::C; break;
812 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
813 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
814 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
815 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000816 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000817 }
818 Lex.Lex();
819 return false;
820}
821
822/// ParseOptionalAlignment
823/// ::= /* empty */
824/// ::= 'align' 4
825bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
826 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000827 if (!EatIfPresent(lltok::kw_align))
828 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000829 LocTy AlignLoc = Lex.getLoc();
830 if (ParseUInt32(Alignment)) return true;
831 if (!isPowerOf2_32(Alignment))
832 return Error(AlignLoc, "alignment is not a power of two");
833 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000834}
835
836/// ParseOptionalCommaAlignment
837/// ::= /* empty */
838/// ::= ',' 'align' 4
839bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
840 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000841 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000842 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000843 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000844 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000845}
846
847/// ParseIndexList
848/// ::= (',' uint32)+
849bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
850 if (Lex.getKind() != lltok::comma)
851 return TokError("expected ',' as start of index list");
852
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000853 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000854 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000855 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000856 Indices.push_back(Idx);
857 }
858
859 return false;
860}
861
862//===----------------------------------------------------------------------===//
863// Type Parsing.
864//===----------------------------------------------------------------------===//
865
866/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +0000867bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
868 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000869 if (ParseTypeRec(Result)) return true;
870
871 // Verify no unresolved uprefs.
872 if (!UpRefs.empty())
873 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000874
Chris Lattnera9a9e072009-03-09 04:49:14 +0000875 if (!AllowVoid && Result.get() == Type::VoidTy)
876 return Error(TypeLoc, "void type only allowed for function results");
877
Chris Lattnerdf986172009-01-02 07:01:27 +0000878 return false;
879}
880
881/// HandleUpRefs - Every time we finish a new layer of types, this function is
882/// called. It loops through the UpRefs vector, which is a list of the
883/// currently active types. For each type, if the up-reference is contained in
884/// the newly completed type, we decrement the level count. When the level
885/// count reaches zero, the up-referenced type is the type that is passed in:
886/// thus we can complete the cycle.
887///
888PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
889 // If Ty isn't abstract, or if there are no up-references in it, then there is
890 // nothing to resolve here.
891 if (!ty->isAbstract() || UpRefs.empty()) return ty;
892
893 PATypeHolder Ty(ty);
894#if 0
895 errs() << "Type '" << Ty->getDescription()
896 << "' newly formed. Resolving upreferences.\n"
897 << UpRefs.size() << " upreferences active!\n";
898#endif
899
900 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
901 // to zero), we resolve them all together before we resolve them to Ty. At
902 // the end of the loop, if there is anything to resolve to Ty, it will be in
903 // this variable.
904 OpaqueType *TypeToResolve = 0;
905
906 for (unsigned i = 0; i != UpRefs.size(); ++i) {
907 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
908 bool ContainsType =
909 std::find(Ty->subtype_begin(), Ty->subtype_end(),
910 UpRefs[i].LastContainedTy) != Ty->subtype_end();
911
912#if 0
913 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
914 << UpRefs[i].LastContainedTy->getDescription() << ") = "
915 << (ContainsType ? "true" : "false")
916 << " level=" << UpRefs[i].NestingLevel << "\n";
917#endif
918 if (!ContainsType)
919 continue;
920
921 // Decrement level of upreference
922 unsigned Level = --UpRefs[i].NestingLevel;
923 UpRefs[i].LastContainedTy = Ty;
924
925 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
926 if (Level != 0)
927 continue;
928
929#if 0
930 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
931#endif
932 if (!TypeToResolve)
933 TypeToResolve = UpRefs[i].UpRefTy;
934 else
935 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
936 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
937 --i; // Do not skip the next element.
938 }
939
940 if (TypeToResolve)
941 TypeToResolve->refineAbstractTypeTo(Ty);
942
943 return Ty;
944}
945
946
947/// ParseTypeRec - The recursive function used to process the internal
948/// implementation details of types.
949bool LLParser::ParseTypeRec(PATypeHolder &Result) {
950 switch (Lex.getKind()) {
951 default:
952 return TokError("expected type");
953 case lltok::Type:
954 // TypeRec ::= 'float' | 'void' (etc)
955 Result = Lex.getTyVal();
956 Lex.Lex();
957 break;
958 case lltok::kw_opaque:
959 // TypeRec ::= 'opaque'
960 Result = OpaqueType::get();
961 Lex.Lex();
962 break;
963 case lltok::lbrace:
964 // TypeRec ::= '{' ... '}'
965 if (ParseStructType(Result, false))
966 return true;
967 break;
968 case lltok::lsquare:
969 // TypeRec ::= '[' ... ']'
970 Lex.Lex(); // eat the lsquare.
971 if (ParseArrayVectorType(Result, false))
972 return true;
973 break;
974 case lltok::less: // Either vector or packed struct.
975 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000976 Lex.Lex();
977 if (Lex.getKind() == lltok::lbrace) {
978 if (ParseStructType(Result, true) ||
979 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +0000980 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000981 } else if (ParseArrayVectorType(Result, true))
982 return true;
983 break;
984 case lltok::LocalVar:
985 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
986 // TypeRec ::= %foo
987 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
988 Result = T;
989 } else {
990 Result = OpaqueType::get();
991 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
992 std::make_pair(Result,
993 Lex.getLoc())));
994 M->addTypeName(Lex.getStrVal(), Result.get());
995 }
996 Lex.Lex();
997 break;
998
999 case lltok::LocalVarID:
1000 // TypeRec ::= %4
1001 if (Lex.getUIntVal() < NumberedTypes.size())
1002 Result = NumberedTypes[Lex.getUIntVal()];
1003 else {
1004 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1005 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1006 if (I != ForwardRefTypeIDs.end())
1007 Result = I->second.first;
1008 else {
1009 Result = OpaqueType::get();
1010 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1011 std::make_pair(Result,
1012 Lex.getLoc())));
1013 }
1014 }
1015 Lex.Lex();
1016 break;
1017 case lltok::backslash: {
1018 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001019 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001020 unsigned Val;
1021 if (ParseUInt32(Val)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001022 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
1023 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1024 Result = OT;
1025 break;
1026 }
1027 }
1028
1029 // Parse the type suffixes.
1030 while (1) {
1031 switch (Lex.getKind()) {
1032 // End of type.
1033 default: return false;
1034
1035 // TypeRec ::= TypeRec '*'
1036 case lltok::star:
1037 if (Result.get() == Type::LabelTy)
1038 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001039 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001040 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerdf986172009-01-02 07:01:27 +00001041 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1042 Lex.Lex();
1043 break;
1044
1045 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1046 case lltok::kw_addrspace: {
1047 if (Result.get() == Type::LabelTy)
1048 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001049 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001050 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerdf986172009-01-02 07:01:27 +00001051 unsigned AddrSpace;
1052 if (ParseOptionalAddrSpace(AddrSpace) ||
1053 ParseToken(lltok::star, "expected '*' in address space"))
1054 return true;
1055
1056 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1057 break;
1058 }
1059
1060 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1061 case lltok::lparen:
1062 if (ParseFunctionType(Result))
1063 return true;
1064 break;
1065 }
1066 }
1067}
1068
1069/// ParseParameterList
1070/// ::= '(' ')'
1071/// ::= '(' Arg (',' Arg)* ')'
1072/// Arg
1073/// ::= Type OptionalAttributes Value OptionalAttributes
1074bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1075 PerFunctionState &PFS) {
1076 if (ParseToken(lltok::lparen, "expected '(' in call"))
1077 return true;
1078
1079 while (Lex.getKind() != lltok::rparen) {
1080 // If this isn't the first argument, we need a comma.
1081 if (!ArgList.empty() &&
1082 ParseToken(lltok::comma, "expected ',' in argument list"))
1083 return true;
1084
1085 // Parse the argument.
1086 LocTy ArgLoc;
1087 PATypeHolder ArgTy(Type::VoidTy);
1088 unsigned ArgAttrs1, ArgAttrs2;
1089 Value *V;
1090 if (ParseType(ArgTy, ArgLoc) ||
1091 ParseOptionalAttrs(ArgAttrs1, 0) ||
1092 ParseValue(ArgTy, V, PFS) ||
1093 // FIXME: Should not allow attributes after the argument, remove this in
1094 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001095 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001096 return true;
1097 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1098 }
1099
1100 Lex.Lex(); // Lex the ')'.
1101 return false;
1102}
1103
1104
1105
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001106/// ParseArgumentList - Parse the argument list for a function type or function
1107/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001108/// ::= '(' ArgTypeListI ')'
1109/// ArgTypeListI
1110/// ::= /*empty*/
1111/// ::= '...'
1112/// ::= ArgTypeList ',' '...'
1113/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001114///
Chris Lattnerdf986172009-01-02 07:01:27 +00001115bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001116 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001117 isVarArg = false;
1118 assert(Lex.getKind() == lltok::lparen);
1119 Lex.Lex(); // eat the (.
1120
1121 if (Lex.getKind() == lltok::rparen) {
1122 // empty
1123 } else if (Lex.getKind() == lltok::dotdotdot) {
1124 isVarArg = true;
1125 Lex.Lex();
1126 } else {
1127 LocTy TypeLoc = Lex.getLoc();
1128 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001129 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001130 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001131
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001132 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1133 // types (such as a function returning a pointer to itself). If parsing a
1134 // function prototype, we require fully resolved types.
1135 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001136 ParseOptionalAttrs(Attrs, 0)) return true;
1137
Chris Lattnera9a9e072009-03-09 04:49:14 +00001138 if (ArgTy == Type::VoidTy)
1139 return Error(TypeLoc, "argument can not have void type");
1140
Chris Lattnerdf986172009-01-02 07:01:27 +00001141 if (Lex.getKind() == lltok::LocalVar ||
1142 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1143 Name = Lex.getStrVal();
1144 Lex.Lex();
1145 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001146
1147 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1148 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001149
1150 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1151
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001152 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001153 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001154 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001155 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001156 break;
1157 }
1158
1159 // Otherwise must be an argument type.
1160 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001161 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001162 ParseOptionalAttrs(Attrs, 0)) return true;
1163
Chris Lattnera9a9e072009-03-09 04:49:14 +00001164 if (ArgTy == Type::VoidTy)
1165 return Error(TypeLoc, "argument can not have void type");
1166
Chris Lattnerdf986172009-01-02 07:01:27 +00001167 if (Lex.getKind() == lltok::LocalVar ||
1168 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1169 Name = Lex.getStrVal();
1170 Lex.Lex();
1171 } else {
1172 Name = "";
1173 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001174
1175 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1176 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001177
1178 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1179 }
1180 }
1181
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001182 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001183}
1184
1185/// ParseFunctionType
1186/// ::= Type ArgumentList OptionalAttrs
1187bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1188 assert(Lex.getKind() == lltok::lparen);
1189
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001190 if (!FunctionType::isValidReturnType(Result))
1191 return TokError("invalid function return type");
1192
Chris Lattnerdf986172009-01-02 07:01:27 +00001193 std::vector<ArgInfo> ArgList;
1194 bool isVarArg;
1195 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001196 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001197 // FIXME: Allow, but ignore attributes on function types!
1198 // FIXME: Remove in LLVM 3.0
1199 ParseOptionalAttrs(Attrs, 2))
1200 return true;
1201
1202 // Reject names on the arguments lists.
1203 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1204 if (!ArgList[i].Name.empty())
1205 return Error(ArgList[i].Loc, "argument name invalid in function type");
1206 if (!ArgList[i].Attrs != 0) {
1207 // Allow but ignore attributes on function types; this permits
1208 // auto-upgrade.
1209 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1210 }
1211 }
1212
1213 std::vector<const Type*> ArgListTy;
1214 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1215 ArgListTy.push_back(ArgList[i].Type);
1216
1217 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1218 return false;
1219}
1220
1221/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1222/// TypeRec
1223/// ::= '{' '}'
1224/// ::= '{' TypeRec (',' TypeRec)* '}'
1225/// ::= '<' '{' '}' '>'
1226/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1227bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1228 assert(Lex.getKind() == lltok::lbrace);
1229 Lex.Lex(); // Consume the '{'
1230
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001231 if (EatIfPresent(lltok::rbrace)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001232 Result = StructType::get(std::vector<const Type*>(), Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001233 return false;
1234 }
1235
1236 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001237 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001238 if (ParseTypeRec(Result)) return true;
1239 ParamsList.push_back(Result);
1240
Chris Lattnera9a9e072009-03-09 04:49:14 +00001241 if (Result == Type::VoidTy)
1242 return Error(EltTyLoc, "struct element can not have void type");
1243
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001244 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001245 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001246 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001247
1248 if (Result == Type::VoidTy)
1249 return Error(EltTyLoc, "struct element can not have void type");
1250
Chris Lattnerdf986172009-01-02 07:01:27 +00001251 ParamsList.push_back(Result);
1252 }
1253
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001254 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1255 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001256
1257 std::vector<const Type*> ParamsListTy;
1258 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1259 ParamsListTy.push_back(ParamsList[i].get());
1260 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1261 return false;
1262}
1263
1264/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1265/// token has already been consumed.
1266/// TypeRec
1267/// ::= '[' APSINTVAL 'x' Types ']'
1268/// ::= '<' APSINTVAL 'x' Types '>'
1269bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1270 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1271 Lex.getAPSIntVal().getBitWidth() > 64)
1272 return TokError("expected number in address space");
1273
1274 LocTy SizeLoc = Lex.getLoc();
1275 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001276 Lex.Lex();
1277
1278 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1279 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001280
1281 LocTy TypeLoc = Lex.getLoc();
1282 PATypeHolder EltTy(Type::VoidTy);
1283 if (ParseTypeRec(EltTy)) return true;
1284
Chris Lattnera9a9e072009-03-09 04:49:14 +00001285 if (EltTy == Type::VoidTy)
1286 return Error(TypeLoc, "array and vector element type cannot be void");
1287
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001288 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1289 "expected end of sequential type"))
1290 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001291
1292 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001293 if (Size == 0)
1294 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001295 if ((unsigned)Size != Size)
1296 return Error(SizeLoc, "size too large for vector");
1297 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1298 return Error(TypeLoc, "vector element type must be fp or integer");
1299 Result = VectorType::get(EltTy, unsigned(Size));
1300 } else {
1301 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1302 return Error(TypeLoc, "invalid array element type");
1303 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1304 }
1305 return false;
1306}
1307
1308//===----------------------------------------------------------------------===//
1309// Function Semantic Analysis.
1310//===----------------------------------------------------------------------===//
1311
1312LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1313 : P(p), F(f) {
1314
1315 // Insert unnamed arguments into the NumberedVals list.
1316 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1317 AI != E; ++AI)
1318 if (!AI->hasName())
1319 NumberedVals.push_back(AI);
1320}
1321
1322LLParser::PerFunctionState::~PerFunctionState() {
1323 // If there were any forward referenced non-basicblock values, delete them.
1324 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1325 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1326 if (!isa<BasicBlock>(I->second.first)) {
1327 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1328 ->getType()));
1329 delete I->second.first;
1330 I->second.first = 0;
1331 }
1332
1333 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1334 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1335 if (!isa<BasicBlock>(I->second.first)) {
1336 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1337 ->getType()));
1338 delete I->second.first;
1339 I->second.first = 0;
1340 }
1341}
1342
1343bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1344 if (!ForwardRefVals.empty())
1345 return P.Error(ForwardRefVals.begin()->second.second,
1346 "use of undefined value '%" + ForwardRefVals.begin()->first +
1347 "'");
1348 if (!ForwardRefValIDs.empty())
1349 return P.Error(ForwardRefValIDs.begin()->second.second,
1350 "use of undefined value '%" +
1351 utostr(ForwardRefValIDs.begin()->first) + "'");
1352 return false;
1353}
1354
1355
1356/// GetVal - Get a value with the specified name or ID, creating a
1357/// forward reference record if needed. This can return null if the value
1358/// exists but does not have the right type.
1359Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1360 const Type *Ty, LocTy Loc) {
1361 // Look this name up in the normal function symbol table.
1362 Value *Val = F.getValueSymbolTable().lookup(Name);
1363
1364 // If this is a forward reference for the value, see if we already created a
1365 // forward ref record.
1366 if (Val == 0) {
1367 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1368 I = ForwardRefVals.find(Name);
1369 if (I != ForwardRefVals.end())
1370 Val = I->second.first;
1371 }
1372
1373 // If we have the value in the symbol table or fwd-ref table, return it.
1374 if (Val) {
1375 if (Val->getType() == Ty) return Val;
1376 if (Ty == Type::LabelTy)
1377 P.Error(Loc, "'%" + Name + "' is not a basic block");
1378 else
1379 P.Error(Loc, "'%" + Name + "' defined with type '" +
1380 Val->getType()->getDescription() + "'");
1381 return 0;
1382 }
1383
1384 // Don't make placeholders with invalid type.
1385 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1386 P.Error(Loc, "invalid use of a non-first-class type");
1387 return 0;
1388 }
1389
1390 // Otherwise, create a new forward reference for this value and remember it.
1391 Value *FwdVal;
1392 if (Ty == Type::LabelTy)
1393 FwdVal = BasicBlock::Create(Name, &F);
1394 else
1395 FwdVal = new Argument(Ty, Name);
1396
1397 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1398 return FwdVal;
1399}
1400
1401Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1402 LocTy Loc) {
1403 // Look this name up in the normal function symbol table.
1404 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1405
1406 // If this is a forward reference for the value, see if we already created a
1407 // forward ref record.
1408 if (Val == 0) {
1409 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1410 I = ForwardRefValIDs.find(ID);
1411 if (I != ForwardRefValIDs.end())
1412 Val = I->second.first;
1413 }
1414
1415 // If we have the value in the symbol table or fwd-ref table, return it.
1416 if (Val) {
1417 if (Val->getType() == Ty) return Val;
1418 if (Ty == Type::LabelTy)
1419 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1420 else
1421 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1422 Val->getType()->getDescription() + "'");
1423 return 0;
1424 }
1425
1426 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1427 P.Error(Loc, "invalid use of a non-first-class type");
1428 return 0;
1429 }
1430
1431 // Otherwise, create a new forward reference for this value and remember it.
1432 Value *FwdVal;
1433 if (Ty == Type::LabelTy)
1434 FwdVal = BasicBlock::Create("", &F);
1435 else
1436 FwdVal = new Argument(Ty);
1437
1438 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1439 return FwdVal;
1440}
1441
1442/// SetInstName - After an instruction is parsed and inserted into its
1443/// basic block, this installs its name.
1444bool LLParser::PerFunctionState::SetInstName(int NameID,
1445 const std::string &NameStr,
1446 LocTy NameLoc, Instruction *Inst) {
1447 // If this instruction has void type, it cannot have a name or ID specified.
1448 if (Inst->getType() == Type::VoidTy) {
1449 if (NameID != -1 || !NameStr.empty())
1450 return P.Error(NameLoc, "instructions returning void cannot have a name");
1451 return false;
1452 }
1453
1454 // If this was a numbered instruction, verify that the instruction is the
1455 // expected value and resolve any forward references.
1456 if (NameStr.empty()) {
1457 // If neither a name nor an ID was specified, just use the next ID.
1458 if (NameID == -1)
1459 NameID = NumberedVals.size();
1460
1461 if (unsigned(NameID) != NumberedVals.size())
1462 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1463 utostr(NumberedVals.size()) + "'");
1464
1465 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1466 ForwardRefValIDs.find(NameID);
1467 if (FI != ForwardRefValIDs.end()) {
1468 if (FI->second.first->getType() != Inst->getType())
1469 return P.Error(NameLoc, "instruction forward referenced with type '" +
1470 FI->second.first->getType()->getDescription() + "'");
1471 FI->second.first->replaceAllUsesWith(Inst);
1472 ForwardRefValIDs.erase(FI);
1473 }
1474
1475 NumberedVals.push_back(Inst);
1476 return false;
1477 }
1478
1479 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1480 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1481 FI = ForwardRefVals.find(NameStr);
1482 if (FI != ForwardRefVals.end()) {
1483 if (FI->second.first->getType() != Inst->getType())
1484 return P.Error(NameLoc, "instruction forward referenced with type '" +
1485 FI->second.first->getType()->getDescription() + "'");
1486 FI->second.first->replaceAllUsesWith(Inst);
1487 ForwardRefVals.erase(FI);
1488 }
1489
1490 // Set the name on the instruction.
1491 Inst->setName(NameStr);
1492
1493 if (Inst->getNameStr() != NameStr)
1494 return P.Error(NameLoc, "multiple definition of local value named '" +
1495 NameStr + "'");
1496 return false;
1497}
1498
1499/// GetBB - Get a basic block with the specified name or ID, creating a
1500/// forward reference record if needed.
1501BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1502 LocTy Loc) {
1503 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1504}
1505
1506BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1507 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1508}
1509
1510/// DefineBB - Define the specified basic block, which is either named or
1511/// unnamed. If there is an error, this returns null otherwise it returns
1512/// the block being defined.
1513BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1514 LocTy Loc) {
1515 BasicBlock *BB;
1516 if (Name.empty())
1517 BB = GetBB(NumberedVals.size(), Loc);
1518 else
1519 BB = GetBB(Name, Loc);
1520 if (BB == 0) return 0; // Already diagnosed error.
1521
1522 // Move the block to the end of the function. Forward ref'd blocks are
1523 // inserted wherever they happen to be referenced.
1524 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1525
1526 // Remove the block from forward ref sets.
1527 if (Name.empty()) {
1528 ForwardRefValIDs.erase(NumberedVals.size());
1529 NumberedVals.push_back(BB);
1530 } else {
1531 // BB forward references are already in the function symbol table.
1532 ForwardRefVals.erase(Name);
1533 }
1534
1535 return BB;
1536}
1537
1538//===----------------------------------------------------------------------===//
1539// Constants.
1540//===----------------------------------------------------------------------===//
1541
1542/// ParseValID - Parse an abstract value that doesn't necessarily have a
1543/// type implied. For example, if we parse "4" we don't know what integer type
1544/// it has. The value will later be combined with its type and checked for
1545/// sanity.
1546bool LLParser::ParseValID(ValID &ID) {
1547 ID.Loc = Lex.getLoc();
1548 switch (Lex.getKind()) {
1549 default: return TokError("expected value token");
1550 case lltok::GlobalID: // @42
1551 ID.UIntVal = Lex.getUIntVal();
1552 ID.Kind = ValID::t_GlobalID;
1553 break;
1554 case lltok::GlobalVar: // @foo
1555 ID.StrVal = Lex.getStrVal();
1556 ID.Kind = ValID::t_GlobalName;
1557 break;
1558 case lltok::LocalVarID: // %42
1559 ID.UIntVal = Lex.getUIntVal();
1560 ID.Kind = ValID::t_LocalID;
1561 break;
1562 case lltok::LocalVar: // %foo
1563 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1564 ID.StrVal = Lex.getStrVal();
1565 ID.Kind = ValID::t_LocalName;
1566 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001567 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1568 ID.Kind = ValID::t_Constant;
1569 Lex.Lex();
1570 if (Lex.getKind() == lltok::lbrace) {
1571 // MDNode:
1572 // ::= '!' '{' TypeAndValue (',' TypeAndValue)* '}'
1573 SmallVector<Constant*, 16> Elts;
1574 if (ParseMDNodeVector(Elts) ||
1575 ParseToken(lltok::rbrace, "expected end of metadata node"))
1576 return true;
1577
1578 ID.ConstantVal = MDNode::get(&Elts[0], Elts.size());
1579 return false;
1580 }
1581
1582 // MDString:
1583 // ::= '!' STRINGCONSTANT
1584 std::string Str;
1585 if (ParseStringConstant(Str)) return true;
1586
1587 ID.ConstantVal = MDString::get(Str.data(), Str.data() + Str.size());
1588 return false;
1589 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001590 case lltok::APSInt:
1591 ID.APSIntVal = Lex.getAPSIntVal();
1592 ID.Kind = ValID::t_APSInt;
1593 break;
1594 case lltok::APFloat:
1595 ID.APFloatVal = Lex.getAPFloatVal();
1596 ID.Kind = ValID::t_APFloat;
1597 break;
1598 case lltok::kw_true:
1599 ID.ConstantVal = ConstantInt::getTrue();
1600 ID.Kind = ValID::t_Constant;
1601 break;
1602 case lltok::kw_false:
1603 ID.ConstantVal = ConstantInt::getFalse();
1604 ID.Kind = ValID::t_Constant;
1605 break;
1606 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1607 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1608 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1609
1610 case lltok::lbrace: {
1611 // ValID ::= '{' ConstVector '}'
1612 Lex.Lex();
1613 SmallVector<Constant*, 16> Elts;
1614 if (ParseGlobalValueVector(Elts) ||
1615 ParseToken(lltok::rbrace, "expected end of struct constant"))
1616 return true;
1617
1618 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
1619 ID.Kind = ValID::t_Constant;
1620 return false;
1621 }
1622 case lltok::less: {
1623 // ValID ::= '<' ConstVector '>' --> Vector.
1624 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1625 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001626 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001627
1628 SmallVector<Constant*, 16> Elts;
1629 LocTy FirstEltLoc = Lex.getLoc();
1630 if (ParseGlobalValueVector(Elts) ||
1631 (isPackedStruct &&
1632 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1633 ParseToken(lltok::greater, "expected end of constant"))
1634 return true;
1635
1636 if (isPackedStruct) {
1637 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
1638 ID.Kind = ValID::t_Constant;
1639 return false;
1640 }
1641
1642 if (Elts.empty())
1643 return Error(ID.Loc, "constant vector must not be empty");
1644
1645 if (!Elts[0]->getType()->isInteger() &&
1646 !Elts[0]->getType()->isFloatingPoint())
1647 return Error(FirstEltLoc,
1648 "vector elements must have integer or floating point type");
1649
1650 // Verify that all the vector elements have the same type.
1651 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1652 if (Elts[i]->getType() != Elts[0]->getType())
1653 return Error(FirstEltLoc,
1654 "vector element #" + utostr(i) +
1655 " is not of type '" + Elts[0]->getType()->getDescription());
1656
1657 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
1658 ID.Kind = ValID::t_Constant;
1659 return false;
1660 }
1661 case lltok::lsquare: { // Array Constant
1662 Lex.Lex();
1663 SmallVector<Constant*, 16> Elts;
1664 LocTy FirstEltLoc = Lex.getLoc();
1665 if (ParseGlobalValueVector(Elts) ||
1666 ParseToken(lltok::rsquare, "expected end of array constant"))
1667 return true;
1668
1669 // Handle empty element.
1670 if (Elts.empty()) {
1671 // Use undef instead of an array because it's inconvenient to determine
1672 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001673 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001674 return false;
1675 }
1676
1677 if (!Elts[0]->getType()->isFirstClassType())
1678 return Error(FirstEltLoc, "invalid array element type: " +
1679 Elts[0]->getType()->getDescription());
1680
1681 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1682
1683 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001684 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001685 if (Elts[i]->getType() != Elts[0]->getType())
1686 return Error(FirstEltLoc,
1687 "array element #" + utostr(i) +
1688 " is not of type '" +Elts[0]->getType()->getDescription());
1689 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001690
Chris Lattnerdf986172009-01-02 07:01:27 +00001691 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
1692 ID.Kind = ValID::t_Constant;
1693 return false;
1694 }
1695 case lltok::kw_c: // c "foo"
1696 Lex.Lex();
1697 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1698 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1699 ID.Kind = ValID::t_Constant;
1700 return false;
1701
1702 case lltok::kw_asm: {
1703 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1704 bool HasSideEffect;
1705 Lex.Lex();
1706 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001707 ParseStringConstant(ID.StrVal) ||
1708 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001709 ParseToken(lltok::StringConstant, "expected constraint string"))
1710 return true;
1711 ID.StrVal2 = Lex.getStrVal();
1712 ID.UIntVal = HasSideEffect;
1713 ID.Kind = ValID::t_InlineAsm;
1714 return false;
1715 }
1716
1717 case lltok::kw_trunc:
1718 case lltok::kw_zext:
1719 case lltok::kw_sext:
1720 case lltok::kw_fptrunc:
1721 case lltok::kw_fpext:
1722 case lltok::kw_bitcast:
1723 case lltok::kw_uitofp:
1724 case lltok::kw_sitofp:
1725 case lltok::kw_fptoui:
1726 case lltok::kw_fptosi:
1727 case lltok::kw_inttoptr:
1728 case lltok::kw_ptrtoint: {
1729 unsigned Opc = Lex.getUIntVal();
1730 PATypeHolder DestTy(Type::VoidTy);
1731 Constant *SrcVal;
1732 Lex.Lex();
1733 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1734 ParseGlobalTypeAndValue(SrcVal) ||
1735 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1736 ParseType(DestTy) ||
1737 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1738 return true;
1739 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1740 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1741 SrcVal->getType()->getDescription() + "' to '" +
1742 DestTy->getDescription() + "'");
1743 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1744 DestTy);
1745 ID.Kind = ValID::t_Constant;
1746 return false;
1747 }
1748 case lltok::kw_extractvalue: {
1749 Lex.Lex();
1750 Constant *Val;
1751 SmallVector<unsigned, 4> Indices;
1752 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1753 ParseGlobalTypeAndValue(Val) ||
1754 ParseIndexList(Indices) ||
1755 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1756 return true;
1757 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1758 return Error(ID.Loc, "extractvalue operand must be array or struct");
1759 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1760 Indices.end()))
1761 return Error(ID.Loc, "invalid indices for extractvalue");
1762 ID.ConstantVal = ConstantExpr::getExtractValue(Val,
1763 &Indices[0], Indices.size());
1764 ID.Kind = ValID::t_Constant;
1765 return false;
1766 }
1767 case lltok::kw_insertvalue: {
1768 Lex.Lex();
1769 Constant *Val0, *Val1;
1770 SmallVector<unsigned, 4> Indices;
1771 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1772 ParseGlobalTypeAndValue(Val0) ||
1773 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1774 ParseGlobalTypeAndValue(Val1) ||
1775 ParseIndexList(Indices) ||
1776 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1777 return true;
1778 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1779 return Error(ID.Loc, "extractvalue operand must be array or struct");
1780 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1781 Indices.end()))
1782 return Error(ID.Loc, "invalid indices for insertvalue");
1783 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1784 &Indices[0], Indices.size());
1785 ID.Kind = ValID::t_Constant;
1786 return false;
1787 }
1788 case lltok::kw_icmp:
1789 case lltok::kw_fcmp:
1790 case lltok::kw_vicmp:
1791 case lltok::kw_vfcmp: {
1792 unsigned PredVal, Opc = Lex.getUIntVal();
1793 Constant *Val0, *Val1;
1794 Lex.Lex();
1795 if (ParseCmpPredicate(PredVal, Opc) ||
1796 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1797 ParseGlobalTypeAndValue(Val0) ||
1798 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1799 ParseGlobalTypeAndValue(Val1) ||
1800 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1801 return true;
1802
1803 if (Val0->getType() != Val1->getType())
1804 return Error(ID.Loc, "compare operands must have the same type");
1805
1806 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1807
1808 if (Opc == Instruction::FCmp) {
1809 if (!Val0->getType()->isFPOrFPVector())
1810 return Error(ID.Loc, "fcmp requires floating point operands");
1811 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1812 } else if (Opc == Instruction::ICmp) {
1813 if (!Val0->getType()->isIntOrIntVector() &&
1814 !isa<PointerType>(Val0->getType()))
1815 return Error(ID.Loc, "icmp requires pointer or integer operands");
1816 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1817 } else if (Opc == Instruction::VFCmp) {
1818 // FIXME: REMOVE VFCMP Support
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001819 if (!Val0->getType()->isFPOrFPVector() ||
1820 !isa<VectorType>(Val0->getType()))
1821 return Error(ID.Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001822 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1823 } else if (Opc == Instruction::VICmp) {
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001824 // FIXME: REMOVE VICMP Support
1825 if (!Val0->getType()->isIntOrIntVector() ||
1826 !isa<VectorType>(Val0->getType()))
1827 return Error(ID.Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001828 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1829 }
1830 ID.Kind = ValID::t_Constant;
1831 return false;
1832 }
1833
1834 // Binary Operators.
1835 case lltok::kw_add:
1836 case lltok::kw_sub:
1837 case lltok::kw_mul:
1838 case lltok::kw_udiv:
1839 case lltok::kw_sdiv:
1840 case lltok::kw_fdiv:
1841 case lltok::kw_urem:
1842 case lltok::kw_srem:
1843 case lltok::kw_frem: {
1844 unsigned Opc = Lex.getUIntVal();
1845 Constant *Val0, *Val1;
1846 Lex.Lex();
1847 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1848 ParseGlobalTypeAndValue(Val0) ||
1849 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1850 ParseGlobalTypeAndValue(Val1) ||
1851 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1852 return true;
1853 if (Val0->getType() != Val1->getType())
1854 return Error(ID.Loc, "operands of constexpr must have same type");
1855 if (!Val0->getType()->isIntOrIntVector() &&
1856 !Val0->getType()->isFPOrFPVector())
1857 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1858 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1859 ID.Kind = ValID::t_Constant;
1860 return false;
1861 }
1862
1863 // Logical Operations
1864 case lltok::kw_shl:
1865 case lltok::kw_lshr:
1866 case lltok::kw_ashr:
1867 case lltok::kw_and:
1868 case lltok::kw_or:
1869 case lltok::kw_xor: {
1870 unsigned Opc = Lex.getUIntVal();
1871 Constant *Val0, *Val1;
1872 Lex.Lex();
1873 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1874 ParseGlobalTypeAndValue(Val0) ||
1875 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1876 ParseGlobalTypeAndValue(Val1) ||
1877 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1878 return true;
1879 if (Val0->getType() != Val1->getType())
1880 return Error(ID.Loc, "operands of constexpr must have same type");
1881 if (!Val0->getType()->isIntOrIntVector())
1882 return Error(ID.Loc,
1883 "constexpr requires integer or integer vector operands");
1884 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1885 ID.Kind = ValID::t_Constant;
1886 return false;
1887 }
1888
1889 case lltok::kw_getelementptr:
1890 case lltok::kw_shufflevector:
1891 case lltok::kw_insertelement:
1892 case lltok::kw_extractelement:
1893 case lltok::kw_select: {
1894 unsigned Opc = Lex.getUIntVal();
1895 SmallVector<Constant*, 16> Elts;
1896 Lex.Lex();
1897 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1898 ParseGlobalValueVector(Elts) ||
1899 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1900 return true;
1901
1902 if (Opc == Instruction::GetElementPtr) {
1903 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1904 return Error(ID.Loc, "getelementptr requires pointer operand");
1905
1906 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1907 (Value**)&Elts[1], Elts.size()-1))
1908 return Error(ID.Loc, "invalid indices for getelementptr");
1909 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1910 &Elts[1], Elts.size()-1);
1911 } else if (Opc == Instruction::Select) {
1912 if (Elts.size() != 3)
1913 return Error(ID.Loc, "expected three operands to select");
1914 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1915 Elts[2]))
1916 return Error(ID.Loc, Reason);
1917 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1918 } else if (Opc == Instruction::ShuffleVector) {
1919 if (Elts.size() != 3)
1920 return Error(ID.Loc, "expected three operands to shufflevector");
1921 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1922 return Error(ID.Loc, "invalid operands to shufflevector");
1923 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1924 } else if (Opc == Instruction::ExtractElement) {
1925 if (Elts.size() != 2)
1926 return Error(ID.Loc, "expected two operands to extractelement");
1927 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1928 return Error(ID.Loc, "invalid extractelement operands");
1929 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1930 } else {
1931 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1932 if (Elts.size() != 3)
1933 return Error(ID.Loc, "expected three operands to insertelement");
1934 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1935 return Error(ID.Loc, "invalid insertelement operands");
1936 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1937 }
1938
1939 ID.Kind = ValID::t_Constant;
1940 return false;
1941 }
1942 }
1943
1944 Lex.Lex();
1945 return false;
1946}
1947
1948/// ParseGlobalValue - Parse a global value with the specified type.
1949bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1950 V = 0;
1951 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001952 return ParseValID(ID) ||
1953 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00001954}
1955
1956/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1957/// constant.
1958bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1959 Constant *&V) {
1960 if (isa<FunctionType>(Ty))
1961 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1962
1963 switch (ID.Kind) {
1964 default: assert(0 && "Unknown ValID!");
1965 case ValID::t_LocalID:
1966 case ValID::t_LocalName:
1967 return Error(ID.Loc, "invalid use of function-local name");
1968 case ValID::t_InlineAsm:
1969 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1970 case ValID::t_GlobalName:
1971 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1972 return V == 0;
1973 case ValID::t_GlobalID:
1974 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1975 return V == 0;
1976 case ValID::t_APSInt:
1977 if (!isa<IntegerType>(Ty))
1978 return Error(ID.Loc, "integer constant must have integer type");
1979 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1980 V = ConstantInt::get(ID.APSIntVal);
1981 return false;
1982 case ValID::t_APFloat:
1983 if (!Ty->isFloatingPoint() ||
1984 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1985 return Error(ID.Loc, "floating point constant invalid for type");
1986
1987 // The lexer has no type info, so builds all float and double FP constants
1988 // as double. Fix this here. Long double does not need this.
1989 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1990 Ty == Type::FloatTy) {
1991 bool Ignored;
1992 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1993 &Ignored);
1994 }
1995 V = ConstantFP::get(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00001996
1997 if (V->getType() != Ty)
1998 return Error(ID.Loc, "floating point constant does not have type '" +
1999 Ty->getDescription() + "'");
2000
Chris Lattnerdf986172009-01-02 07:01:27 +00002001 return false;
2002 case ValID::t_Null:
2003 if (!isa<PointerType>(Ty))
2004 return Error(ID.Loc, "null must be a pointer type");
2005 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2006 return false;
2007 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002008 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00002009 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2010 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002011 return Error(ID.Loc, "invalid type for undef constant");
Chris Lattnerdf986172009-01-02 07:01:27 +00002012 V = UndefValue::get(Ty);
2013 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002014 case ValID::t_EmptyArray:
2015 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2016 return Error(ID.Loc, "invalid empty array initializer");
2017 V = UndefValue::get(Ty);
2018 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002019 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002020 // FIXME: LabelTy should not be a first-class type.
2021 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00002022 return Error(ID.Loc, "invalid type for null constant");
2023 V = Constant::getNullValue(Ty);
2024 return false;
2025 case ValID::t_Constant:
2026 if (ID.ConstantVal->getType() != Ty)
2027 return Error(ID.Loc, "constant expression type mismatch");
2028 V = ID.ConstantVal;
2029 return false;
2030 }
2031}
2032
2033bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2034 PATypeHolder Type(Type::VoidTy);
2035 return ParseType(Type) ||
2036 ParseGlobalValue(Type, V);
2037}
2038
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002039/// ParseGlobalValueVector
2040/// ::= /*empty*/
2041/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002042bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2043 // Empty list.
2044 if (Lex.getKind() == lltok::rbrace ||
2045 Lex.getKind() == lltok::rsquare ||
2046 Lex.getKind() == lltok::greater ||
2047 Lex.getKind() == lltok::rparen)
2048 return false;
2049
2050 Constant *C;
2051 if (ParseGlobalTypeAndValue(C)) return true;
2052 Elts.push_back(C);
2053
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002054 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002055 if (ParseGlobalTypeAndValue(C)) return true;
2056 Elts.push_back(C);
2057 }
2058
2059 return false;
2060}
2061
2062
2063//===----------------------------------------------------------------------===//
2064// Function Parsing.
2065//===----------------------------------------------------------------------===//
2066
2067bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2068 PerFunctionState &PFS) {
2069 if (ID.Kind == ValID::t_LocalID)
2070 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2071 else if (ID.Kind == ValID::t_LocalName)
2072 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002073 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002074 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2075 const FunctionType *FTy =
2076 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2077 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2078 return Error(ID.Loc, "invalid type for inline asm constraint string");
2079 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2080 return false;
2081 } else {
2082 Constant *C;
2083 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2084 V = C;
2085 return false;
2086 }
2087
2088 return V == 0;
2089}
2090
2091bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2092 V = 0;
2093 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002094 return ParseValID(ID) ||
2095 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002096}
2097
2098bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2099 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002100 return ParseType(T) ||
2101 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002102}
2103
2104/// FunctionHeader
2105/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2106/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2107/// OptionalAlign OptGC
2108bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2109 // Parse the linkage.
2110 LocTy LinkageLoc = Lex.getLoc();
2111 unsigned Linkage;
2112
2113 unsigned Visibility, CC, RetAttrs;
2114 PATypeHolder RetType(Type::VoidTy);
2115 LocTy RetTypeLoc = Lex.getLoc();
2116 if (ParseOptionalLinkage(Linkage) ||
2117 ParseOptionalVisibility(Visibility) ||
2118 ParseOptionalCallingConv(CC) ||
2119 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002120 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002121 return true;
2122
2123 // Verify that the linkage is ok.
2124 switch ((GlobalValue::LinkageTypes)Linkage) {
2125 case GlobalValue::ExternalLinkage:
2126 break; // always ok.
2127 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002128 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002129 if (isDefine)
2130 return Error(LinkageLoc, "invalid linkage for function definition");
2131 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002132 case GlobalValue::PrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002133 case GlobalValue::InternalLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002134 case GlobalValue::LinkOnceAnyLinkage:
2135 case GlobalValue::LinkOnceODRLinkage:
2136 case GlobalValue::WeakAnyLinkage:
2137 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002138 case GlobalValue::DLLExportLinkage:
2139 if (!isDefine)
2140 return Error(LinkageLoc, "invalid linkage for function declaration");
2141 break;
2142 case GlobalValue::AppendingLinkage:
2143 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002144 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002145 return Error(LinkageLoc, "invalid function linkage type");
2146 }
2147
Chris Lattner99bb3152009-01-05 08:00:30 +00002148 if (!FunctionType::isValidReturnType(RetType) ||
2149 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002150 return Error(RetTypeLoc, "invalid function return type");
2151
Chris Lattnerdf986172009-01-02 07:01:27 +00002152 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002153
2154 std::string FunctionName;
2155 if (Lex.getKind() == lltok::GlobalVar) {
2156 FunctionName = Lex.getStrVal();
2157 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2158 unsigned NameID = Lex.getUIntVal();
2159
2160 if (NameID != NumberedVals.size())
2161 return TokError("function expected to be numbered '%" +
2162 utostr(NumberedVals.size()) + "'");
2163 } else {
2164 return TokError("expected function name");
2165 }
2166
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002167 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002168
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002169 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002170 return TokError("expected '(' in function argument list");
2171
2172 std::vector<ArgInfo> ArgList;
2173 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002174 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002175 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002176 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002177 std::string GC;
2178
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002179 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002180 ParseOptionalAttrs(FuncAttrs, 2) ||
2181 (EatIfPresent(lltok::kw_section) &&
2182 ParseStringConstant(Section)) ||
2183 ParseOptionalAlignment(Alignment) ||
2184 (EatIfPresent(lltok::kw_gc) &&
2185 ParseStringConstant(GC)))
2186 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002187
2188 // If the alignment was parsed as an attribute, move to the alignment field.
2189 if (FuncAttrs & Attribute::Alignment) {
2190 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2191 FuncAttrs &= ~Attribute::Alignment;
2192 }
2193
Chris Lattnerdf986172009-01-02 07:01:27 +00002194 // Okay, if we got here, the function is syntactically valid. Convert types
2195 // and do semantic checks.
2196 std::vector<const Type*> ParamTypeList;
2197 SmallVector<AttributeWithIndex, 8> Attrs;
2198 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2199 // attributes.
2200 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2201 if (FuncAttrs & ObsoleteFuncAttrs) {
2202 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2203 FuncAttrs &= ~ObsoleteFuncAttrs;
2204 }
2205
2206 if (RetAttrs != Attribute::None)
2207 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2208
2209 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2210 ParamTypeList.push_back(ArgList[i].Type);
2211 if (ArgList[i].Attrs != Attribute::None)
2212 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2213 }
2214
2215 if (FuncAttrs != Attribute::None)
2216 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2217
2218 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2219
Chris Lattnera9a9e072009-03-09 04:49:14 +00002220 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2221 RetType != Type::VoidTy)
2222 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2223
Chris Lattnerdf986172009-01-02 07:01:27 +00002224 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2225 const PointerType *PFT = PointerType::getUnqual(FT);
2226
2227 Fn = 0;
2228 if (!FunctionName.empty()) {
2229 // If this was a definition of a forward reference, remove the definition
2230 // from the forward reference table and fill in the forward ref.
2231 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2232 ForwardRefVals.find(FunctionName);
2233 if (FRVI != ForwardRefVals.end()) {
2234 Fn = M->getFunction(FunctionName);
2235 ForwardRefVals.erase(FRVI);
2236 } else if ((Fn = M->getFunction(FunctionName))) {
2237 // If this function already exists in the symbol table, then it is
2238 // multiply defined. We accept a few cases for old backwards compat.
2239 // FIXME: Remove this stuff for LLVM 3.0.
2240 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2241 (!Fn->isDeclaration() && isDefine)) {
2242 // If the redefinition has different type or different attributes,
2243 // reject it. If both have bodies, reject it.
2244 return Error(NameLoc, "invalid redefinition of function '" +
2245 FunctionName + "'");
2246 } else if (Fn->isDeclaration()) {
2247 // Make sure to strip off any argument names so we can't get conflicts.
2248 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2249 AI != AE; ++AI)
2250 AI->setName("");
2251 }
2252 }
2253
2254 } else if (FunctionName.empty()) {
2255 // If this is a definition of a forward referenced function, make sure the
2256 // types agree.
2257 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2258 = ForwardRefValIDs.find(NumberedVals.size());
2259 if (I != ForwardRefValIDs.end()) {
2260 Fn = cast<Function>(I->second.first);
2261 if (Fn->getType() != PFT)
2262 return Error(NameLoc, "type of definition and forward reference of '@" +
2263 utostr(NumberedVals.size()) +"' disagree");
2264 ForwardRefValIDs.erase(I);
2265 }
2266 }
2267
2268 if (Fn == 0)
2269 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2270 else // Move the forward-reference to the correct spot in the module.
2271 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2272
2273 if (FunctionName.empty())
2274 NumberedVals.push_back(Fn);
2275
2276 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2277 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2278 Fn->setCallingConv(CC);
2279 Fn->setAttributes(PAL);
2280 Fn->setAlignment(Alignment);
2281 Fn->setSection(Section);
2282 if (!GC.empty()) Fn->setGC(GC.c_str());
2283
2284 // Add all of the arguments we parsed to the function.
2285 Function::arg_iterator ArgIt = Fn->arg_begin();
2286 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2287 // If the argument has a name, insert it into the argument symbol table.
2288 if (ArgList[i].Name.empty()) continue;
2289
2290 // Set the name, if it conflicted, it will be auto-renamed.
2291 ArgIt->setName(ArgList[i].Name);
2292
2293 if (ArgIt->getNameStr() != ArgList[i].Name)
2294 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2295 ArgList[i].Name + "'");
2296 }
2297
2298 return false;
2299}
2300
2301
2302/// ParseFunctionBody
2303/// ::= '{' BasicBlock+ '}'
2304/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2305///
2306bool LLParser::ParseFunctionBody(Function &Fn) {
2307 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2308 return TokError("expected '{' in function body");
2309 Lex.Lex(); // eat the {.
2310
2311 PerFunctionState PFS(*this, Fn);
2312
2313 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2314 if (ParseBasicBlock(PFS)) return true;
2315
2316 // Eat the }.
2317 Lex.Lex();
2318
2319 // Verify function is ok.
2320 return PFS.VerifyFunctionComplete();
2321}
2322
2323/// ParseBasicBlock
2324/// ::= LabelStr? Instruction*
2325bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2326 // If this basic block starts out with a name, remember it.
2327 std::string Name;
2328 LocTy NameLoc = Lex.getLoc();
2329 if (Lex.getKind() == lltok::LabelStr) {
2330 Name = Lex.getStrVal();
2331 Lex.Lex();
2332 }
2333
2334 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2335 if (BB == 0) return true;
2336
2337 std::string NameStr;
2338
2339 // Parse the instructions in this block until we get a terminator.
2340 Instruction *Inst;
2341 do {
2342 // This instruction may have three possibilities for a name: a) none
2343 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2344 LocTy NameLoc = Lex.getLoc();
2345 int NameID = -1;
2346 NameStr = "";
2347
2348 if (Lex.getKind() == lltok::LocalVarID) {
2349 NameID = Lex.getUIntVal();
2350 Lex.Lex();
2351 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2352 return true;
2353 } else if (Lex.getKind() == lltok::LocalVar ||
2354 // FIXME: REMOVE IN LLVM 3.0
2355 Lex.getKind() == lltok::StringConstant) {
2356 NameStr = Lex.getStrVal();
2357 Lex.Lex();
2358 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2359 return true;
2360 }
2361
2362 if (ParseInstruction(Inst, BB, PFS)) return true;
2363
2364 BB->getInstList().push_back(Inst);
2365
2366 // Set the name on the instruction.
2367 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2368 } while (!isa<TerminatorInst>(Inst));
2369
2370 return false;
2371}
2372
2373//===----------------------------------------------------------------------===//
2374// Instruction Parsing.
2375//===----------------------------------------------------------------------===//
2376
2377/// ParseInstruction - Parse one of the many different instructions.
2378///
2379bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2380 PerFunctionState &PFS) {
2381 lltok::Kind Token = Lex.getKind();
2382 if (Token == lltok::Eof)
2383 return TokError("found end of file when expecting more instructions");
2384 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002385 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002386 Lex.Lex(); // Eat the keyword.
2387
2388 switch (Token) {
2389 default: return Error(Loc, "expected instruction opcode");
2390 // Terminator Instructions.
2391 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2392 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2393 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2394 case lltok::kw_br: return ParseBr(Inst, PFS);
2395 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2396 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2397 // Binary Operators.
2398 case lltok::kw_add:
2399 case lltok::kw_sub:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002400 case lltok::kw_mul: return ParseArithmetic(Inst, PFS, KeywordVal, 0);
Chris Lattnere914b592009-01-05 08:24:46 +00002401
Chris Lattnerdf986172009-01-02 07:01:27 +00002402 case lltok::kw_udiv:
2403 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002404 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002405 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002406 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002407 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002408 case lltok::kw_shl:
2409 case lltok::kw_lshr:
2410 case lltok::kw_ashr:
2411 case lltok::kw_and:
2412 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002413 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002414 case lltok::kw_icmp:
2415 case lltok::kw_fcmp:
2416 case lltok::kw_vicmp:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002417 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002418 // Casts.
2419 case lltok::kw_trunc:
2420 case lltok::kw_zext:
2421 case lltok::kw_sext:
2422 case lltok::kw_fptrunc:
2423 case lltok::kw_fpext:
2424 case lltok::kw_bitcast:
2425 case lltok::kw_uitofp:
2426 case lltok::kw_sitofp:
2427 case lltok::kw_fptoui:
2428 case lltok::kw_fptosi:
2429 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002430 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002431 // Other.
2432 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002433 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002434 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2435 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2436 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2437 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2438 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2439 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2440 // Memory.
2441 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002442 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002443 case lltok::kw_free: return ParseFree(Inst, PFS);
2444 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2445 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2446 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002447 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002448 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002449 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002450 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002451 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002452 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002453 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2454 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2455 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2456 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2457 }
2458}
2459
2460/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2461bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2462 // FIXME: REMOVE vicmp/vfcmp!
2463 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2464 switch (Lex.getKind()) {
2465 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2466 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2467 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2468 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2469 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2470 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2471 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2472 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2473 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2474 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2475 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2476 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2477 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2478 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2479 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2480 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2481 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2482 }
2483 } else {
2484 switch (Lex.getKind()) {
2485 default: TokError("expected icmp predicate (e.g. 'eq')");
2486 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2487 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2488 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2489 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2490 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2491 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2492 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2493 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2494 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2495 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2496 }
2497 }
2498 Lex.Lex();
2499 return false;
2500}
2501
2502//===----------------------------------------------------------------------===//
2503// Terminator Instructions.
2504//===----------------------------------------------------------------------===//
2505
2506/// ParseRet - Parse a return instruction.
2507/// ::= 'ret' void
2508/// ::= 'ret' TypeAndValue
2509/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2510bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2511 PerFunctionState &PFS) {
2512 PATypeHolder Ty(Type::VoidTy);
Chris Lattnera9a9e072009-03-09 04:49:14 +00002513 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002514
2515 if (Ty == Type::VoidTy) {
2516 Inst = ReturnInst::Create();
2517 return false;
2518 }
2519
2520 Value *RV;
2521 if (ParseValue(Ty, RV, PFS)) return true;
2522
2523 // The normal case is one return value.
2524 if (Lex.getKind() == lltok::comma) {
2525 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2526 // of 'ret {i32,i32} {i32 1, i32 2}'
2527 SmallVector<Value*, 8> RVs;
2528 RVs.push_back(RV);
2529
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002530 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002531 if (ParseTypeAndValue(RV, PFS)) return true;
2532 RVs.push_back(RV);
2533 }
2534
2535 RV = UndefValue::get(PFS.getFunction().getReturnType());
2536 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2537 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2538 BB->getInstList().push_back(I);
2539 RV = I;
2540 }
2541 }
2542 Inst = ReturnInst::Create(RV);
2543 return false;
2544}
2545
2546
2547/// ParseBr
2548/// ::= 'br' TypeAndValue
2549/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2550bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2551 LocTy Loc, Loc2;
2552 Value *Op0, *Op1, *Op2;
2553 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2554
2555 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2556 Inst = BranchInst::Create(BB);
2557 return false;
2558 }
2559
2560 if (Op0->getType() != Type::Int1Ty)
2561 return Error(Loc, "branch condition must have 'i1' type");
2562
2563 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2564 ParseTypeAndValue(Op1, Loc, PFS) ||
2565 ParseToken(lltok::comma, "expected ',' after true destination") ||
2566 ParseTypeAndValue(Op2, Loc2, PFS))
2567 return true;
2568
2569 if (!isa<BasicBlock>(Op1))
2570 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002571 if (!isa<BasicBlock>(Op2))
2572 return Error(Loc2, "true destination of branch must be a basic block");
2573
2574 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2575 return false;
2576}
2577
2578/// ParseSwitch
2579/// Instruction
2580/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2581/// JumpTable
2582/// ::= (TypeAndValue ',' TypeAndValue)*
2583bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2584 LocTy CondLoc, BBLoc;
2585 Value *Cond, *DefaultBB;
2586 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2587 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2588 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2589 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2590 return true;
2591
2592 if (!isa<IntegerType>(Cond->getType()))
2593 return Error(CondLoc, "switch condition must have integer type");
2594 if (!isa<BasicBlock>(DefaultBB))
2595 return Error(BBLoc, "default destination must be a basic block");
2596
2597 // Parse the jump table pairs.
2598 SmallPtrSet<Value*, 32> SeenCases;
2599 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2600 while (Lex.getKind() != lltok::rsquare) {
2601 Value *Constant, *DestBB;
2602
2603 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2604 ParseToken(lltok::comma, "expected ',' after case value") ||
2605 ParseTypeAndValue(DestBB, BBLoc, PFS))
2606 return true;
2607
2608 if (!SeenCases.insert(Constant))
2609 return Error(CondLoc, "duplicate case value in switch");
2610 if (!isa<ConstantInt>(Constant))
2611 return Error(CondLoc, "case value is not a constant integer");
2612 if (!isa<BasicBlock>(DestBB))
2613 return Error(BBLoc, "case destination is not a basic block");
2614
2615 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2616 cast<BasicBlock>(DestBB)));
2617 }
2618
2619 Lex.Lex(); // Eat the ']'.
2620
2621 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2622 Table.size());
2623 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2624 SI->addCase(Table[i].first, Table[i].second);
2625 Inst = SI;
2626 return false;
2627}
2628
2629/// ParseInvoke
2630/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2631/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2632bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2633 LocTy CallLoc = Lex.getLoc();
2634 unsigned CC, RetAttrs, FnAttrs;
2635 PATypeHolder RetType(Type::VoidTy);
2636 LocTy RetTypeLoc;
2637 ValID CalleeID;
2638 SmallVector<ParamInfo, 16> ArgList;
2639
2640 Value *NormalBB, *UnwindBB;
2641 if (ParseOptionalCallingConv(CC) ||
2642 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002643 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002644 ParseValID(CalleeID) ||
2645 ParseParameterList(ArgList, PFS) ||
2646 ParseOptionalAttrs(FnAttrs, 2) ||
2647 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2648 ParseTypeAndValue(NormalBB, PFS) ||
2649 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2650 ParseTypeAndValue(UnwindBB, PFS))
2651 return true;
2652
2653 if (!isa<BasicBlock>(NormalBB))
2654 return Error(CallLoc, "normal destination is not a basic block");
2655 if (!isa<BasicBlock>(UnwindBB))
2656 return Error(CallLoc, "unwind destination is not a basic block");
2657
2658 // If RetType is a non-function pointer type, then this is the short syntax
2659 // for the call, which means that RetType is just the return type. Infer the
2660 // rest of the function argument types from the arguments that are present.
2661 const PointerType *PFTy = 0;
2662 const FunctionType *Ty = 0;
2663 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2664 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2665 // Pull out the types of all of the arguments...
2666 std::vector<const Type*> ParamTypes;
2667 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2668 ParamTypes.push_back(ArgList[i].V->getType());
2669
2670 if (!FunctionType::isValidReturnType(RetType))
2671 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2672
2673 Ty = FunctionType::get(RetType, ParamTypes, false);
2674 PFTy = PointerType::getUnqual(Ty);
2675 }
2676
2677 // Look up the callee.
2678 Value *Callee;
2679 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2680
2681 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2682 // function attributes.
2683 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2684 if (FnAttrs & ObsoleteFuncAttrs) {
2685 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2686 FnAttrs &= ~ObsoleteFuncAttrs;
2687 }
2688
2689 // Set up the Attributes for the function.
2690 SmallVector<AttributeWithIndex, 8> Attrs;
2691 if (RetAttrs != Attribute::None)
2692 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2693
2694 SmallVector<Value*, 8> Args;
2695
2696 // Loop through FunctionType's arguments and ensure they are specified
2697 // correctly. Also, gather any parameter attributes.
2698 FunctionType::param_iterator I = Ty->param_begin();
2699 FunctionType::param_iterator E = Ty->param_end();
2700 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2701 const Type *ExpectedTy = 0;
2702 if (I != E) {
2703 ExpectedTy = *I++;
2704 } else if (!Ty->isVarArg()) {
2705 return Error(ArgList[i].Loc, "too many arguments specified");
2706 }
2707
2708 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2709 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2710 ExpectedTy->getDescription() + "'");
2711 Args.push_back(ArgList[i].V);
2712 if (ArgList[i].Attrs != Attribute::None)
2713 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2714 }
2715
2716 if (I != E)
2717 return Error(CallLoc, "not enough parameters specified for call");
2718
2719 if (FnAttrs != Attribute::None)
2720 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2721
2722 // Finish off the Attributes and check them
2723 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2724
2725 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2726 cast<BasicBlock>(UnwindBB),
2727 Args.begin(), Args.end());
2728 II->setCallingConv(CC);
2729 II->setAttributes(PAL);
2730 Inst = II;
2731 return false;
2732}
2733
2734
2735
2736//===----------------------------------------------------------------------===//
2737// Binary Operators.
2738//===----------------------------------------------------------------------===//
2739
2740/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002741/// ::= ArithmeticOps TypeAndValue ',' Value
2742///
2743/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2744/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002745bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002746 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002747 LocTy Loc; Value *LHS, *RHS;
2748 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2749 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2750 ParseValue(LHS->getType(), RHS, PFS))
2751 return true;
2752
Chris Lattnere914b592009-01-05 08:24:46 +00002753 bool Valid;
2754 switch (OperandType) {
2755 default: assert(0 && "Unknown operand type!");
2756 case 0: // int or FP.
2757 Valid = LHS->getType()->isIntOrIntVector() ||
2758 LHS->getType()->isFPOrFPVector();
2759 break;
2760 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2761 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2762 }
2763
2764 if (!Valid)
2765 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002766
2767 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2768 return false;
2769}
2770
2771/// ParseLogical
2772/// ::= ArithmeticOps TypeAndValue ',' Value {
2773bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2774 unsigned Opc) {
2775 LocTy Loc; Value *LHS, *RHS;
2776 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2777 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2778 ParseValue(LHS->getType(), RHS, PFS))
2779 return true;
2780
2781 if (!LHS->getType()->isIntOrIntVector())
2782 return Error(Loc,"instruction requires integer or integer vector operands");
2783
2784 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2785 return false;
2786}
2787
2788
2789/// ParseCompare
2790/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2791/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2792/// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2793/// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2794bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2795 unsigned Opc) {
2796 // Parse the integer/fp comparison predicate.
2797 LocTy Loc;
2798 unsigned Pred;
2799 Value *LHS, *RHS;
2800 if (ParseCmpPredicate(Pred, Opc) ||
2801 ParseTypeAndValue(LHS, Loc, PFS) ||
2802 ParseToken(lltok::comma, "expected ',' after compare value") ||
2803 ParseValue(LHS->getType(), RHS, PFS))
2804 return true;
2805
2806 if (Opc == Instruction::FCmp) {
2807 if (!LHS->getType()->isFPOrFPVector())
2808 return Error(Loc, "fcmp requires floating point operands");
2809 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2810 } else if (Opc == Instruction::ICmp) {
2811 if (!LHS->getType()->isIntOrIntVector() &&
2812 !isa<PointerType>(LHS->getType()))
2813 return Error(Loc, "icmp requires integer operands");
2814 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2815 } else if (Opc == Instruction::VFCmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002816 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2817 return Error(Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002818 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2819 } else if (Opc == Instruction::VICmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002820 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2821 return Error(Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002822 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2823 }
2824 return false;
2825}
2826
2827//===----------------------------------------------------------------------===//
2828// Other Instructions.
2829//===----------------------------------------------------------------------===//
2830
2831
2832/// ParseCast
2833/// ::= CastOpc TypeAndValue 'to' Type
2834bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2835 unsigned Opc) {
2836 LocTy Loc; Value *Op;
2837 PATypeHolder DestTy(Type::VoidTy);
2838 if (ParseTypeAndValue(Op, Loc, PFS) ||
2839 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2840 ParseType(DestTy))
2841 return true;
2842
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002843 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2844 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002845 return Error(Loc, "invalid cast opcode for cast from '" +
2846 Op->getType()->getDescription() + "' to '" +
2847 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002848 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002849 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2850 return false;
2851}
2852
2853/// ParseSelect
2854/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2855bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2856 LocTy Loc;
2857 Value *Op0, *Op1, *Op2;
2858 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2859 ParseToken(lltok::comma, "expected ',' after select condition") ||
2860 ParseTypeAndValue(Op1, PFS) ||
2861 ParseToken(lltok::comma, "expected ',' after select value") ||
2862 ParseTypeAndValue(Op2, PFS))
2863 return true;
2864
2865 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2866 return Error(Loc, Reason);
2867
2868 Inst = SelectInst::Create(Op0, Op1, Op2);
2869 return false;
2870}
2871
Chris Lattner0088a5c2009-01-05 08:18:44 +00002872/// ParseVA_Arg
2873/// ::= 'va_arg' TypeAndValue ',' Type
2874bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002875 Value *Op;
2876 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002877 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00002878 if (ParseTypeAndValue(Op, PFS) ||
2879 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00002880 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002881 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00002882
2883 if (!EltTy->isFirstClassType())
2884 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002885
2886 Inst = new VAArgInst(Op, EltTy);
2887 return false;
2888}
2889
2890/// ParseExtractElement
2891/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2892bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2893 LocTy Loc;
2894 Value *Op0, *Op1;
2895 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2896 ParseToken(lltok::comma, "expected ',' after extract value") ||
2897 ParseTypeAndValue(Op1, PFS))
2898 return true;
2899
2900 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2901 return Error(Loc, "invalid extractelement operands");
2902
2903 Inst = new ExtractElementInst(Op0, Op1);
2904 return false;
2905}
2906
2907/// ParseInsertElement
2908/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2909bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2910 LocTy Loc;
2911 Value *Op0, *Op1, *Op2;
2912 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2913 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2914 ParseTypeAndValue(Op1, PFS) ||
2915 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2916 ParseTypeAndValue(Op2, PFS))
2917 return true;
2918
2919 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2920 return Error(Loc, "invalid extractelement operands");
2921
2922 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2923 return false;
2924}
2925
2926/// ParseShuffleVector
2927/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2928bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2929 LocTy Loc;
2930 Value *Op0, *Op1, *Op2;
2931 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2932 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2933 ParseTypeAndValue(Op1, PFS) ||
2934 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2935 ParseTypeAndValue(Op2, PFS))
2936 return true;
2937
2938 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2939 return Error(Loc, "invalid extractelement operands");
2940
2941 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2942 return false;
2943}
2944
2945/// ParsePHI
2946/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2947bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2948 PATypeHolder Ty(Type::VoidTy);
2949 Value *Op0, *Op1;
2950 LocTy TypeLoc = Lex.getLoc();
2951
2952 if (ParseType(Ty) ||
2953 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2954 ParseValue(Ty, Op0, PFS) ||
2955 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2956 ParseValue(Type::LabelTy, Op1, PFS) ||
2957 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2958 return true;
2959
2960 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2961 while (1) {
2962 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2963
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002964 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00002965 break;
2966
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002967 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002968 ParseValue(Ty, Op0, PFS) ||
2969 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2970 ParseValue(Type::LabelTy, Op1, PFS) ||
2971 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2972 return true;
2973 }
2974
2975 if (!Ty->isFirstClassType())
2976 return Error(TypeLoc, "phi node must have first class type");
2977
2978 PHINode *PN = PHINode::Create(Ty);
2979 PN->reserveOperandSpace(PHIVals.size());
2980 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2981 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2982 Inst = PN;
2983 return false;
2984}
2985
2986/// ParseCall
2987/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2988/// ParameterList OptionalAttrs
2989bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
2990 bool isTail) {
2991 unsigned CC, RetAttrs, FnAttrs;
2992 PATypeHolder RetType(Type::VoidTy);
2993 LocTy RetTypeLoc;
2994 ValID CalleeID;
2995 SmallVector<ParamInfo, 16> ArgList;
2996 LocTy CallLoc = Lex.getLoc();
2997
2998 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
2999 ParseOptionalCallingConv(CC) ||
3000 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003001 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003002 ParseValID(CalleeID) ||
3003 ParseParameterList(ArgList, PFS) ||
3004 ParseOptionalAttrs(FnAttrs, 2))
3005 return true;
3006
3007 // If RetType is a non-function pointer type, then this is the short syntax
3008 // for the call, which means that RetType is just the return type. Infer the
3009 // rest of the function argument types from the arguments that are present.
3010 const PointerType *PFTy = 0;
3011 const FunctionType *Ty = 0;
3012 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3013 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3014 // Pull out the types of all of the arguments...
3015 std::vector<const Type*> ParamTypes;
3016 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3017 ParamTypes.push_back(ArgList[i].V->getType());
3018
3019 if (!FunctionType::isValidReturnType(RetType))
3020 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3021
3022 Ty = FunctionType::get(RetType, ParamTypes, false);
3023 PFTy = PointerType::getUnqual(Ty);
3024 }
3025
3026 // Look up the callee.
3027 Value *Callee;
3028 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3029
Chris Lattnerdf986172009-01-02 07:01:27 +00003030 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3031 // function attributes.
3032 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3033 if (FnAttrs & ObsoleteFuncAttrs) {
3034 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3035 FnAttrs &= ~ObsoleteFuncAttrs;
3036 }
3037
3038 // Set up the Attributes for the function.
3039 SmallVector<AttributeWithIndex, 8> Attrs;
3040 if (RetAttrs != Attribute::None)
3041 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3042
3043 SmallVector<Value*, 8> Args;
3044
3045 // Loop through FunctionType's arguments and ensure they are specified
3046 // correctly. Also, gather any parameter attributes.
3047 FunctionType::param_iterator I = Ty->param_begin();
3048 FunctionType::param_iterator E = Ty->param_end();
3049 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3050 const Type *ExpectedTy = 0;
3051 if (I != E) {
3052 ExpectedTy = *I++;
3053 } else if (!Ty->isVarArg()) {
3054 return Error(ArgList[i].Loc, "too many arguments specified");
3055 }
3056
3057 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3058 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3059 ExpectedTy->getDescription() + "'");
3060 Args.push_back(ArgList[i].V);
3061 if (ArgList[i].Attrs != Attribute::None)
3062 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3063 }
3064
3065 if (I != E)
3066 return Error(CallLoc, "not enough parameters specified for call");
3067
3068 if (FnAttrs != Attribute::None)
3069 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3070
3071 // Finish off the Attributes and check them
3072 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3073
3074 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3075 CI->setTailCall(isTail);
3076 CI->setCallingConv(CC);
3077 CI->setAttributes(PAL);
3078 Inst = CI;
3079 return false;
3080}
3081
3082//===----------------------------------------------------------------------===//
3083// Memory Instructions.
3084//===----------------------------------------------------------------------===//
3085
3086/// ParseAlloc
3087/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3088/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3089bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3090 unsigned Opc) {
3091 PATypeHolder Ty(Type::VoidTy);
3092 Value *Size = 0;
3093 LocTy SizeLoc = 0;
3094 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003095 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003096
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003097 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003098 if (Lex.getKind() == lltok::kw_align) {
3099 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003100 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3101 ParseOptionalCommaAlignment(Alignment)) {
3102 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003103 }
3104 }
3105
3106 if (Size && Size->getType() != Type::Int32Ty)
3107 return Error(SizeLoc, "element count must be i32");
3108
3109 if (Opc == Instruction::Malloc)
3110 Inst = new MallocInst(Ty, Size, Alignment);
3111 else
3112 Inst = new AllocaInst(Ty, Size, Alignment);
3113 return false;
3114}
3115
3116/// ParseFree
3117/// ::= 'free' TypeAndValue
3118bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3119 Value *Val; LocTy Loc;
3120 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3121 if (!isa<PointerType>(Val->getType()))
3122 return Error(Loc, "operand to free must be a pointer");
3123 Inst = new FreeInst(Val);
3124 return false;
3125}
3126
3127/// ParseLoad
3128/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3129bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3130 bool isVolatile) {
3131 Value *Val; LocTy Loc;
3132 unsigned Alignment;
3133 if (ParseTypeAndValue(Val, Loc, PFS) ||
3134 ParseOptionalCommaAlignment(Alignment))
3135 return true;
3136
3137 if (!isa<PointerType>(Val->getType()) ||
3138 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3139 return Error(Loc, "load operand must be a pointer to a first class type");
3140
3141 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3142 return false;
3143}
3144
3145/// ParseStore
3146/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3147bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3148 bool isVolatile) {
3149 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3150 unsigned Alignment;
3151 if (ParseTypeAndValue(Val, Loc, PFS) ||
3152 ParseToken(lltok::comma, "expected ',' after store operand") ||
3153 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3154 ParseOptionalCommaAlignment(Alignment))
3155 return true;
3156
3157 if (!isa<PointerType>(Ptr->getType()))
3158 return Error(PtrLoc, "store operand must be a pointer");
3159 if (!Val->getType()->isFirstClassType())
3160 return Error(Loc, "store operand must be a first class value");
3161 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3162 return Error(Loc, "stored value and pointer type do not match");
3163
3164 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3165 return false;
3166}
3167
3168/// ParseGetResult
3169/// ::= 'getresult' TypeAndValue ',' uint
3170/// FIXME: Remove support for getresult in LLVM 3.0
3171bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3172 Value *Val; LocTy ValLoc, EltLoc;
3173 unsigned Element;
3174 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3175 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003176 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003177 return true;
3178
3179 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3180 return Error(ValLoc, "getresult inst requires an aggregate operand");
3181 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3182 return Error(EltLoc, "invalid getresult index for value");
3183 Inst = ExtractValueInst::Create(Val, Element);
3184 return false;
3185}
3186
3187/// ParseGetElementPtr
3188/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3189bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3190 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003191 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003192
3193 if (!isa<PointerType>(Ptr->getType()))
3194 return Error(Loc, "base of getelementptr must be a pointer");
3195
3196 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003197 while (EatIfPresent(lltok::comma)) {
3198 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003199 if (!isa<IntegerType>(Val->getType()))
3200 return Error(EltLoc, "getelementptr index must be an integer");
3201 Indices.push_back(Val);
3202 }
3203
3204 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3205 Indices.begin(), Indices.end()))
3206 return Error(Loc, "invalid getelementptr indices");
3207 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3208 return false;
3209}
3210
3211/// ParseExtractValue
3212/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3213bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3214 Value *Val; LocTy Loc;
3215 SmallVector<unsigned, 4> Indices;
3216 if (ParseTypeAndValue(Val, Loc, PFS) ||
3217 ParseIndexList(Indices))
3218 return true;
3219
3220 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3221 return Error(Loc, "extractvalue operand must be array or struct");
3222
3223 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3224 Indices.end()))
3225 return Error(Loc, "invalid indices for extractvalue");
3226 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3227 return false;
3228}
3229
3230/// ParseInsertValue
3231/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3232bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3233 Value *Val0, *Val1; LocTy Loc0, Loc1;
3234 SmallVector<unsigned, 4> Indices;
3235 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3236 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3237 ParseTypeAndValue(Val1, Loc1, PFS) ||
3238 ParseIndexList(Indices))
3239 return true;
3240
3241 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3242 return Error(Loc0, "extractvalue operand must be array or struct");
3243
3244 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3245 Indices.end()))
3246 return Error(Loc0, "invalid indices for insertvalue");
3247 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3248 return false;
3249}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003250
3251//===----------------------------------------------------------------------===//
3252// Embedded metadata.
3253//===----------------------------------------------------------------------===//
3254
3255/// ParseMDNodeVector
3256/// ::= TypeAndValue (',' TypeAndValue)*
3257bool LLParser::ParseMDNodeVector(SmallVectorImpl<Constant*> &Elts) {
3258 assert(Lex.getKind() == lltok::lbrace);
3259 Lex.Lex();
3260 do {
3261 Constant *C;
3262 if (ParseGlobalTypeAndValue(C)) return true;
3263 Elts.push_back(C);
3264 } while (EatIfPresent(lltok::comma));
3265
3266 return false;
3267}