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