blob: c13737aae5259d0369efbb476c3f70596369a823 [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') ...
116 case lltok::kw_internal: // OptionalLinkage
117 case lltok::kw_weak: // OptionalLinkage
118 case lltok::kw_linkonce: // OptionalLinkage
119 case lltok::kw_appending: // OptionalLinkage
120 case lltok::kw_dllexport: // OptionalLinkage
121 case lltok::kw_common: // OptionalLinkage
122 case lltok::kw_dllimport: // OptionalLinkage
123 case lltok::kw_extern_weak: // OptionalLinkage
124 case lltok::kw_external: { // OptionalLinkage
125 unsigned Linkage, Visibility;
126 if (ParseOptionalLinkage(Linkage) ||
127 ParseOptionalVisibility(Visibility) ||
128 ParseGlobal("", 0, Linkage, true, Visibility))
129 return true;
130 break;
131 }
132 case lltok::kw_default: // OptionalVisibility
133 case lltok::kw_hidden: // OptionalVisibility
134 case lltok::kw_protected: { // OptionalVisibility
135 unsigned Visibility;
136 if (ParseOptionalVisibility(Visibility) ||
137 ParseGlobal("", 0, 0, false, Visibility))
138 return true;
139 break;
140 }
141
142 case lltok::kw_thread_local: // OptionalThreadLocal
143 case lltok::kw_addrspace: // OptionalAddrSpace
144 case lltok::kw_constant: // GlobalType
145 case lltok::kw_global: // GlobalType
146 if (ParseGlobal("", 0, 0, false, 0)) return true;
147 break;
148 }
149 }
150}
151
152
153/// toplevelentity
154/// ::= 'module' 'asm' STRINGCONSTANT
155bool LLParser::ParseModuleAsm() {
156 assert(Lex.getKind() == lltok::kw_module);
157 Lex.Lex();
158
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000159 std::string AsmStr;
160 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
161 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000162
163 const std::string &AsmSoFar = M->getModuleInlineAsm();
164 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000165 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000166 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000167 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000168 return false;
169}
170
171/// toplevelentity
172/// ::= 'target' 'triple' '=' STRINGCONSTANT
173/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
174bool LLParser::ParseTargetDefinition() {
175 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000176 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000177 switch (Lex.Lex()) {
178 default: return TokError("unknown target property");
179 case lltok::kw_triple:
180 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000181 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
182 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000183 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000184 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000185 return false;
186 case lltok::kw_datalayout:
187 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000188 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
189 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000190 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000191 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000192 return false;
193 }
194}
195
196/// toplevelentity
197/// ::= 'deplibs' '=' '[' ']'
198/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
199bool LLParser::ParseDepLibs() {
200 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000201 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000202 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
203 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
204 return true;
205
206 if (EatIfPresent(lltok::rsquare))
207 return false;
208
209 std::string Str;
210 if (ParseStringConstant(Str)) return true;
211 M->addLibrary(Str);
212
213 while (EatIfPresent(lltok::comma)) {
214 if (ParseStringConstant(Str)) return true;
215 M->addLibrary(Str);
216 }
217
218 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000219}
220
221/// toplevelentity
222/// ::= 'type' type
223bool LLParser::ParseUnnamedType() {
224 assert(Lex.getKind() == lltok::kw_type);
225 LocTy TypeLoc = Lex.getLoc();
226 Lex.Lex(); // eat kw_type
227
228 PATypeHolder Ty(Type::VoidTy);
229 if (ParseType(Ty)) return true;
230
231 unsigned TypeID = NumberedTypes.size();
232
233 // We don't allow assigning names to void type
234 if (Ty == Type::VoidTy)
235 return Error(TypeLoc, "can't assign name to the void type");
236
237 // See if this type was previously referenced.
238 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
239 FI = ForwardRefTypeIDs.find(TypeID);
240 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000241 if (FI->second.first.get() == Ty)
242 return Error(TypeLoc, "self referential type is invalid");
243
Chris Lattnerdf986172009-01-02 07:01:27 +0000244 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
245 Ty = FI->second.first.get();
246 ForwardRefTypeIDs.erase(FI);
247 }
248
249 NumberedTypes.push_back(Ty);
250
251 return false;
252}
253
254/// toplevelentity
255/// ::= LocalVar '=' 'type' type
256bool LLParser::ParseNamedType() {
257 std::string Name = Lex.getStrVal();
258 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000259 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000260
261 PATypeHolder Ty(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000262
263 if (ParseToken(lltok::equal, "expected '=' after name") ||
264 ParseToken(lltok::kw_type, "expected 'type' after name") ||
265 ParseType(Ty))
266 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000267
268 // We don't allow assigning names to void type
269 if (Ty == Type::VoidTy)
270 return Error(NameLoc, "can't assign name '" + Name + "' to the void type");
271
272 // Set the type name, checking for conflicts as we do so.
273 bool AlreadyExists = M->addTypeName(Name, Ty);
274 if (!AlreadyExists) return false;
275
276 // See if this type is a forward reference. We need to eagerly resolve
277 // types to allow recursive type redefinitions below.
278 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
279 FI = ForwardRefTypes.find(Name);
280 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000281 if (FI->second.first.get() == Ty)
282 return Error(NameLoc, "self referential type is invalid");
283
Chris Lattnerdf986172009-01-02 07:01:27 +0000284 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
285 Ty = FI->second.first.get();
286 ForwardRefTypes.erase(FI);
287 }
288
289 // Inserting a name that is already defined, get the existing name.
290 const Type *Existing = M->getTypeByName(Name);
291 assert(Existing && "Conflict but no matching type?!");
292
293 // Otherwise, this is an attempt to redefine a type. That's okay if
294 // the redefinition is identical to the original.
295 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
296 if (Existing == Ty) return false;
297
298 // Any other kind of (non-equivalent) redefinition is an error.
299 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
300 Ty->getDescription() + "'");
301}
302
303
304/// toplevelentity
305/// ::= 'declare' FunctionHeader
306bool LLParser::ParseDeclare() {
307 assert(Lex.getKind() == lltok::kw_declare);
308 Lex.Lex();
309
310 Function *F;
311 return ParseFunctionHeader(F, false);
312}
313
314/// toplevelentity
315/// ::= 'define' FunctionHeader '{' ...
316bool LLParser::ParseDefine() {
317 assert(Lex.getKind() == lltok::kw_define);
318 Lex.Lex();
319
320 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000321 return ParseFunctionHeader(F, true) ||
322 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000323}
324
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000325/// ParseGlobalType
326/// ::= 'constant'
327/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000328bool LLParser::ParseGlobalType(bool &IsConstant) {
329 if (Lex.getKind() == lltok::kw_constant)
330 IsConstant = true;
331 else if (Lex.getKind() == lltok::kw_global)
332 IsConstant = false;
333 else
334 return TokError("expected 'global' or 'constant'");
335 Lex.Lex();
336 return false;
337}
338
339/// ParseNamedGlobal:
340/// GlobalVar '=' OptionalVisibility ALIAS ...
341/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
342bool LLParser::ParseNamedGlobal() {
343 assert(Lex.getKind() == lltok::GlobalVar);
344 LocTy NameLoc = Lex.getLoc();
345 std::string Name = Lex.getStrVal();
346 Lex.Lex();
347
348 bool HasLinkage;
349 unsigned Linkage, Visibility;
350 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
351 ParseOptionalLinkage(Linkage, HasLinkage) ||
352 ParseOptionalVisibility(Visibility))
353 return true;
354
355 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
356 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
357 return ParseAlias(Name, NameLoc, Visibility);
358}
359
360/// ParseAlias:
361/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
362/// Aliasee
363/// ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')'
364///
365/// Everything through visibility has already been parsed.
366///
367bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
368 unsigned Visibility) {
369 assert(Lex.getKind() == lltok::kw_alias);
370 Lex.Lex();
371 unsigned Linkage;
372 LocTy LinkageLoc = Lex.getLoc();
373 if (ParseOptionalLinkage(Linkage))
374 return true;
375
376 if (Linkage != GlobalValue::ExternalLinkage &&
377 Linkage != GlobalValue::WeakLinkage &&
378 Linkage != GlobalValue::InternalLinkage)
379 return Error(LinkageLoc, "invalid linkage type for alias");
380
381 Constant *Aliasee;
382 LocTy AliaseeLoc = Lex.getLoc();
383 if (Lex.getKind() != lltok::kw_bitcast) {
384 if (ParseGlobalTypeAndValue(Aliasee)) return true;
385 } else {
386 // The bitcast dest type is not present, it is implied by the dest type.
387 ValID ID;
388 if (ParseValID(ID)) return true;
389 if (ID.Kind != ValID::t_Constant)
390 return Error(AliaseeLoc, "invalid aliasee");
391 Aliasee = ID.ConstantVal;
392 }
393
394 if (!isa<PointerType>(Aliasee->getType()))
395 return Error(AliaseeLoc, "alias must have pointer type");
396
397 // Okay, create the alias but do not insert it into the module yet.
398 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
399 (GlobalValue::LinkageTypes)Linkage, Name,
400 Aliasee);
401 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
402
403 // See if this value already exists in the symbol table. If so, it is either
404 // a redefinition or a definition of a forward reference.
405 if (GlobalValue *Val =
406 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
407 // See if this was a redefinition. If so, there is no entry in
408 // ForwardRefVals.
409 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
410 I = ForwardRefVals.find(Name);
411 if (I == ForwardRefVals.end())
412 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
413
414 // Otherwise, this was a definition of forward ref. Verify that types
415 // agree.
416 if (Val->getType() != GA->getType())
417 return Error(NameLoc,
418 "forward reference and definition of alias have different types");
419
420 // If they agree, just RAUW the old value with the alias and remove the
421 // forward ref info.
422 Val->replaceAllUsesWith(GA);
423 Val->eraseFromParent();
424 ForwardRefVals.erase(I);
425 }
426
427 // Insert into the module, we know its name won't collide now.
428 M->getAliasList().push_back(GA);
429 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
430
431 return false;
432}
433
434/// ParseGlobal
435/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
436/// OptionalAddrSpace GlobalType Type Const
437/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
438/// OptionalAddrSpace GlobalType Type Const
439///
440/// Everything through visibility has been parsed already.
441///
442bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
443 unsigned Linkage, bool HasLinkage,
444 unsigned Visibility) {
445 unsigned AddrSpace;
446 bool ThreadLocal, IsConstant;
447 LocTy TyLoc;
448
449 PATypeHolder Ty(Type::VoidTy);
450 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
451 ParseOptionalAddrSpace(AddrSpace) ||
452 ParseGlobalType(IsConstant) ||
453 ParseType(Ty, TyLoc))
454 return true;
455
456 // If the linkage is specified and is external, then no initializer is
457 // present.
458 Constant *Init = 0;
459 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
460 Linkage != GlobalValue::ExternalWeakLinkage &&
461 Linkage != GlobalValue::ExternalLinkage)) {
462 if (ParseGlobalValue(Ty, Init))
463 return true;
464 }
465
466 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
467 return Error(TyLoc, "invald type for global variable");
468
469 GlobalVariable *GV = 0;
470
471 // See if the global was forward referenced, if so, use the global.
472 if (!Name.empty() && (GV = M->getGlobalVariable(Name, true))) {
473 if (!ForwardRefVals.erase(Name))
474 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;
567 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
568 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
569 else
570 FwdVal = new GlobalVariable(PTy->getElementType(), false,
571 GlobalValue::ExternalWeakLinkage, 0, Name, M);
572
573 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
574 return FwdVal;
575}
576
577GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
578 const PointerType *PTy = dyn_cast<PointerType>(Ty);
579 if (PTy == 0) {
580 Error(Loc, "global variable reference must have pointer type");
581 return 0;
582 }
583
584 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
585
586 // If this is a forward reference for the value, see if we already created a
587 // forward ref record.
588 if (Val == 0) {
589 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
590 I = ForwardRefValIDs.find(ID);
591 if (I != ForwardRefValIDs.end())
592 Val = I->second.first;
593 }
594
595 // If we have the value in the symbol table or fwd-ref table, return it.
596 if (Val) {
597 if (Val->getType() == Ty) return Val;
598 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
599 Val->getType()->getDescription() + "'");
600 return 0;
601 }
602
603 // Otherwise, create a new forward reference for this value and remember it.
604 GlobalValue *FwdVal;
605 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
606 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
607 else
608 FwdVal = new GlobalVariable(PTy->getElementType(), false,
609 GlobalValue::ExternalWeakLinkage, 0, "", M);
610
611 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
612 return FwdVal;
613}
614
615
616//===----------------------------------------------------------------------===//
617// Helper Routines.
618//===----------------------------------------------------------------------===//
619
620/// ParseToken - If the current token has the specified kind, eat it and return
621/// success. Otherwise, emit the specified error and return failure.
622bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
623 if (Lex.getKind() != T)
624 return TokError(ErrMsg);
625 Lex.Lex();
626 return false;
627}
628
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000629/// ParseStringConstant
630/// ::= StringConstant
631bool LLParser::ParseStringConstant(std::string &Result) {
632 if (Lex.getKind() != lltok::StringConstant)
633 return TokError("expected string constant");
634 Result = Lex.getStrVal();
635 Lex.Lex();
636 return false;
637}
638
639/// ParseUInt32
640/// ::= uint32
641bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000642 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
643 return TokError("expected integer");
644 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
645 if (Val64 != unsigned(Val64))
646 return TokError("expected 32-bit integer (too large)");
647 Val = Val64;
648 Lex.Lex();
649 return false;
650}
651
652
653/// ParseOptionalAddrSpace
654/// := /*empty*/
655/// := 'addrspace' '(' uint32 ')'
656bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
657 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000658 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000659 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000660 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000661 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000662 ParseToken(lltok::rparen, "expected ')' in address space");
663}
664
665/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
666/// indicates what kind of attribute list this is: 0: function arg, 1: result,
667/// 2: function attr.
668bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
669 Attrs = Attribute::None;
670 LocTy AttrLoc = Lex.getLoc();
671
672 while (1) {
673 switch (Lex.getKind()) {
674 case lltok::kw_sext:
675 case lltok::kw_zext:
676 // Treat these as signext/zeroext unless they are function attrs.
677 // FIXME: REMOVE THIS IN LLVM 3.0
678 if (AttrKind != 2) {
679 if (Lex.getKind() == lltok::kw_sext)
680 Attrs |= Attribute::SExt;
681 else
682 Attrs |= Attribute::ZExt;
683 break;
684 }
685 // FALL THROUGH.
686 default: // End of attributes.
687 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
688 return Error(AttrLoc, "invalid use of function-only attribute");
689
690 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
691 return Error(AttrLoc, "invalid use of parameter-only attribute");
692
693 return false;
694 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
695 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
696 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
697 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
698 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
699 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
700 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
701 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
702
703 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
704 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
705 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
706 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
707 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
708 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
709 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
710 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
711 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
712
713
714 case lltok::kw_align: {
715 unsigned Alignment;
716 if (ParseOptionalAlignment(Alignment))
717 return true;
718 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
719 continue;
720 }
721 }
722 Lex.Lex();
723 }
724}
725
726/// ParseOptionalLinkage
727/// ::= /*empty*/
728/// ::= 'internal'
729/// ::= 'weak'
730/// ::= 'linkonce'
731/// ::= 'appending'
732/// ::= 'dllexport'
733/// ::= 'common'
734/// ::= 'dllimport'
735/// ::= 'extern_weak'
736/// ::= 'external'
737bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
738 HasLinkage = false;
739 switch (Lex.getKind()) {
740 default: Res = GlobalValue::ExternalLinkage; return false;
741 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
742 case lltok::kw_weak: Res = GlobalValue::WeakLinkage; break;
743 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceLinkage; break;
744 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
745 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
746 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
747 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
748 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
749 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
750 }
751 Lex.Lex();
752 HasLinkage = true;
753 return false;
754}
755
756/// ParseOptionalVisibility
757/// ::= /*empty*/
758/// ::= 'default'
759/// ::= 'hidden'
760/// ::= 'protected'
761///
762bool LLParser::ParseOptionalVisibility(unsigned &Res) {
763 switch (Lex.getKind()) {
764 default: Res = GlobalValue::DefaultVisibility; return false;
765 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
766 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
767 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
768 }
769 Lex.Lex();
770 return false;
771}
772
773/// ParseOptionalCallingConv
774/// ::= /*empty*/
775/// ::= 'ccc'
776/// ::= 'fastcc'
777/// ::= 'coldcc'
778/// ::= 'x86_stdcallcc'
779/// ::= 'x86_fastcallcc'
780/// ::= 'cc' UINT
781///
782bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
783 switch (Lex.getKind()) {
784 default: CC = CallingConv::C; return false;
785 case lltok::kw_ccc: CC = CallingConv::C; break;
786 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
787 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
788 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
789 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000790 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000791 }
792 Lex.Lex();
793 return false;
794}
795
796/// ParseOptionalAlignment
797/// ::= /* empty */
798/// ::= 'align' 4
799bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
800 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000801 if (!EatIfPresent(lltok::kw_align))
802 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000803 LocTy AlignLoc = Lex.getLoc();
804 if (ParseUInt32(Alignment)) return true;
805 if (!isPowerOf2_32(Alignment))
806 return Error(AlignLoc, "alignment is not a power of two");
807 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000808}
809
810/// ParseOptionalCommaAlignment
811/// ::= /* empty */
812/// ::= ',' 'align' 4
813bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
814 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000815 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000816 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000817 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000818 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000819}
820
821/// ParseIndexList
822/// ::= (',' uint32)+
823bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
824 if (Lex.getKind() != lltok::comma)
825 return TokError("expected ',' as start of index list");
826
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000827 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000828 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000829 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000830 Indices.push_back(Idx);
831 }
832
833 return false;
834}
835
836//===----------------------------------------------------------------------===//
837// Type Parsing.
838//===----------------------------------------------------------------------===//
839
840/// ParseType - Parse and resolve a full type.
841bool LLParser::ParseType(PATypeHolder &Result) {
842 if (ParseTypeRec(Result)) return true;
843
844 // Verify no unresolved uprefs.
845 if (!UpRefs.empty())
846 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000847
848 return false;
849}
850
851/// HandleUpRefs - Every time we finish a new layer of types, this function is
852/// called. It loops through the UpRefs vector, which is a list of the
853/// currently active types. For each type, if the up-reference is contained in
854/// the newly completed type, we decrement the level count. When the level
855/// count reaches zero, the up-referenced type is the type that is passed in:
856/// thus we can complete the cycle.
857///
858PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
859 // If Ty isn't abstract, or if there are no up-references in it, then there is
860 // nothing to resolve here.
861 if (!ty->isAbstract() || UpRefs.empty()) return ty;
862
863 PATypeHolder Ty(ty);
864#if 0
865 errs() << "Type '" << Ty->getDescription()
866 << "' newly formed. Resolving upreferences.\n"
867 << UpRefs.size() << " upreferences active!\n";
868#endif
869
870 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
871 // to zero), we resolve them all together before we resolve them to Ty. At
872 // the end of the loop, if there is anything to resolve to Ty, it will be in
873 // this variable.
874 OpaqueType *TypeToResolve = 0;
875
876 for (unsigned i = 0; i != UpRefs.size(); ++i) {
877 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
878 bool ContainsType =
879 std::find(Ty->subtype_begin(), Ty->subtype_end(),
880 UpRefs[i].LastContainedTy) != Ty->subtype_end();
881
882#if 0
883 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
884 << UpRefs[i].LastContainedTy->getDescription() << ") = "
885 << (ContainsType ? "true" : "false")
886 << " level=" << UpRefs[i].NestingLevel << "\n";
887#endif
888 if (!ContainsType)
889 continue;
890
891 // Decrement level of upreference
892 unsigned Level = --UpRefs[i].NestingLevel;
893 UpRefs[i].LastContainedTy = Ty;
894
895 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
896 if (Level != 0)
897 continue;
898
899#if 0
900 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
901#endif
902 if (!TypeToResolve)
903 TypeToResolve = UpRefs[i].UpRefTy;
904 else
905 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
906 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
907 --i; // Do not skip the next element.
908 }
909
910 if (TypeToResolve)
911 TypeToResolve->refineAbstractTypeTo(Ty);
912
913 return Ty;
914}
915
916
917/// ParseTypeRec - The recursive function used to process the internal
918/// implementation details of types.
919bool LLParser::ParseTypeRec(PATypeHolder &Result) {
920 switch (Lex.getKind()) {
921 default:
922 return TokError("expected type");
923 case lltok::Type:
924 // TypeRec ::= 'float' | 'void' (etc)
925 Result = Lex.getTyVal();
926 Lex.Lex();
927 break;
928 case lltok::kw_opaque:
929 // TypeRec ::= 'opaque'
930 Result = OpaqueType::get();
931 Lex.Lex();
932 break;
933 case lltok::lbrace:
934 // TypeRec ::= '{' ... '}'
935 if (ParseStructType(Result, false))
936 return true;
937 break;
938 case lltok::lsquare:
939 // TypeRec ::= '[' ... ']'
940 Lex.Lex(); // eat the lsquare.
941 if (ParseArrayVectorType(Result, false))
942 return true;
943 break;
944 case lltok::less: // Either vector or packed struct.
945 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000946 Lex.Lex();
947 if (Lex.getKind() == lltok::lbrace) {
948 if (ParseStructType(Result, true) ||
949 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +0000950 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000951 } else if (ParseArrayVectorType(Result, true))
952 return true;
953 break;
954 case lltok::LocalVar:
955 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
956 // TypeRec ::= %foo
957 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
958 Result = T;
959 } else {
960 Result = OpaqueType::get();
961 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
962 std::make_pair(Result,
963 Lex.getLoc())));
964 M->addTypeName(Lex.getStrVal(), Result.get());
965 }
966 Lex.Lex();
967 break;
968
969 case lltok::LocalVarID:
970 // TypeRec ::= %4
971 if (Lex.getUIntVal() < NumberedTypes.size())
972 Result = NumberedTypes[Lex.getUIntVal()];
973 else {
974 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
975 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
976 if (I != ForwardRefTypeIDs.end())
977 Result = I->second.first;
978 else {
979 Result = OpaqueType::get();
980 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
981 std::make_pair(Result,
982 Lex.getLoc())));
983 }
984 }
985 Lex.Lex();
986 break;
987 case lltok::backslash: {
988 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +0000989 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000990 unsigned Val;
991 if (ParseUInt32(Val)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000992 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
993 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
994 Result = OT;
995 break;
996 }
997 }
998
999 // Parse the type suffixes.
1000 while (1) {
1001 switch (Lex.getKind()) {
1002 // End of type.
1003 default: return false;
1004
1005 // TypeRec ::= TypeRec '*'
1006 case lltok::star:
1007 if (Result.get() == Type::LabelTy)
1008 return TokError("basic block pointers are invalid");
1009 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1010 Lex.Lex();
1011 break;
1012
1013 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1014 case lltok::kw_addrspace: {
1015 if (Result.get() == Type::LabelTy)
1016 return TokError("basic block pointers are invalid");
1017 unsigned AddrSpace;
1018 if (ParseOptionalAddrSpace(AddrSpace) ||
1019 ParseToken(lltok::star, "expected '*' in address space"))
1020 return true;
1021
1022 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1023 break;
1024 }
1025
1026 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1027 case lltok::lparen:
1028 if (ParseFunctionType(Result))
1029 return true;
1030 break;
1031 }
1032 }
1033}
1034
1035/// ParseParameterList
1036/// ::= '(' ')'
1037/// ::= '(' Arg (',' Arg)* ')'
1038/// Arg
1039/// ::= Type OptionalAttributes Value OptionalAttributes
1040bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1041 PerFunctionState &PFS) {
1042 if (ParseToken(lltok::lparen, "expected '(' in call"))
1043 return true;
1044
1045 while (Lex.getKind() != lltok::rparen) {
1046 // If this isn't the first argument, we need a comma.
1047 if (!ArgList.empty() &&
1048 ParseToken(lltok::comma, "expected ',' in argument list"))
1049 return true;
1050
1051 // Parse the argument.
1052 LocTy ArgLoc;
1053 PATypeHolder ArgTy(Type::VoidTy);
1054 unsigned ArgAttrs1, ArgAttrs2;
1055 Value *V;
1056 if (ParseType(ArgTy, ArgLoc) ||
1057 ParseOptionalAttrs(ArgAttrs1, 0) ||
1058 ParseValue(ArgTy, V, PFS) ||
1059 // FIXME: Should not allow attributes after the argument, remove this in
1060 // LLVM 3.0.
1061 ParseOptionalAttrs(ArgAttrs2, 0))
1062 return true;
1063 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1064 }
1065
1066 Lex.Lex(); // Lex the ')'.
1067 return false;
1068}
1069
1070
1071
1072/// ParseArgumentList
1073/// ::= '(' ArgTypeListI ')'
1074/// ArgTypeListI
1075/// ::= /*empty*/
1076/// ::= '...'
1077/// ::= ArgTypeList ',' '...'
1078/// ::= ArgType (',' ArgType)*
1079bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1080 bool &isVarArg) {
1081 isVarArg = false;
1082 assert(Lex.getKind() == lltok::lparen);
1083 Lex.Lex(); // eat the (.
1084
1085 if (Lex.getKind() == lltok::rparen) {
1086 // empty
1087 } else if (Lex.getKind() == lltok::dotdotdot) {
1088 isVarArg = true;
1089 Lex.Lex();
1090 } else {
1091 LocTy TypeLoc = Lex.getLoc();
1092 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001093 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001094 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001095
1096 if (ParseTypeRec(ArgTy) ||
1097 ParseOptionalAttrs(Attrs, 0)) return true;
1098
Chris Lattnerdf986172009-01-02 07:01:27 +00001099 if (Lex.getKind() == lltok::LocalVar ||
1100 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1101 Name = Lex.getStrVal();
1102 Lex.Lex();
1103 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001104
1105 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1106 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001107
1108 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1109
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001110 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001111 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001112 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001113 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001114 break;
1115 }
1116
1117 // Otherwise must be an argument type.
1118 TypeLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001119 if (ParseTypeRec(ArgTy) ||
1120 ParseOptionalAttrs(Attrs, 0)) return true;
1121
Chris Lattnerdf986172009-01-02 07:01:27 +00001122 if (Lex.getKind() == lltok::LocalVar ||
1123 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1124 Name = Lex.getStrVal();
1125 Lex.Lex();
1126 } else {
1127 Name = "";
1128 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001129
1130 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1131 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001132
1133 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1134 }
1135 }
1136
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001137 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001138}
1139
1140/// ParseFunctionType
1141/// ::= Type ArgumentList OptionalAttrs
1142bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1143 assert(Lex.getKind() == lltok::lparen);
1144
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001145 if (!FunctionType::isValidReturnType(Result))
1146 return TokError("invalid function return type");
1147
Chris Lattnerdf986172009-01-02 07:01:27 +00001148 std::vector<ArgInfo> ArgList;
1149 bool isVarArg;
1150 unsigned Attrs;
1151 if (ParseArgumentList(ArgList, isVarArg) ||
1152 // FIXME: Allow, but ignore attributes on function types!
1153 // FIXME: Remove in LLVM 3.0
1154 ParseOptionalAttrs(Attrs, 2))
1155 return true;
1156
1157 // Reject names on the arguments lists.
1158 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1159 if (!ArgList[i].Name.empty())
1160 return Error(ArgList[i].Loc, "argument name invalid in function type");
1161 if (!ArgList[i].Attrs != 0) {
1162 // Allow but ignore attributes on function types; this permits
1163 // auto-upgrade.
1164 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1165 }
1166 }
1167
1168 std::vector<const Type*> ArgListTy;
1169 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1170 ArgListTy.push_back(ArgList[i].Type);
1171
1172 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1173 return false;
1174}
1175
1176/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1177/// TypeRec
1178/// ::= '{' '}'
1179/// ::= '{' TypeRec (',' TypeRec)* '}'
1180/// ::= '<' '{' '}' '>'
1181/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1182bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1183 assert(Lex.getKind() == lltok::lbrace);
1184 Lex.Lex(); // Consume the '{'
1185
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001186 if (EatIfPresent(lltok::rbrace)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001187 Result = StructType::get(std::vector<const Type*>(), Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001188 return false;
1189 }
1190
1191 std::vector<PATypeHolder> ParamsList;
1192 if (ParseTypeRec(Result)) return true;
1193 ParamsList.push_back(Result);
1194
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001195 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001196 if (ParseTypeRec(Result)) return true;
1197 ParamsList.push_back(Result);
1198 }
1199
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001200 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1201 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001202
1203 std::vector<const Type*> ParamsListTy;
1204 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1205 ParamsListTy.push_back(ParamsList[i].get());
1206 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1207 return false;
1208}
1209
1210/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1211/// token has already been consumed.
1212/// TypeRec
1213/// ::= '[' APSINTVAL 'x' Types ']'
1214/// ::= '<' APSINTVAL 'x' Types '>'
1215bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1216 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1217 Lex.getAPSIntVal().getBitWidth() > 64)
1218 return TokError("expected number in address space");
1219
1220 LocTy SizeLoc = Lex.getLoc();
1221 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001222 Lex.Lex();
1223
1224 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1225 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001226
1227 LocTy TypeLoc = Lex.getLoc();
1228 PATypeHolder EltTy(Type::VoidTy);
1229 if (ParseTypeRec(EltTy)) return true;
1230
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001231 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1232 "expected end of sequential type"))
1233 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001234
1235 if (isVector) {
1236 if ((unsigned)Size != Size)
1237 return Error(SizeLoc, "size too large for vector");
1238 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1239 return Error(TypeLoc, "vector element type must be fp or integer");
1240 Result = VectorType::get(EltTy, unsigned(Size));
1241 } else {
1242 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1243 return Error(TypeLoc, "invalid array element type");
1244 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1245 }
1246 return false;
1247}
1248
1249//===----------------------------------------------------------------------===//
1250// Function Semantic Analysis.
1251//===----------------------------------------------------------------------===//
1252
1253LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1254 : P(p), F(f) {
1255
1256 // Insert unnamed arguments into the NumberedVals list.
1257 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1258 AI != E; ++AI)
1259 if (!AI->hasName())
1260 NumberedVals.push_back(AI);
1261}
1262
1263LLParser::PerFunctionState::~PerFunctionState() {
1264 // If there were any forward referenced non-basicblock values, delete them.
1265 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1266 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1267 if (!isa<BasicBlock>(I->second.first)) {
1268 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1269 ->getType()));
1270 delete I->second.first;
1271 I->second.first = 0;
1272 }
1273
1274 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1275 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1276 if (!isa<BasicBlock>(I->second.first)) {
1277 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1278 ->getType()));
1279 delete I->second.first;
1280 I->second.first = 0;
1281 }
1282}
1283
1284bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1285 if (!ForwardRefVals.empty())
1286 return P.Error(ForwardRefVals.begin()->second.second,
1287 "use of undefined value '%" + ForwardRefVals.begin()->first +
1288 "'");
1289 if (!ForwardRefValIDs.empty())
1290 return P.Error(ForwardRefValIDs.begin()->second.second,
1291 "use of undefined value '%" +
1292 utostr(ForwardRefValIDs.begin()->first) + "'");
1293 return false;
1294}
1295
1296
1297/// GetVal - Get a value with the specified name or ID, creating a
1298/// forward reference record if needed. This can return null if the value
1299/// exists but does not have the right type.
1300Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1301 const Type *Ty, LocTy Loc) {
1302 // Look this name up in the normal function symbol table.
1303 Value *Val = F.getValueSymbolTable().lookup(Name);
1304
1305 // If this is a forward reference for the value, see if we already created a
1306 // forward ref record.
1307 if (Val == 0) {
1308 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1309 I = ForwardRefVals.find(Name);
1310 if (I != ForwardRefVals.end())
1311 Val = I->second.first;
1312 }
1313
1314 // If we have the value in the symbol table or fwd-ref table, return it.
1315 if (Val) {
1316 if (Val->getType() == Ty) return Val;
1317 if (Ty == Type::LabelTy)
1318 P.Error(Loc, "'%" + Name + "' is not a basic block");
1319 else
1320 P.Error(Loc, "'%" + Name + "' defined with type '" +
1321 Val->getType()->getDescription() + "'");
1322 return 0;
1323 }
1324
1325 // Don't make placeholders with invalid type.
1326 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1327 P.Error(Loc, "invalid use of a non-first-class type");
1328 return 0;
1329 }
1330
1331 // Otherwise, create a new forward reference for this value and remember it.
1332 Value *FwdVal;
1333 if (Ty == Type::LabelTy)
1334 FwdVal = BasicBlock::Create(Name, &F);
1335 else
1336 FwdVal = new Argument(Ty, Name);
1337
1338 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1339 return FwdVal;
1340}
1341
1342Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1343 LocTy Loc) {
1344 // Look this name up in the normal function symbol table.
1345 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1346
1347 // If this is a forward reference for the value, see if we already created a
1348 // forward ref record.
1349 if (Val == 0) {
1350 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1351 I = ForwardRefValIDs.find(ID);
1352 if (I != ForwardRefValIDs.end())
1353 Val = I->second.first;
1354 }
1355
1356 // If we have the value in the symbol table or fwd-ref table, return it.
1357 if (Val) {
1358 if (Val->getType() == Ty) return Val;
1359 if (Ty == Type::LabelTy)
1360 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1361 else
1362 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1363 Val->getType()->getDescription() + "'");
1364 return 0;
1365 }
1366
1367 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1368 P.Error(Loc, "invalid use of a non-first-class type");
1369 return 0;
1370 }
1371
1372 // Otherwise, create a new forward reference for this value and remember it.
1373 Value *FwdVal;
1374 if (Ty == Type::LabelTy)
1375 FwdVal = BasicBlock::Create("", &F);
1376 else
1377 FwdVal = new Argument(Ty);
1378
1379 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1380 return FwdVal;
1381}
1382
1383/// SetInstName - After an instruction is parsed and inserted into its
1384/// basic block, this installs its name.
1385bool LLParser::PerFunctionState::SetInstName(int NameID,
1386 const std::string &NameStr,
1387 LocTy NameLoc, Instruction *Inst) {
1388 // If this instruction has void type, it cannot have a name or ID specified.
1389 if (Inst->getType() == Type::VoidTy) {
1390 if (NameID != -1 || !NameStr.empty())
1391 return P.Error(NameLoc, "instructions returning void cannot have a name");
1392 return false;
1393 }
1394
1395 // If this was a numbered instruction, verify that the instruction is the
1396 // expected value and resolve any forward references.
1397 if (NameStr.empty()) {
1398 // If neither a name nor an ID was specified, just use the next ID.
1399 if (NameID == -1)
1400 NameID = NumberedVals.size();
1401
1402 if (unsigned(NameID) != NumberedVals.size())
1403 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1404 utostr(NumberedVals.size()) + "'");
1405
1406 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1407 ForwardRefValIDs.find(NameID);
1408 if (FI != ForwardRefValIDs.end()) {
1409 if (FI->second.first->getType() != Inst->getType())
1410 return P.Error(NameLoc, "instruction forward referenced with type '" +
1411 FI->second.first->getType()->getDescription() + "'");
1412 FI->second.first->replaceAllUsesWith(Inst);
1413 ForwardRefValIDs.erase(FI);
1414 }
1415
1416 NumberedVals.push_back(Inst);
1417 return false;
1418 }
1419
1420 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1421 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1422 FI = ForwardRefVals.find(NameStr);
1423 if (FI != ForwardRefVals.end()) {
1424 if (FI->second.first->getType() != Inst->getType())
1425 return P.Error(NameLoc, "instruction forward referenced with type '" +
1426 FI->second.first->getType()->getDescription() + "'");
1427 FI->second.first->replaceAllUsesWith(Inst);
1428 ForwardRefVals.erase(FI);
1429 }
1430
1431 // Set the name on the instruction.
1432 Inst->setName(NameStr);
1433
1434 if (Inst->getNameStr() != NameStr)
1435 return P.Error(NameLoc, "multiple definition of local value named '" +
1436 NameStr + "'");
1437 return false;
1438}
1439
1440/// GetBB - Get a basic block with the specified name or ID, creating a
1441/// forward reference record if needed.
1442BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1443 LocTy Loc) {
1444 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1445}
1446
1447BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1448 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1449}
1450
1451/// DefineBB - Define the specified basic block, which is either named or
1452/// unnamed. If there is an error, this returns null otherwise it returns
1453/// the block being defined.
1454BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1455 LocTy Loc) {
1456 BasicBlock *BB;
1457 if (Name.empty())
1458 BB = GetBB(NumberedVals.size(), Loc);
1459 else
1460 BB = GetBB(Name, Loc);
1461 if (BB == 0) return 0; // Already diagnosed error.
1462
1463 // Move the block to the end of the function. Forward ref'd blocks are
1464 // inserted wherever they happen to be referenced.
1465 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1466
1467 // Remove the block from forward ref sets.
1468 if (Name.empty()) {
1469 ForwardRefValIDs.erase(NumberedVals.size());
1470 NumberedVals.push_back(BB);
1471 } else {
1472 // BB forward references are already in the function symbol table.
1473 ForwardRefVals.erase(Name);
1474 }
1475
1476 return BB;
1477}
1478
1479//===----------------------------------------------------------------------===//
1480// Constants.
1481//===----------------------------------------------------------------------===//
1482
1483/// ParseValID - Parse an abstract value that doesn't necessarily have a
1484/// type implied. For example, if we parse "4" we don't know what integer type
1485/// it has. The value will later be combined with its type and checked for
1486/// sanity.
1487bool LLParser::ParseValID(ValID &ID) {
1488 ID.Loc = Lex.getLoc();
1489 switch (Lex.getKind()) {
1490 default: return TokError("expected value token");
1491 case lltok::GlobalID: // @42
1492 ID.UIntVal = Lex.getUIntVal();
1493 ID.Kind = ValID::t_GlobalID;
1494 break;
1495 case lltok::GlobalVar: // @foo
1496 ID.StrVal = Lex.getStrVal();
1497 ID.Kind = ValID::t_GlobalName;
1498 break;
1499 case lltok::LocalVarID: // %42
1500 ID.UIntVal = Lex.getUIntVal();
1501 ID.Kind = ValID::t_LocalID;
1502 break;
1503 case lltok::LocalVar: // %foo
1504 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1505 ID.StrVal = Lex.getStrVal();
1506 ID.Kind = ValID::t_LocalName;
1507 break;
1508 case lltok::APSInt:
1509 ID.APSIntVal = Lex.getAPSIntVal();
1510 ID.Kind = ValID::t_APSInt;
1511 break;
1512 case lltok::APFloat:
1513 ID.APFloatVal = Lex.getAPFloatVal();
1514 ID.Kind = ValID::t_APFloat;
1515 break;
1516 case lltok::kw_true:
1517 ID.ConstantVal = ConstantInt::getTrue();
1518 ID.Kind = ValID::t_Constant;
1519 break;
1520 case lltok::kw_false:
1521 ID.ConstantVal = ConstantInt::getFalse();
1522 ID.Kind = ValID::t_Constant;
1523 break;
1524 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1525 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1526 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1527
1528 case lltok::lbrace: {
1529 // ValID ::= '{' ConstVector '}'
1530 Lex.Lex();
1531 SmallVector<Constant*, 16> Elts;
1532 if (ParseGlobalValueVector(Elts) ||
1533 ParseToken(lltok::rbrace, "expected end of struct constant"))
1534 return true;
1535
1536 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
1537 ID.Kind = ValID::t_Constant;
1538 return false;
1539 }
1540 case lltok::less: {
1541 // ValID ::= '<' ConstVector '>' --> Vector.
1542 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1543 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001544 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001545
1546 SmallVector<Constant*, 16> Elts;
1547 LocTy FirstEltLoc = Lex.getLoc();
1548 if (ParseGlobalValueVector(Elts) ||
1549 (isPackedStruct &&
1550 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1551 ParseToken(lltok::greater, "expected end of constant"))
1552 return true;
1553
1554 if (isPackedStruct) {
1555 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
1556 ID.Kind = ValID::t_Constant;
1557 return false;
1558 }
1559
1560 if (Elts.empty())
1561 return Error(ID.Loc, "constant vector must not be empty");
1562
1563 if (!Elts[0]->getType()->isInteger() &&
1564 !Elts[0]->getType()->isFloatingPoint())
1565 return Error(FirstEltLoc,
1566 "vector elements must have integer or floating point type");
1567
1568 // Verify that all the vector elements have the same type.
1569 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1570 if (Elts[i]->getType() != Elts[0]->getType())
1571 return Error(FirstEltLoc,
1572 "vector element #" + utostr(i) +
1573 " is not of type '" + Elts[0]->getType()->getDescription());
1574
1575 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
1576 ID.Kind = ValID::t_Constant;
1577 return false;
1578 }
1579 case lltok::lsquare: { // Array Constant
1580 Lex.Lex();
1581 SmallVector<Constant*, 16> Elts;
1582 LocTy FirstEltLoc = Lex.getLoc();
1583 if (ParseGlobalValueVector(Elts) ||
1584 ParseToken(lltok::rsquare, "expected end of array constant"))
1585 return true;
1586
1587 // Handle empty element.
1588 if (Elts.empty()) {
1589 // Use undef instead of an array because it's inconvenient to determine
1590 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001591 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001592 return false;
1593 }
1594
1595 if (!Elts[0]->getType()->isFirstClassType())
1596 return Error(FirstEltLoc, "invalid array element type: " +
1597 Elts[0]->getType()->getDescription());
1598
1599 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1600
1601 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001602 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001603 if (Elts[i]->getType() != Elts[0]->getType())
1604 return Error(FirstEltLoc,
1605 "array element #" + utostr(i) +
1606 " is not of type '" +Elts[0]->getType()->getDescription());
1607 }
1608
1609 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
1610 ID.Kind = ValID::t_Constant;
1611 return false;
1612 }
1613 case lltok::kw_c: // c "foo"
1614 Lex.Lex();
1615 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1616 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1617 ID.Kind = ValID::t_Constant;
1618 return false;
1619
1620 case lltok::kw_asm: {
1621 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1622 bool HasSideEffect;
1623 Lex.Lex();
1624 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001625 ParseStringConstant(ID.StrVal) ||
1626 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001627 ParseToken(lltok::StringConstant, "expected constraint string"))
1628 return true;
1629 ID.StrVal2 = Lex.getStrVal();
1630 ID.UIntVal = HasSideEffect;
1631 ID.Kind = ValID::t_InlineAsm;
1632 return false;
1633 }
1634
1635 case lltok::kw_trunc:
1636 case lltok::kw_zext:
1637 case lltok::kw_sext:
1638 case lltok::kw_fptrunc:
1639 case lltok::kw_fpext:
1640 case lltok::kw_bitcast:
1641 case lltok::kw_uitofp:
1642 case lltok::kw_sitofp:
1643 case lltok::kw_fptoui:
1644 case lltok::kw_fptosi:
1645 case lltok::kw_inttoptr:
1646 case lltok::kw_ptrtoint: {
1647 unsigned Opc = Lex.getUIntVal();
1648 PATypeHolder DestTy(Type::VoidTy);
1649 Constant *SrcVal;
1650 Lex.Lex();
1651 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1652 ParseGlobalTypeAndValue(SrcVal) ||
1653 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1654 ParseType(DestTy) ||
1655 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1656 return true;
1657 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1658 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1659 SrcVal->getType()->getDescription() + "' to '" +
1660 DestTy->getDescription() + "'");
1661 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1662 DestTy);
1663 ID.Kind = ValID::t_Constant;
1664 return false;
1665 }
1666 case lltok::kw_extractvalue: {
1667 Lex.Lex();
1668 Constant *Val;
1669 SmallVector<unsigned, 4> Indices;
1670 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1671 ParseGlobalTypeAndValue(Val) ||
1672 ParseIndexList(Indices) ||
1673 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1674 return true;
1675 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1676 return Error(ID.Loc, "extractvalue operand must be array or struct");
1677 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1678 Indices.end()))
1679 return Error(ID.Loc, "invalid indices for extractvalue");
1680 ID.ConstantVal = ConstantExpr::getExtractValue(Val,
1681 &Indices[0], Indices.size());
1682 ID.Kind = ValID::t_Constant;
1683 return false;
1684 }
1685 case lltok::kw_insertvalue: {
1686 Lex.Lex();
1687 Constant *Val0, *Val1;
1688 SmallVector<unsigned, 4> Indices;
1689 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1690 ParseGlobalTypeAndValue(Val0) ||
1691 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1692 ParseGlobalTypeAndValue(Val1) ||
1693 ParseIndexList(Indices) ||
1694 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1695 return true;
1696 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1697 return Error(ID.Loc, "extractvalue operand must be array or struct");
1698 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1699 Indices.end()))
1700 return Error(ID.Loc, "invalid indices for insertvalue");
1701 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1702 &Indices[0], Indices.size());
1703 ID.Kind = ValID::t_Constant;
1704 return false;
1705 }
1706 case lltok::kw_icmp:
1707 case lltok::kw_fcmp:
1708 case lltok::kw_vicmp:
1709 case lltok::kw_vfcmp: {
1710 unsigned PredVal, Opc = Lex.getUIntVal();
1711 Constant *Val0, *Val1;
1712 Lex.Lex();
1713 if (ParseCmpPredicate(PredVal, Opc) ||
1714 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1715 ParseGlobalTypeAndValue(Val0) ||
1716 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1717 ParseGlobalTypeAndValue(Val1) ||
1718 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1719 return true;
1720
1721 if (Val0->getType() != Val1->getType())
1722 return Error(ID.Loc, "compare operands must have the same type");
1723
1724 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1725
1726 if (Opc == Instruction::FCmp) {
1727 if (!Val0->getType()->isFPOrFPVector())
1728 return Error(ID.Loc, "fcmp requires floating point operands");
1729 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1730 } else if (Opc == Instruction::ICmp) {
1731 if (!Val0->getType()->isIntOrIntVector() &&
1732 !isa<PointerType>(Val0->getType()))
1733 return Error(ID.Loc, "icmp requires pointer or integer operands");
1734 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1735 } else if (Opc == Instruction::VFCmp) {
1736 // FIXME: REMOVE VFCMP Support
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001737 if (!Val0->getType()->isFPOrFPVector() ||
1738 !isa<VectorType>(Val0->getType()))
1739 return Error(ID.Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001740 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1741 } else if (Opc == Instruction::VICmp) {
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001742 // FIXME: REMOVE VICMP Support
1743 if (!Val0->getType()->isIntOrIntVector() ||
1744 !isa<VectorType>(Val0->getType()))
1745 return Error(ID.Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001746 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1747 }
1748 ID.Kind = ValID::t_Constant;
1749 return false;
1750 }
1751
1752 // Binary Operators.
1753 case lltok::kw_add:
1754 case lltok::kw_sub:
1755 case lltok::kw_mul:
1756 case lltok::kw_udiv:
1757 case lltok::kw_sdiv:
1758 case lltok::kw_fdiv:
1759 case lltok::kw_urem:
1760 case lltok::kw_srem:
1761 case lltok::kw_frem: {
1762 unsigned Opc = Lex.getUIntVal();
1763 Constant *Val0, *Val1;
1764 Lex.Lex();
1765 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1766 ParseGlobalTypeAndValue(Val0) ||
1767 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1768 ParseGlobalTypeAndValue(Val1) ||
1769 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1770 return true;
1771 if (Val0->getType() != Val1->getType())
1772 return Error(ID.Loc, "operands of constexpr must have same type");
1773 if (!Val0->getType()->isIntOrIntVector() &&
1774 !Val0->getType()->isFPOrFPVector())
1775 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1776 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1777 ID.Kind = ValID::t_Constant;
1778 return false;
1779 }
1780
1781 // Logical Operations
1782 case lltok::kw_shl:
1783 case lltok::kw_lshr:
1784 case lltok::kw_ashr:
1785 case lltok::kw_and:
1786 case lltok::kw_or:
1787 case lltok::kw_xor: {
1788 unsigned Opc = Lex.getUIntVal();
1789 Constant *Val0, *Val1;
1790 Lex.Lex();
1791 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1792 ParseGlobalTypeAndValue(Val0) ||
1793 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1794 ParseGlobalTypeAndValue(Val1) ||
1795 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1796 return true;
1797 if (Val0->getType() != Val1->getType())
1798 return Error(ID.Loc, "operands of constexpr must have same type");
1799 if (!Val0->getType()->isIntOrIntVector())
1800 return Error(ID.Loc,
1801 "constexpr requires integer or integer vector operands");
1802 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1803 ID.Kind = ValID::t_Constant;
1804 return false;
1805 }
1806
1807 case lltok::kw_getelementptr:
1808 case lltok::kw_shufflevector:
1809 case lltok::kw_insertelement:
1810 case lltok::kw_extractelement:
1811 case lltok::kw_select: {
1812 unsigned Opc = Lex.getUIntVal();
1813 SmallVector<Constant*, 16> Elts;
1814 Lex.Lex();
1815 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1816 ParseGlobalValueVector(Elts) ||
1817 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1818 return true;
1819
1820 if (Opc == Instruction::GetElementPtr) {
1821 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1822 return Error(ID.Loc, "getelementptr requires pointer operand");
1823
1824 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1825 (Value**)&Elts[1], Elts.size()-1))
1826 return Error(ID.Loc, "invalid indices for getelementptr");
1827 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1828 &Elts[1], Elts.size()-1);
1829 } else if (Opc == Instruction::Select) {
1830 if (Elts.size() != 3)
1831 return Error(ID.Loc, "expected three operands to select");
1832 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1833 Elts[2]))
1834 return Error(ID.Loc, Reason);
1835 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1836 } else if (Opc == Instruction::ShuffleVector) {
1837 if (Elts.size() != 3)
1838 return Error(ID.Loc, "expected three operands to shufflevector");
1839 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1840 return Error(ID.Loc, "invalid operands to shufflevector");
1841 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1842 } else if (Opc == Instruction::ExtractElement) {
1843 if (Elts.size() != 2)
1844 return Error(ID.Loc, "expected two operands to extractelement");
1845 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1846 return Error(ID.Loc, "invalid extractelement operands");
1847 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1848 } else {
1849 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1850 if (Elts.size() != 3)
1851 return Error(ID.Loc, "expected three operands to insertelement");
1852 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1853 return Error(ID.Loc, "invalid insertelement operands");
1854 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1855 }
1856
1857 ID.Kind = ValID::t_Constant;
1858 return false;
1859 }
1860 }
1861
1862 Lex.Lex();
1863 return false;
1864}
1865
1866/// ParseGlobalValue - Parse a global value with the specified type.
1867bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1868 V = 0;
1869 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001870 return ParseValID(ID) ||
1871 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00001872}
1873
1874/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1875/// constant.
1876bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1877 Constant *&V) {
1878 if (isa<FunctionType>(Ty))
1879 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1880
1881 switch (ID.Kind) {
1882 default: assert(0 && "Unknown ValID!");
1883 case ValID::t_LocalID:
1884 case ValID::t_LocalName:
1885 return Error(ID.Loc, "invalid use of function-local name");
1886 case ValID::t_InlineAsm:
1887 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1888 case ValID::t_GlobalName:
1889 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1890 return V == 0;
1891 case ValID::t_GlobalID:
1892 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1893 return V == 0;
1894 case ValID::t_APSInt:
1895 if (!isa<IntegerType>(Ty))
1896 return Error(ID.Loc, "integer constant must have integer type");
1897 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1898 V = ConstantInt::get(ID.APSIntVal);
1899 return false;
1900 case ValID::t_APFloat:
1901 if (!Ty->isFloatingPoint() ||
1902 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1903 return Error(ID.Loc, "floating point constant invalid for type");
1904
1905 // The lexer has no type info, so builds all float and double FP constants
1906 // as double. Fix this here. Long double does not need this.
1907 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1908 Ty == Type::FloatTy) {
1909 bool Ignored;
1910 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1911 &Ignored);
1912 }
1913 V = ConstantFP::get(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00001914
1915 if (V->getType() != Ty)
1916 return Error(ID.Loc, "floating point constant does not have type '" +
1917 Ty->getDescription() + "'");
1918
Chris Lattnerdf986172009-01-02 07:01:27 +00001919 return false;
1920 case ValID::t_Null:
1921 if (!isa<PointerType>(Ty))
1922 return Error(ID.Loc, "null must be a pointer type");
1923 V = ConstantPointerNull::get(cast<PointerType>(Ty));
1924 return false;
1925 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00001926 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00001927 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
1928 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00001929 return Error(ID.Loc, "invalid type for undef constant");
Chris Lattnerdf986172009-01-02 07:01:27 +00001930 V = UndefValue::get(Ty);
1931 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00001932 case ValID::t_EmptyArray:
1933 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
1934 return Error(ID.Loc, "invalid empty array initializer");
1935 V = UndefValue::get(Ty);
1936 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001937 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00001938 // FIXME: LabelTy should not be a first-class type.
1939 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00001940 return Error(ID.Loc, "invalid type for null constant");
1941 V = Constant::getNullValue(Ty);
1942 return false;
1943 case ValID::t_Constant:
1944 if (ID.ConstantVal->getType() != Ty)
1945 return Error(ID.Loc, "constant expression type mismatch");
1946 V = ID.ConstantVal;
1947 return false;
1948 }
1949}
1950
1951bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
1952 PATypeHolder Type(Type::VoidTy);
1953 return ParseType(Type) ||
1954 ParseGlobalValue(Type, V);
1955}
1956
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001957/// ParseGlobalValueVector
1958/// ::= /*empty*/
1959/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00001960bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
1961 // Empty list.
1962 if (Lex.getKind() == lltok::rbrace ||
1963 Lex.getKind() == lltok::rsquare ||
1964 Lex.getKind() == lltok::greater ||
1965 Lex.getKind() == lltok::rparen)
1966 return false;
1967
1968 Constant *C;
1969 if (ParseGlobalTypeAndValue(C)) return true;
1970 Elts.push_back(C);
1971
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001972 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001973 if (ParseGlobalTypeAndValue(C)) return true;
1974 Elts.push_back(C);
1975 }
1976
1977 return false;
1978}
1979
1980
1981//===----------------------------------------------------------------------===//
1982// Function Parsing.
1983//===----------------------------------------------------------------------===//
1984
1985bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
1986 PerFunctionState &PFS) {
1987 if (ID.Kind == ValID::t_LocalID)
1988 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
1989 else if (ID.Kind == ValID::t_LocalName)
1990 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
1991 else if (ID.Kind == ValID::ValID::t_InlineAsm) {
1992 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1993 const FunctionType *FTy =
1994 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1995 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
1996 return Error(ID.Loc, "invalid type for inline asm constraint string");
1997 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
1998 return false;
1999 } else {
2000 Constant *C;
2001 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2002 V = C;
2003 return false;
2004 }
2005
2006 return V == 0;
2007}
2008
2009bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2010 V = 0;
2011 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002012 return ParseValID(ID) ||
2013 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002014}
2015
2016bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2017 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002018 return ParseType(T) ||
2019 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002020}
2021
2022/// FunctionHeader
2023/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2024/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2025/// OptionalAlign OptGC
2026bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2027 // Parse the linkage.
2028 LocTy LinkageLoc = Lex.getLoc();
2029 unsigned Linkage;
2030
2031 unsigned Visibility, CC, RetAttrs;
2032 PATypeHolder RetType(Type::VoidTy);
2033 LocTy RetTypeLoc = Lex.getLoc();
2034 if (ParseOptionalLinkage(Linkage) ||
2035 ParseOptionalVisibility(Visibility) ||
2036 ParseOptionalCallingConv(CC) ||
2037 ParseOptionalAttrs(RetAttrs, 1) ||
2038 ParseType(RetType, RetTypeLoc))
2039 return true;
2040
2041 // Verify that the linkage is ok.
2042 switch ((GlobalValue::LinkageTypes)Linkage) {
2043 case GlobalValue::ExternalLinkage:
2044 break; // always ok.
2045 case GlobalValue::DLLImportLinkage:
2046 case GlobalValue::ExternalWeakLinkage:
2047 if (isDefine)
2048 return Error(LinkageLoc, "invalid linkage for function definition");
2049 break;
2050 case GlobalValue::InternalLinkage:
2051 case GlobalValue::LinkOnceLinkage:
2052 case GlobalValue::WeakLinkage:
2053 case GlobalValue::DLLExportLinkage:
2054 if (!isDefine)
2055 return Error(LinkageLoc, "invalid linkage for function declaration");
2056 break;
2057 case GlobalValue::AppendingLinkage:
2058 case GlobalValue::GhostLinkage:
2059 case GlobalValue::CommonLinkage:
2060 return Error(LinkageLoc, "invalid function linkage type");
2061 }
2062
Chris Lattner99bb3152009-01-05 08:00:30 +00002063 if (!FunctionType::isValidReturnType(RetType) ||
2064 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002065 return Error(RetTypeLoc, "invalid function return type");
2066
2067 if (Lex.getKind() != lltok::GlobalVar)
2068 return TokError("expected function name");
2069
2070 LocTy NameLoc = Lex.getLoc();
2071 std::string FunctionName = Lex.getStrVal();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002072 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002073
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002074 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002075 return TokError("expected '(' in function argument list");
2076
2077 std::vector<ArgInfo> ArgList;
2078 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002079 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002080 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002081 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002082 std::string GC;
2083
2084 if (ParseArgumentList(ArgList, isVarArg) ||
2085 ParseOptionalAttrs(FuncAttrs, 2) ||
2086 (EatIfPresent(lltok::kw_section) &&
2087 ParseStringConstant(Section)) ||
2088 ParseOptionalAlignment(Alignment) ||
2089 (EatIfPresent(lltok::kw_gc) &&
2090 ParseStringConstant(GC)))
2091 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002092
2093 // If the alignment was parsed as an attribute, move to the alignment field.
2094 if (FuncAttrs & Attribute::Alignment) {
2095 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2096 FuncAttrs &= ~Attribute::Alignment;
2097 }
2098
Chris Lattnerdf986172009-01-02 07:01:27 +00002099 // Okay, if we got here, the function is syntactically valid. Convert types
2100 // and do semantic checks.
2101 std::vector<const Type*> ParamTypeList;
2102 SmallVector<AttributeWithIndex, 8> Attrs;
2103 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2104 // attributes.
2105 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2106 if (FuncAttrs & ObsoleteFuncAttrs) {
2107 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2108 FuncAttrs &= ~ObsoleteFuncAttrs;
2109 }
2110
2111 if (RetAttrs != Attribute::None)
2112 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2113
2114 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2115 ParamTypeList.push_back(ArgList[i].Type);
2116 if (ArgList[i].Attrs != Attribute::None)
2117 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2118 }
2119
2120 if (FuncAttrs != Attribute::None)
2121 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2122
2123 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2124
2125 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2126 const PointerType *PFT = PointerType::getUnqual(FT);
2127
2128 Fn = 0;
2129 if (!FunctionName.empty()) {
2130 // If this was a definition of a forward reference, remove the definition
2131 // from the forward reference table and fill in the forward ref.
2132 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2133 ForwardRefVals.find(FunctionName);
2134 if (FRVI != ForwardRefVals.end()) {
2135 Fn = M->getFunction(FunctionName);
2136 ForwardRefVals.erase(FRVI);
2137 } else if ((Fn = M->getFunction(FunctionName))) {
2138 // If this function already exists in the symbol table, then it is
2139 // multiply defined. We accept a few cases for old backwards compat.
2140 // FIXME: Remove this stuff for LLVM 3.0.
2141 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2142 (!Fn->isDeclaration() && isDefine)) {
2143 // If the redefinition has different type or different attributes,
2144 // reject it. If both have bodies, reject it.
2145 return Error(NameLoc, "invalid redefinition of function '" +
2146 FunctionName + "'");
2147 } else if (Fn->isDeclaration()) {
2148 // Make sure to strip off any argument names so we can't get conflicts.
2149 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2150 AI != AE; ++AI)
2151 AI->setName("");
2152 }
2153 }
2154
2155 } else if (FunctionName.empty()) {
2156 // If this is a definition of a forward referenced function, make sure the
2157 // types agree.
2158 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2159 = ForwardRefValIDs.find(NumberedVals.size());
2160 if (I != ForwardRefValIDs.end()) {
2161 Fn = cast<Function>(I->second.first);
2162 if (Fn->getType() != PFT)
2163 return Error(NameLoc, "type of definition and forward reference of '@" +
2164 utostr(NumberedVals.size()) +"' disagree");
2165 ForwardRefValIDs.erase(I);
2166 }
2167 }
2168
2169 if (Fn == 0)
2170 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2171 else // Move the forward-reference to the correct spot in the module.
2172 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2173
2174 if (FunctionName.empty())
2175 NumberedVals.push_back(Fn);
2176
2177 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2178 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2179 Fn->setCallingConv(CC);
2180 Fn->setAttributes(PAL);
2181 Fn->setAlignment(Alignment);
2182 Fn->setSection(Section);
2183 if (!GC.empty()) Fn->setGC(GC.c_str());
2184
2185 // Add all of the arguments we parsed to the function.
2186 Function::arg_iterator ArgIt = Fn->arg_begin();
2187 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2188 // If the argument has a name, insert it into the argument symbol table.
2189 if (ArgList[i].Name.empty()) continue;
2190
2191 // Set the name, if it conflicted, it will be auto-renamed.
2192 ArgIt->setName(ArgList[i].Name);
2193
2194 if (ArgIt->getNameStr() != ArgList[i].Name)
2195 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2196 ArgList[i].Name + "'");
2197 }
2198
2199 return false;
2200}
2201
2202
2203/// ParseFunctionBody
2204/// ::= '{' BasicBlock+ '}'
2205/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2206///
2207bool LLParser::ParseFunctionBody(Function &Fn) {
2208 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2209 return TokError("expected '{' in function body");
2210 Lex.Lex(); // eat the {.
2211
2212 PerFunctionState PFS(*this, Fn);
2213
2214 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2215 if (ParseBasicBlock(PFS)) return true;
2216
2217 // Eat the }.
2218 Lex.Lex();
2219
2220 // Verify function is ok.
2221 return PFS.VerifyFunctionComplete();
2222}
2223
2224/// ParseBasicBlock
2225/// ::= LabelStr? Instruction*
2226bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2227 // If this basic block starts out with a name, remember it.
2228 std::string Name;
2229 LocTy NameLoc = Lex.getLoc();
2230 if (Lex.getKind() == lltok::LabelStr) {
2231 Name = Lex.getStrVal();
2232 Lex.Lex();
2233 }
2234
2235 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2236 if (BB == 0) return true;
2237
2238 std::string NameStr;
2239
2240 // Parse the instructions in this block until we get a terminator.
2241 Instruction *Inst;
2242 do {
2243 // This instruction may have three possibilities for a name: a) none
2244 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2245 LocTy NameLoc = Lex.getLoc();
2246 int NameID = -1;
2247 NameStr = "";
2248
2249 if (Lex.getKind() == lltok::LocalVarID) {
2250 NameID = Lex.getUIntVal();
2251 Lex.Lex();
2252 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2253 return true;
2254 } else if (Lex.getKind() == lltok::LocalVar ||
2255 // FIXME: REMOVE IN LLVM 3.0
2256 Lex.getKind() == lltok::StringConstant) {
2257 NameStr = Lex.getStrVal();
2258 Lex.Lex();
2259 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2260 return true;
2261 }
2262
2263 if (ParseInstruction(Inst, BB, PFS)) return true;
2264
2265 BB->getInstList().push_back(Inst);
2266
2267 // Set the name on the instruction.
2268 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2269 } while (!isa<TerminatorInst>(Inst));
2270
2271 return false;
2272}
2273
2274//===----------------------------------------------------------------------===//
2275// Instruction Parsing.
2276//===----------------------------------------------------------------------===//
2277
2278/// ParseInstruction - Parse one of the many different instructions.
2279///
2280bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2281 PerFunctionState &PFS) {
2282 lltok::Kind Token = Lex.getKind();
2283 if (Token == lltok::Eof)
2284 return TokError("found end of file when expecting more instructions");
2285 LocTy Loc = Lex.getLoc();
2286 Lex.Lex(); // Eat the keyword.
2287
2288 switch (Token) {
2289 default: return Error(Loc, "expected instruction opcode");
2290 // Terminator Instructions.
2291 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2292 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2293 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2294 case lltok::kw_br: return ParseBr(Inst, PFS);
2295 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2296 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2297 // Binary Operators.
2298 case lltok::kw_add:
2299 case lltok::kw_sub:
Chris Lattnere914b592009-01-05 08:24:46 +00002300 case lltok::kw_mul: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 0);
2301
Chris Lattnerdf986172009-01-02 07:01:27 +00002302 case lltok::kw_udiv:
2303 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002304 case lltok::kw_urem:
Chris Lattnere914b592009-01-05 08:24:46 +00002305 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 1);
2306 case lltok::kw_fdiv:
2307 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002308 case lltok::kw_shl:
2309 case lltok::kw_lshr:
2310 case lltok::kw_ashr:
2311 case lltok::kw_and:
2312 case lltok::kw_or:
2313 case lltok::kw_xor: return ParseLogical(Inst, PFS, Lex.getUIntVal());
2314 case lltok::kw_icmp:
2315 case lltok::kw_fcmp:
2316 case lltok::kw_vicmp:
2317 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, Lex.getUIntVal());
2318 // Casts.
2319 case lltok::kw_trunc:
2320 case lltok::kw_zext:
2321 case lltok::kw_sext:
2322 case lltok::kw_fptrunc:
2323 case lltok::kw_fpext:
2324 case lltok::kw_bitcast:
2325 case lltok::kw_uitofp:
2326 case lltok::kw_sitofp:
2327 case lltok::kw_fptoui:
2328 case lltok::kw_fptosi:
2329 case lltok::kw_inttoptr:
2330 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, Lex.getUIntVal());
2331 // Other.
2332 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002333 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002334 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2335 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2336 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2337 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2338 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2339 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2340 // Memory.
2341 case lltok::kw_alloca:
2342 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, Lex.getUIntVal());
2343 case lltok::kw_free: return ParseFree(Inst, PFS);
2344 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2345 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2346 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002347 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002348 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002349 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002350 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002351 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002352 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002353 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2354 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2355 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2356 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2357 }
2358}
2359
2360/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2361bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2362 // FIXME: REMOVE vicmp/vfcmp!
2363 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2364 switch (Lex.getKind()) {
2365 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2366 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2367 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2368 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2369 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2370 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2371 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2372 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2373 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2374 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2375 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2376 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2377 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2378 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2379 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2380 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2381 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2382 }
2383 } else {
2384 switch (Lex.getKind()) {
2385 default: TokError("expected icmp predicate (e.g. 'eq')");
2386 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2387 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2388 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2389 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2390 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2391 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2392 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2393 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2394 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2395 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2396 }
2397 }
2398 Lex.Lex();
2399 return false;
2400}
2401
2402//===----------------------------------------------------------------------===//
2403// Terminator Instructions.
2404//===----------------------------------------------------------------------===//
2405
2406/// ParseRet - Parse a return instruction.
2407/// ::= 'ret' void
2408/// ::= 'ret' TypeAndValue
2409/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2410bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2411 PerFunctionState &PFS) {
2412 PATypeHolder Ty(Type::VoidTy);
2413 if (ParseType(Ty)) return true;
2414
2415 if (Ty == Type::VoidTy) {
2416 Inst = ReturnInst::Create();
2417 return false;
2418 }
2419
2420 Value *RV;
2421 if (ParseValue(Ty, RV, PFS)) return true;
2422
2423 // The normal case is one return value.
2424 if (Lex.getKind() == lltok::comma) {
2425 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2426 // of 'ret {i32,i32} {i32 1, i32 2}'
2427 SmallVector<Value*, 8> RVs;
2428 RVs.push_back(RV);
2429
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002430 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002431 if (ParseTypeAndValue(RV, PFS)) return true;
2432 RVs.push_back(RV);
2433 }
2434
2435 RV = UndefValue::get(PFS.getFunction().getReturnType());
2436 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2437 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2438 BB->getInstList().push_back(I);
2439 RV = I;
2440 }
2441 }
2442 Inst = ReturnInst::Create(RV);
2443 return false;
2444}
2445
2446
2447/// ParseBr
2448/// ::= 'br' TypeAndValue
2449/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2450bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2451 LocTy Loc, Loc2;
2452 Value *Op0, *Op1, *Op2;
2453 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2454
2455 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2456 Inst = BranchInst::Create(BB);
2457 return false;
2458 }
2459
2460 if (Op0->getType() != Type::Int1Ty)
2461 return Error(Loc, "branch condition must have 'i1' type");
2462
2463 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2464 ParseTypeAndValue(Op1, Loc, PFS) ||
2465 ParseToken(lltok::comma, "expected ',' after true destination") ||
2466 ParseTypeAndValue(Op2, Loc2, PFS))
2467 return true;
2468
2469 if (!isa<BasicBlock>(Op1))
2470 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002471 if (!isa<BasicBlock>(Op2))
2472 return Error(Loc2, "true destination of branch must be a basic block");
2473
2474 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2475 return false;
2476}
2477
2478/// ParseSwitch
2479/// Instruction
2480/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2481/// JumpTable
2482/// ::= (TypeAndValue ',' TypeAndValue)*
2483bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2484 LocTy CondLoc, BBLoc;
2485 Value *Cond, *DefaultBB;
2486 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2487 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2488 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2489 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2490 return true;
2491
2492 if (!isa<IntegerType>(Cond->getType()))
2493 return Error(CondLoc, "switch condition must have integer type");
2494 if (!isa<BasicBlock>(DefaultBB))
2495 return Error(BBLoc, "default destination must be a basic block");
2496
2497 // Parse the jump table pairs.
2498 SmallPtrSet<Value*, 32> SeenCases;
2499 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2500 while (Lex.getKind() != lltok::rsquare) {
2501 Value *Constant, *DestBB;
2502
2503 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2504 ParseToken(lltok::comma, "expected ',' after case value") ||
2505 ParseTypeAndValue(DestBB, BBLoc, PFS))
2506 return true;
2507
2508 if (!SeenCases.insert(Constant))
2509 return Error(CondLoc, "duplicate case value in switch");
2510 if (!isa<ConstantInt>(Constant))
2511 return Error(CondLoc, "case value is not a constant integer");
2512 if (!isa<BasicBlock>(DestBB))
2513 return Error(BBLoc, "case destination is not a basic block");
2514
2515 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2516 cast<BasicBlock>(DestBB)));
2517 }
2518
2519 Lex.Lex(); // Eat the ']'.
2520
2521 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2522 Table.size());
2523 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2524 SI->addCase(Table[i].first, Table[i].second);
2525 Inst = SI;
2526 return false;
2527}
2528
2529/// ParseInvoke
2530/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2531/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2532bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2533 LocTy CallLoc = Lex.getLoc();
2534 unsigned CC, RetAttrs, FnAttrs;
2535 PATypeHolder RetType(Type::VoidTy);
2536 LocTy RetTypeLoc;
2537 ValID CalleeID;
2538 SmallVector<ParamInfo, 16> ArgList;
2539
2540 Value *NormalBB, *UnwindBB;
2541 if (ParseOptionalCallingConv(CC) ||
2542 ParseOptionalAttrs(RetAttrs, 1) ||
2543 ParseType(RetType, RetTypeLoc) ||
2544 ParseValID(CalleeID) ||
2545 ParseParameterList(ArgList, PFS) ||
2546 ParseOptionalAttrs(FnAttrs, 2) ||
2547 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2548 ParseTypeAndValue(NormalBB, PFS) ||
2549 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2550 ParseTypeAndValue(UnwindBB, PFS))
2551 return true;
2552
2553 if (!isa<BasicBlock>(NormalBB))
2554 return Error(CallLoc, "normal destination is not a basic block");
2555 if (!isa<BasicBlock>(UnwindBB))
2556 return Error(CallLoc, "unwind destination is not a basic block");
2557
2558 // If RetType is a non-function pointer type, then this is the short syntax
2559 // for the call, which means that RetType is just the return type. Infer the
2560 // rest of the function argument types from the arguments that are present.
2561 const PointerType *PFTy = 0;
2562 const FunctionType *Ty = 0;
2563 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2564 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2565 // Pull out the types of all of the arguments...
2566 std::vector<const Type*> ParamTypes;
2567 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2568 ParamTypes.push_back(ArgList[i].V->getType());
2569
2570 if (!FunctionType::isValidReturnType(RetType))
2571 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2572
2573 Ty = FunctionType::get(RetType, ParamTypes, false);
2574 PFTy = PointerType::getUnqual(Ty);
2575 }
2576
2577 // Look up the callee.
2578 Value *Callee;
2579 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2580
2581 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2582 // function attributes.
2583 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2584 if (FnAttrs & ObsoleteFuncAttrs) {
2585 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2586 FnAttrs &= ~ObsoleteFuncAttrs;
2587 }
2588
2589 // Set up the Attributes for the function.
2590 SmallVector<AttributeWithIndex, 8> Attrs;
2591 if (RetAttrs != Attribute::None)
2592 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2593
2594 SmallVector<Value*, 8> Args;
2595
2596 // Loop through FunctionType's arguments and ensure they are specified
2597 // correctly. Also, gather any parameter attributes.
2598 FunctionType::param_iterator I = Ty->param_begin();
2599 FunctionType::param_iterator E = Ty->param_end();
2600 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2601 const Type *ExpectedTy = 0;
2602 if (I != E) {
2603 ExpectedTy = *I++;
2604 } else if (!Ty->isVarArg()) {
2605 return Error(ArgList[i].Loc, "too many arguments specified");
2606 }
2607
2608 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2609 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2610 ExpectedTy->getDescription() + "'");
2611 Args.push_back(ArgList[i].V);
2612 if (ArgList[i].Attrs != Attribute::None)
2613 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2614 }
2615
2616 if (I != E)
2617 return Error(CallLoc, "not enough parameters specified for call");
2618
2619 if (FnAttrs != Attribute::None)
2620 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2621
2622 // Finish off the Attributes and check them
2623 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2624
2625 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2626 cast<BasicBlock>(UnwindBB),
2627 Args.begin(), Args.end());
2628 II->setCallingConv(CC);
2629 II->setAttributes(PAL);
2630 Inst = II;
2631 return false;
2632}
2633
2634
2635
2636//===----------------------------------------------------------------------===//
2637// Binary Operators.
2638//===----------------------------------------------------------------------===//
2639
2640/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002641/// ::= ArithmeticOps TypeAndValue ',' Value
2642///
2643/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2644/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002645bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002646 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002647 LocTy Loc; Value *LHS, *RHS;
2648 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2649 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2650 ParseValue(LHS->getType(), RHS, PFS))
2651 return true;
2652
Chris Lattnere914b592009-01-05 08:24:46 +00002653 bool Valid;
2654 switch (OperandType) {
2655 default: assert(0 && "Unknown operand type!");
2656 case 0: // int or FP.
2657 Valid = LHS->getType()->isIntOrIntVector() ||
2658 LHS->getType()->isFPOrFPVector();
2659 break;
2660 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2661 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2662 }
2663
2664 if (!Valid)
2665 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002666
2667 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2668 return false;
2669}
2670
2671/// ParseLogical
2672/// ::= ArithmeticOps TypeAndValue ',' Value {
2673bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2674 unsigned Opc) {
2675 LocTy Loc; Value *LHS, *RHS;
2676 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2677 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2678 ParseValue(LHS->getType(), RHS, PFS))
2679 return true;
2680
2681 if (!LHS->getType()->isIntOrIntVector())
2682 return Error(Loc,"instruction requires integer or integer vector operands");
2683
2684 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2685 return false;
2686}
2687
2688
2689/// ParseCompare
2690/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2691/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2692/// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2693/// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2694bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2695 unsigned Opc) {
2696 // Parse the integer/fp comparison predicate.
2697 LocTy Loc;
2698 unsigned Pred;
2699 Value *LHS, *RHS;
2700 if (ParseCmpPredicate(Pred, Opc) ||
2701 ParseTypeAndValue(LHS, Loc, PFS) ||
2702 ParseToken(lltok::comma, "expected ',' after compare value") ||
2703 ParseValue(LHS->getType(), RHS, PFS))
2704 return true;
2705
2706 if (Opc == Instruction::FCmp) {
2707 if (!LHS->getType()->isFPOrFPVector())
2708 return Error(Loc, "fcmp requires floating point operands");
2709 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2710 } else if (Opc == Instruction::ICmp) {
2711 if (!LHS->getType()->isIntOrIntVector() &&
2712 !isa<PointerType>(LHS->getType()))
2713 return Error(Loc, "icmp requires integer operands");
2714 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2715 } else if (Opc == Instruction::VFCmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002716 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2717 return Error(Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002718 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2719 } else if (Opc == Instruction::VICmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002720 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2721 return Error(Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002722 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2723 }
2724 return false;
2725}
2726
2727//===----------------------------------------------------------------------===//
2728// Other Instructions.
2729//===----------------------------------------------------------------------===//
2730
2731
2732/// ParseCast
2733/// ::= CastOpc TypeAndValue 'to' Type
2734bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2735 unsigned Opc) {
2736 LocTy Loc; Value *Op;
2737 PATypeHolder DestTy(Type::VoidTy);
2738 if (ParseTypeAndValue(Op, Loc, PFS) ||
2739 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2740 ParseType(DestTy))
2741 return true;
2742
2743 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy))
2744 return Error(Loc, "invalid cast opcode for cast from '" +
2745 Op->getType()->getDescription() + "' to '" +
2746 DestTy->getDescription() + "'");
2747 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2748 return false;
2749}
2750
2751/// ParseSelect
2752/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2753bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2754 LocTy Loc;
2755 Value *Op0, *Op1, *Op2;
2756 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2757 ParseToken(lltok::comma, "expected ',' after select condition") ||
2758 ParseTypeAndValue(Op1, PFS) ||
2759 ParseToken(lltok::comma, "expected ',' after select value") ||
2760 ParseTypeAndValue(Op2, PFS))
2761 return true;
2762
2763 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2764 return Error(Loc, Reason);
2765
2766 Inst = SelectInst::Create(Op0, Op1, Op2);
2767 return false;
2768}
2769
Chris Lattner0088a5c2009-01-05 08:18:44 +00002770/// ParseVA_Arg
2771/// ::= 'va_arg' TypeAndValue ',' Type
2772bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002773 Value *Op;
2774 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002775 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00002776 if (ParseTypeAndValue(Op, PFS) ||
2777 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00002778 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002779 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00002780
2781 if (!EltTy->isFirstClassType())
2782 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002783
2784 Inst = new VAArgInst(Op, EltTy);
2785 return false;
2786}
2787
2788/// ParseExtractElement
2789/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2790bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2791 LocTy Loc;
2792 Value *Op0, *Op1;
2793 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2794 ParseToken(lltok::comma, "expected ',' after extract value") ||
2795 ParseTypeAndValue(Op1, PFS))
2796 return true;
2797
2798 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2799 return Error(Loc, "invalid extractelement operands");
2800
2801 Inst = new ExtractElementInst(Op0, Op1);
2802 return false;
2803}
2804
2805/// ParseInsertElement
2806/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2807bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2808 LocTy Loc;
2809 Value *Op0, *Op1, *Op2;
2810 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2811 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2812 ParseTypeAndValue(Op1, PFS) ||
2813 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2814 ParseTypeAndValue(Op2, PFS))
2815 return true;
2816
2817 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2818 return Error(Loc, "invalid extractelement operands");
2819
2820 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2821 return false;
2822}
2823
2824/// ParseShuffleVector
2825/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2826bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2827 LocTy Loc;
2828 Value *Op0, *Op1, *Op2;
2829 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2830 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2831 ParseTypeAndValue(Op1, PFS) ||
2832 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2833 ParseTypeAndValue(Op2, PFS))
2834 return true;
2835
2836 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2837 return Error(Loc, "invalid extractelement operands");
2838
2839 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2840 return false;
2841}
2842
2843/// ParsePHI
2844/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2845bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2846 PATypeHolder Ty(Type::VoidTy);
2847 Value *Op0, *Op1;
2848 LocTy TypeLoc = Lex.getLoc();
2849
2850 if (ParseType(Ty) ||
2851 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2852 ParseValue(Ty, Op0, PFS) ||
2853 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2854 ParseValue(Type::LabelTy, Op1, PFS) ||
2855 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2856 return true;
2857
2858 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2859 while (1) {
2860 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2861
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002862 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00002863 break;
2864
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002865 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002866 ParseValue(Ty, Op0, PFS) ||
2867 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2868 ParseValue(Type::LabelTy, Op1, PFS) ||
2869 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2870 return true;
2871 }
2872
2873 if (!Ty->isFirstClassType())
2874 return Error(TypeLoc, "phi node must have first class type");
2875
2876 PHINode *PN = PHINode::Create(Ty);
2877 PN->reserveOperandSpace(PHIVals.size());
2878 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2879 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2880 Inst = PN;
2881 return false;
2882}
2883
2884/// ParseCall
2885/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2886/// ParameterList OptionalAttrs
2887bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
2888 bool isTail) {
2889 unsigned CC, RetAttrs, FnAttrs;
2890 PATypeHolder RetType(Type::VoidTy);
2891 LocTy RetTypeLoc;
2892 ValID CalleeID;
2893 SmallVector<ParamInfo, 16> ArgList;
2894 LocTy CallLoc = Lex.getLoc();
2895
2896 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
2897 ParseOptionalCallingConv(CC) ||
2898 ParseOptionalAttrs(RetAttrs, 1) ||
2899 ParseType(RetType, RetTypeLoc) ||
2900 ParseValID(CalleeID) ||
2901 ParseParameterList(ArgList, PFS) ||
2902 ParseOptionalAttrs(FnAttrs, 2))
2903 return true;
2904
2905 // If RetType is a non-function pointer type, then this is the short syntax
2906 // for the call, which means that RetType is just the return type. Infer the
2907 // rest of the function argument types from the arguments that are present.
2908 const PointerType *PFTy = 0;
2909 const FunctionType *Ty = 0;
2910 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2911 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2912 // Pull out the types of all of the arguments...
2913 std::vector<const Type*> ParamTypes;
2914 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2915 ParamTypes.push_back(ArgList[i].V->getType());
2916
2917 if (!FunctionType::isValidReturnType(RetType))
2918 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2919
2920 Ty = FunctionType::get(RetType, ParamTypes, false);
2921 PFTy = PointerType::getUnqual(Ty);
2922 }
2923
2924 // Look up the callee.
2925 Value *Callee;
2926 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2927
2928 // Check for call to invalid intrinsic to avoid crashing later.
2929 if (Function *F = dyn_cast<Function>(Callee)) {
2930 if (F->hasName() && F->getNameLen() >= 5 &&
2931 !strncmp(F->getValueName()->getKeyData(), "llvm.", 5) &&
2932 !F->getIntrinsicID(true))
2933 return Error(CallLoc, "Call to invalid LLVM intrinsic function '" +
2934 F->getNameStr() + "'");
2935 }
2936
2937 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2938 // function attributes.
2939 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2940 if (FnAttrs & ObsoleteFuncAttrs) {
2941 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2942 FnAttrs &= ~ObsoleteFuncAttrs;
2943 }
2944
2945 // Set up the Attributes for the function.
2946 SmallVector<AttributeWithIndex, 8> Attrs;
2947 if (RetAttrs != Attribute::None)
2948 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2949
2950 SmallVector<Value*, 8> Args;
2951
2952 // Loop through FunctionType's arguments and ensure they are specified
2953 // correctly. Also, gather any parameter attributes.
2954 FunctionType::param_iterator I = Ty->param_begin();
2955 FunctionType::param_iterator E = Ty->param_end();
2956 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2957 const Type *ExpectedTy = 0;
2958 if (I != E) {
2959 ExpectedTy = *I++;
2960 } else if (!Ty->isVarArg()) {
2961 return Error(ArgList[i].Loc, "too many arguments specified");
2962 }
2963
2964 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2965 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2966 ExpectedTy->getDescription() + "'");
2967 Args.push_back(ArgList[i].V);
2968 if (ArgList[i].Attrs != Attribute::None)
2969 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2970 }
2971
2972 if (I != E)
2973 return Error(CallLoc, "not enough parameters specified for call");
2974
2975 if (FnAttrs != Attribute::None)
2976 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2977
2978 // Finish off the Attributes and check them
2979 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2980
2981 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
2982 CI->setTailCall(isTail);
2983 CI->setCallingConv(CC);
2984 CI->setAttributes(PAL);
2985 Inst = CI;
2986 return false;
2987}
2988
2989//===----------------------------------------------------------------------===//
2990// Memory Instructions.
2991//===----------------------------------------------------------------------===//
2992
2993/// ParseAlloc
2994/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
2995/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
2996bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
2997 unsigned Opc) {
2998 PATypeHolder Ty(Type::VoidTy);
2999 Value *Size = 0;
3000 LocTy SizeLoc = 0;
3001 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003002 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003003
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003004 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003005 if (Lex.getKind() == lltok::kw_align) {
3006 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003007 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3008 ParseOptionalCommaAlignment(Alignment)) {
3009 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003010 }
3011 }
3012
3013 if (Size && Size->getType() != Type::Int32Ty)
3014 return Error(SizeLoc, "element count must be i32");
3015
3016 if (Opc == Instruction::Malloc)
3017 Inst = new MallocInst(Ty, Size, Alignment);
3018 else
3019 Inst = new AllocaInst(Ty, Size, Alignment);
3020 return false;
3021}
3022
3023/// ParseFree
3024/// ::= 'free' TypeAndValue
3025bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3026 Value *Val; LocTy Loc;
3027 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3028 if (!isa<PointerType>(Val->getType()))
3029 return Error(Loc, "operand to free must be a pointer");
3030 Inst = new FreeInst(Val);
3031 return false;
3032}
3033
3034/// ParseLoad
3035/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3036bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3037 bool isVolatile) {
3038 Value *Val; LocTy Loc;
3039 unsigned Alignment;
3040 if (ParseTypeAndValue(Val, Loc, PFS) ||
3041 ParseOptionalCommaAlignment(Alignment))
3042 return true;
3043
3044 if (!isa<PointerType>(Val->getType()) ||
3045 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3046 return Error(Loc, "load operand must be a pointer to a first class type");
3047
3048 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3049 return false;
3050}
3051
3052/// ParseStore
3053/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3054bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3055 bool isVolatile) {
3056 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3057 unsigned Alignment;
3058 if (ParseTypeAndValue(Val, Loc, PFS) ||
3059 ParseToken(lltok::comma, "expected ',' after store operand") ||
3060 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3061 ParseOptionalCommaAlignment(Alignment))
3062 return true;
3063
3064 if (!isa<PointerType>(Ptr->getType()))
3065 return Error(PtrLoc, "store operand must be a pointer");
3066 if (!Val->getType()->isFirstClassType())
3067 return Error(Loc, "store operand must be a first class value");
3068 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3069 return Error(Loc, "stored value and pointer type do not match");
3070
3071 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3072 return false;
3073}
3074
3075/// ParseGetResult
3076/// ::= 'getresult' TypeAndValue ',' uint
3077/// FIXME: Remove support for getresult in LLVM 3.0
3078bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3079 Value *Val; LocTy ValLoc, EltLoc;
3080 unsigned Element;
3081 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3082 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003083 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003084 return true;
3085
3086 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3087 return Error(ValLoc, "getresult inst requires an aggregate operand");
3088 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3089 return Error(EltLoc, "invalid getresult index for value");
3090 Inst = ExtractValueInst::Create(Val, Element);
3091 return false;
3092}
3093
3094/// ParseGetElementPtr
3095/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3096bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3097 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003098 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003099
3100 if (!isa<PointerType>(Ptr->getType()))
3101 return Error(Loc, "base of getelementptr must be a pointer");
3102
3103 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003104 while (EatIfPresent(lltok::comma)) {
3105 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003106 if (!isa<IntegerType>(Val->getType()))
3107 return Error(EltLoc, "getelementptr index must be an integer");
3108 Indices.push_back(Val);
3109 }
3110
3111 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3112 Indices.begin(), Indices.end()))
3113 return Error(Loc, "invalid getelementptr indices");
3114 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3115 return false;
3116}
3117
3118/// ParseExtractValue
3119/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3120bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3121 Value *Val; LocTy Loc;
3122 SmallVector<unsigned, 4> Indices;
3123 if (ParseTypeAndValue(Val, Loc, PFS) ||
3124 ParseIndexList(Indices))
3125 return true;
3126
3127 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3128 return Error(Loc, "extractvalue operand must be array or struct");
3129
3130 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3131 Indices.end()))
3132 return Error(Loc, "invalid indices for extractvalue");
3133 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3134 return false;
3135}
3136
3137/// ParseInsertValue
3138/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3139bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3140 Value *Val0, *Val1; LocTy Loc0, Loc1;
3141 SmallVector<unsigned, 4> Indices;
3142 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3143 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3144 ParseTypeAndValue(Val1, Loc1, PFS) ||
3145 ParseIndexList(Indices))
3146 return true;
3147
3148 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3149 return Error(Loc0, "extractvalue operand must be array or struct");
3150
3151 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3152 Indices.end()))
3153 return Error(Loc0, "invalid indices for insertvalue");
3154 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3155 return false;
3156}