blob: 097b385c3eaf2e3b697de2e720bdb13ea2ee5ee6 [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"
Owen Andersonfba933c2009-07-01 23:57:11 +000021#include "llvm/LLVMContext.h"
Nick Lewyckycb337992009-05-10 20:57:05 +000022#include "llvm/MDNode.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000023#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000024#include "llvm/Operator.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000025#include "llvm/ValueSymbolTable.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/StringExtras.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000029#include "llvm/Support/raw_ostream.h"
30using namespace llvm;
31
Chris Lattnerdf986172009-01-02 07:01:27 +000032namespace llvm {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000033 /// ValID - Represents a reference of a definition of some sort with no type.
34 /// There are several cases where we have to parse the value but where the
35 /// type can depend on later context. This may either be a numeric reference
36 /// or a symbolic (%var) reference. This is just a discriminated union.
Chris Lattnerdf986172009-01-02 07:01:27 +000037 struct ValID {
38 enum {
39 t_LocalID, t_GlobalID, // ID in UIntVal.
40 t_LocalName, t_GlobalName, // Name in StrVal.
41 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
42 t_Null, t_Undef, t_Zero, // No value.
Chris Lattner081b5052009-01-05 07:52:51 +000043 t_EmptyArray, // No value: []
Chris Lattnerdf986172009-01-02 07:01:27 +000044 t_Constant, // Value in ConstantVal.
Devang Patele54abc92009-07-22 17:43:22 +000045 t_InlineAsm, // Value in StrVal/StrVal2/UIntVal.
46 t_Metadata // Value in MetadataVal.
Chris Lattnerdf986172009-01-02 07:01:27 +000047 } Kind;
48
49 LLParser::LocTy Loc;
50 unsigned UIntVal;
51 std::string StrVal, StrVal2;
52 APSInt APSIntVal;
53 APFloat APFloatVal;
54 Constant *ConstantVal;
Devang Patele54abc92009-07-22 17:43:22 +000055 MetadataBase *MetadataVal;
Chris Lattnerdf986172009-01-02 07:01:27 +000056 ValID() : APFloatVal(0.0) {}
57 };
58}
59
Chris Lattner3ed88ef2009-01-02 08:05:26 +000060/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000061bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000062 // Prime the lexer.
63 Lex.Lex();
64
Chris Lattnerad7d1e22009-01-04 20:44:11 +000065 return ParseTopLevelEntities() ||
66 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000067}
68
69/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
70/// module.
71bool LLParser::ValidateEndOfModule() {
72 if (!ForwardRefTypes.empty())
73 return Error(ForwardRefTypes.begin()->second.second,
74 "use of undefined type named '" +
75 ForwardRefTypes.begin()->first + "'");
76 if (!ForwardRefTypeIDs.empty())
77 return Error(ForwardRefTypeIDs.begin()->second.second,
78 "use of undefined type '%" +
79 utostr(ForwardRefTypeIDs.begin()->first) + "'");
80
81 if (!ForwardRefVals.empty())
82 return Error(ForwardRefVals.begin()->second.second,
83 "use of undefined value '@" + ForwardRefVals.begin()->first +
84 "'");
85
86 if (!ForwardRefValIDs.empty())
87 return Error(ForwardRefValIDs.begin()->second.second,
88 "use of undefined value '@" +
89 utostr(ForwardRefValIDs.begin()->first) + "'");
90
Devang Patel1c7eea62009-07-08 19:23:54 +000091 if (!ForwardRefMDNodes.empty())
92 return Error(ForwardRefMDNodes.begin()->second.second,
93 "use of undefined metadata '!" +
94 utostr(ForwardRefMDNodes.begin()->first) + "'");
95
96
Chris Lattnerdf986172009-01-02 07:01:27 +000097 // Look for intrinsic functions and CallInst that need to be upgraded
98 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
99 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
100
101 return false;
102}
103
104//===----------------------------------------------------------------------===//
105// Top-Level Entities
106//===----------------------------------------------------------------------===//
107
108bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000109 while (1) {
110 switch (Lex.getKind()) {
111 default: return TokError("expected top-level entity");
112 case lltok::Eof: return false;
113 //case lltok::kw_define:
114 case lltok::kw_declare: if (ParseDeclare()) return true; break;
115 case lltok::kw_define: if (ParseDefine()) return true; break;
116 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
117 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
118 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
119 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
120 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
121 case lltok::LocalVar: if (ParseNamedType()) return true; break;
122 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Devang Patel923078c2009-07-01 19:21:12 +0000123 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000124
125 // The Global variable production with no name can have many different
126 // optional leading prefixes, the production is:
127 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
128 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000129 case lltok::kw_private : // OptionalLinkage
130 case lltok::kw_linker_private: // OptionalLinkage
131 case lltok::kw_internal: // OptionalLinkage
132 case lltok::kw_weak: // OptionalLinkage
133 case lltok::kw_weak_odr: // OptionalLinkage
134 case lltok::kw_linkonce: // OptionalLinkage
135 case lltok::kw_linkonce_odr: // OptionalLinkage
136 case lltok::kw_appending: // OptionalLinkage
137 case lltok::kw_dllexport: // OptionalLinkage
138 case lltok::kw_common: // OptionalLinkage
139 case lltok::kw_dllimport: // OptionalLinkage
140 case lltok::kw_extern_weak: // OptionalLinkage
141 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000142 unsigned Linkage, Visibility;
143 if (ParseOptionalLinkage(Linkage) ||
144 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000145 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000146 return true;
147 break;
148 }
149 case lltok::kw_default: // OptionalVisibility
150 case lltok::kw_hidden: // OptionalVisibility
151 case lltok::kw_protected: { // OptionalVisibility
152 unsigned Visibility;
153 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000154 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000155 return true;
156 break;
157 }
158
159 case lltok::kw_thread_local: // OptionalThreadLocal
160 case lltok::kw_addrspace: // OptionalAddrSpace
161 case lltok::kw_constant: // GlobalType
162 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000163 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000164 break;
165 }
166 }
167}
168
169
170/// toplevelentity
171/// ::= 'module' 'asm' STRINGCONSTANT
172bool LLParser::ParseModuleAsm() {
173 assert(Lex.getKind() == lltok::kw_module);
174 Lex.Lex();
175
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000176 std::string AsmStr;
177 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
178 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000179
180 const std::string &AsmSoFar = M->getModuleInlineAsm();
181 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000182 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000183 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000184 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000185 return false;
186}
187
188/// toplevelentity
189/// ::= 'target' 'triple' '=' STRINGCONSTANT
190/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
191bool LLParser::ParseTargetDefinition() {
192 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000193 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000194 switch (Lex.Lex()) {
195 default: return TokError("unknown target property");
196 case lltok::kw_triple:
197 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000198 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
199 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000200 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000201 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000202 return false;
203 case lltok::kw_datalayout:
204 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000205 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
206 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000207 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000208 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000209 return false;
210 }
211}
212
213/// toplevelentity
214/// ::= 'deplibs' '=' '[' ']'
215/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
216bool LLParser::ParseDepLibs() {
217 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000218 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000219 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
220 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
221 return true;
222
223 if (EatIfPresent(lltok::rsquare))
224 return false;
225
226 std::string Str;
227 if (ParseStringConstant(Str)) return true;
228 M->addLibrary(Str);
229
230 while (EatIfPresent(lltok::comma)) {
231 if (ParseStringConstant(Str)) return true;
232 M->addLibrary(Str);
233 }
234
235 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000236}
237
238/// toplevelentity
239/// ::= 'type' type
240bool LLParser::ParseUnnamedType() {
241 assert(Lex.getKind() == lltok::kw_type);
242 LocTy TypeLoc = Lex.getLoc();
243 Lex.Lex(); // eat kw_type
244
245 PATypeHolder Ty(Type::VoidTy);
246 if (ParseType(Ty)) return true;
247
248 unsigned TypeID = NumberedTypes.size();
249
Chris Lattnerdf986172009-01-02 07:01:27 +0000250 // See if this type was previously referenced.
251 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
252 FI = ForwardRefTypeIDs.find(TypeID);
253 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000254 if (FI->second.first.get() == Ty)
255 return Error(TypeLoc, "self referential type is invalid");
256
Chris Lattnerdf986172009-01-02 07:01:27 +0000257 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
258 Ty = FI->second.first.get();
259 ForwardRefTypeIDs.erase(FI);
260 }
261
262 NumberedTypes.push_back(Ty);
263
264 return false;
265}
266
267/// toplevelentity
268/// ::= LocalVar '=' 'type' type
269bool LLParser::ParseNamedType() {
270 std::string Name = Lex.getStrVal();
271 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000272 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000273
274 PATypeHolder Ty(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000275
276 if (ParseToken(lltok::equal, "expected '=' after name") ||
277 ParseToken(lltok::kw_type, "expected 'type' after name") ||
278 ParseType(Ty))
279 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000280
Chris Lattnerdf986172009-01-02 07:01:27 +0000281 // Set the type name, checking for conflicts as we do so.
282 bool AlreadyExists = M->addTypeName(Name, Ty);
283 if (!AlreadyExists) return false;
284
285 // See if this type is a forward reference. We need to eagerly resolve
286 // types to allow recursive type redefinitions below.
287 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
288 FI = ForwardRefTypes.find(Name);
289 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000290 if (FI->second.first.get() == Ty)
291 return Error(NameLoc, "self referential type is invalid");
292
Chris Lattnerdf986172009-01-02 07:01:27 +0000293 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
294 Ty = FI->second.first.get();
295 ForwardRefTypes.erase(FI);
296 }
297
298 // Inserting a name that is already defined, get the existing name.
299 const Type *Existing = M->getTypeByName(Name);
300 assert(Existing && "Conflict but no matching type?!");
301
302 // Otherwise, this is an attempt to redefine a type. That's okay if
303 // the redefinition is identical to the original.
304 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
305 if (Existing == Ty) return false;
306
307 // Any other kind of (non-equivalent) redefinition is an error.
308 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
309 Ty->getDescription() + "'");
310}
311
312
313/// toplevelentity
314/// ::= 'declare' FunctionHeader
315bool LLParser::ParseDeclare() {
316 assert(Lex.getKind() == lltok::kw_declare);
317 Lex.Lex();
318
319 Function *F;
320 return ParseFunctionHeader(F, false);
321}
322
323/// toplevelentity
324/// ::= 'define' FunctionHeader '{' ...
325bool LLParser::ParseDefine() {
326 assert(Lex.getKind() == lltok::kw_define);
327 Lex.Lex();
328
329 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000330 return ParseFunctionHeader(F, true) ||
331 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000332}
333
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000334/// ParseGlobalType
335/// ::= 'constant'
336/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000337bool LLParser::ParseGlobalType(bool &IsConstant) {
338 if (Lex.getKind() == lltok::kw_constant)
339 IsConstant = true;
340 else if (Lex.getKind() == lltok::kw_global)
341 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000342 else {
343 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000344 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000345 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000346 Lex.Lex();
347 return false;
348}
349
350/// ParseNamedGlobal:
351/// GlobalVar '=' OptionalVisibility ALIAS ...
352/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
353bool LLParser::ParseNamedGlobal() {
354 assert(Lex.getKind() == lltok::GlobalVar);
355 LocTy NameLoc = Lex.getLoc();
356 std::string Name = Lex.getStrVal();
357 Lex.Lex();
358
359 bool HasLinkage;
360 unsigned Linkage, Visibility;
361 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
362 ParseOptionalLinkage(Linkage, HasLinkage) ||
363 ParseOptionalVisibility(Visibility))
364 return true;
365
366 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
367 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
368 return ParseAlias(Name, NameLoc, Visibility);
369}
370
Devang Patel256be962009-07-20 19:00:08 +0000371// MDString:
372// ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +0000373bool LLParser::ParseMDString(MetadataBase *&MDS) {
Devang Patel256be962009-07-20 19:00:08 +0000374 std::string Str;
375 if (ParseStringConstant(Str)) return true;
376 MDS = Context.getMDString(Str.data(), Str.data() + Str.size());
377 return false;
378}
379
380// MDNode:
381// ::= '!' MDNodeNumber
Devang Patel104cf9e2009-07-23 01:07:34 +0000382bool LLParser::ParseMDNode(MetadataBase *&Node) {
Devang Patel256be962009-07-20 19:00:08 +0000383 // !{ ..., !42, ... }
384 unsigned MID = 0;
385 if (ParseUInt32(MID)) return true;
386
387 // Check existing MDNode.
Devang Patel104cf9e2009-07-23 01:07:34 +0000388 std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
Devang Patel256be962009-07-20 19:00:08 +0000389 if (I != MetadataCache.end()) {
390 Node = I->second;
391 return false;
392 }
393
394 // Check known forward references.
Devang Patel104cf9e2009-07-23 01:07:34 +0000395 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel256be962009-07-20 19:00:08 +0000396 FI = ForwardRefMDNodes.find(MID);
397 if (FI != ForwardRefMDNodes.end()) {
398 Node = FI->second.first;
399 return false;
400 }
401
402 // Create MDNode forward reference
403 SmallVector<Value *, 1> Elts;
404 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
405 Elts.push_back(Context.getMDString(FwdRefName));
406 MDNode *FwdNode = Context.getMDNode(Elts.data(), Elts.size());
407 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
408 Node = FwdNode;
409 return false;
410}
411
Devang Patel923078c2009-07-01 19:21:12 +0000412/// ParseStandaloneMetadata:
413/// !42 = !{...}
414bool LLParser::ParseStandaloneMetadata() {
415 assert(Lex.getKind() == lltok::Metadata);
416 Lex.Lex();
417 unsigned MetadataID = 0;
418 if (ParseUInt32(MetadataID))
419 return true;
420 if (MetadataCache.find(MetadataID) != MetadataCache.end())
421 return TokError("Metadata id is already used");
422 if (ParseToken(lltok::equal, "expected '=' here"))
423 return true;
424
425 LocTy TyLoc;
Devang Patel923078c2009-07-01 19:21:12 +0000426 PATypeHolder Ty(Type::VoidTy);
Devang Patel2214c942009-07-08 21:57:07 +0000427 if (ParseType(Ty, TyLoc))
Devang Patel923078c2009-07-01 19:21:12 +0000428 return true;
429
Devang Patel104cf9e2009-07-23 01:07:34 +0000430 if (Lex.getKind() != lltok::Metadata)
431 return TokError("Expected metadata here");
Devang Patel923078c2009-07-01 19:21:12 +0000432
Devang Patel104cf9e2009-07-23 01:07:34 +0000433 Lex.Lex();
434 if (Lex.getKind() != lltok::lbrace)
435 return TokError("Expected '{' here");
436
437 SmallVector<Value *, 16> Elts;
438 if (ParseMDNodeVector(Elts)
439 || ParseToken(lltok::rbrace, "exected end of metadata node"))
440 return true;
441
442 MDNode *Init = Context.getMDNode(Elts.data(), Elts.size());
Devang Patel923078c2009-07-01 19:21:12 +0000443 MetadataCache[MetadataID] = Init;
Devang Patel104cf9e2009-07-23 01:07:34 +0000444 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000445 FI = ForwardRefMDNodes.find(MetadataID);
446 if (FI != ForwardRefMDNodes.end()) {
Devang Patel104cf9e2009-07-23 01:07:34 +0000447 MDNode *FwdNode = cast<MDNode>(FI->second.first);
Devang Patel1c7eea62009-07-08 19:23:54 +0000448 FwdNode->replaceAllUsesWith(Init);
449 ForwardRefMDNodes.erase(FI);
450 }
451
Devang Patel923078c2009-07-01 19:21:12 +0000452 return false;
453}
454
Chris Lattnerdf986172009-01-02 07:01:27 +0000455/// ParseAlias:
456/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
457/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000458/// ::= TypeAndValue
459/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
460/// ::= 'getelementptr' '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000461///
462/// Everything through visibility has already been parsed.
463///
464bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
465 unsigned Visibility) {
466 assert(Lex.getKind() == lltok::kw_alias);
467 Lex.Lex();
468 unsigned Linkage;
469 LocTy LinkageLoc = Lex.getLoc();
470 if (ParseOptionalLinkage(Linkage))
471 return true;
472
473 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000474 Linkage != GlobalValue::WeakAnyLinkage &&
475 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000476 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000477 Linkage != GlobalValue::PrivateLinkage &&
478 Linkage != GlobalValue::LinkerPrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000479 return Error(LinkageLoc, "invalid linkage type for alias");
480
481 Constant *Aliasee;
482 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000483 if (Lex.getKind() != lltok::kw_bitcast &&
484 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000485 if (ParseGlobalTypeAndValue(Aliasee)) return true;
486 } else {
487 // The bitcast dest type is not present, it is implied by the dest type.
488 ValID ID;
489 if (ParseValID(ID)) return true;
490 if (ID.Kind != ValID::t_Constant)
491 return Error(AliaseeLoc, "invalid aliasee");
492 Aliasee = ID.ConstantVal;
493 }
494
495 if (!isa<PointerType>(Aliasee->getType()))
496 return Error(AliaseeLoc, "alias must have pointer type");
497
498 // Okay, create the alias but do not insert it into the module yet.
499 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
500 (GlobalValue::LinkageTypes)Linkage, Name,
501 Aliasee);
502 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
503
504 // See if this value already exists in the symbol table. If so, it is either
505 // a redefinition or a definition of a forward reference.
506 if (GlobalValue *Val =
507 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
508 // See if this was a redefinition. If so, there is no entry in
509 // ForwardRefVals.
510 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
511 I = ForwardRefVals.find(Name);
512 if (I == ForwardRefVals.end())
513 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
514
515 // Otherwise, this was a definition of forward ref. Verify that types
516 // agree.
517 if (Val->getType() != GA->getType())
518 return Error(NameLoc,
519 "forward reference and definition of alias have different types");
520
521 // If they agree, just RAUW the old value with the alias and remove the
522 // forward ref info.
523 Val->replaceAllUsesWith(GA);
524 Val->eraseFromParent();
525 ForwardRefVals.erase(I);
526 }
527
528 // Insert into the module, we know its name won't collide now.
529 M->getAliasList().push_back(GA);
530 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
531
532 return false;
533}
534
535/// ParseGlobal
536/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
537/// OptionalAddrSpace GlobalType Type Const
538/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
539/// OptionalAddrSpace GlobalType Type Const
540///
541/// Everything through visibility has been parsed already.
542///
543bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
544 unsigned Linkage, bool HasLinkage,
545 unsigned Visibility) {
546 unsigned AddrSpace;
547 bool ThreadLocal, IsConstant;
548 LocTy TyLoc;
549
550 PATypeHolder Ty(Type::VoidTy);
551 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
552 ParseOptionalAddrSpace(AddrSpace) ||
553 ParseGlobalType(IsConstant) ||
554 ParseType(Ty, TyLoc))
555 return true;
556
557 // If the linkage is specified and is external, then no initializer is
558 // present.
559 Constant *Init = 0;
560 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000561 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000562 Linkage != GlobalValue::ExternalLinkage)) {
563 if (ParseGlobalValue(Ty, Init))
564 return true;
565 }
566
Chris Lattnera9a9e072009-03-09 04:49:14 +0000567 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
Chris Lattner4a2f1122009-02-08 20:00:15 +0000568 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000569
570 GlobalVariable *GV = 0;
571
572 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000573 if (!Name.empty()) {
574 if ((GV = M->getGlobalVariable(Name, true)) &&
575 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000576 return Error(NameLoc, "redefinition of global '@" + Name + "'");
577 } else {
578 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
579 I = ForwardRefValIDs.find(NumberedVals.size());
580 if (I != ForwardRefValIDs.end()) {
581 GV = cast<GlobalVariable>(I->second.first);
582 ForwardRefValIDs.erase(I);
583 }
584 }
585
586 if (GV == 0) {
Owen Andersone9b11b42009-07-08 19:03:57 +0000587 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
588 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000589 } else {
590 if (GV->getType()->getElementType() != Ty)
591 return Error(TyLoc,
592 "forward reference and definition of global have different types");
593
594 // Move the forward-reference to the correct spot in the module.
595 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
596 }
597
598 if (Name.empty())
599 NumberedVals.push_back(GV);
600
601 // Set the parsed properties on the global.
602 if (Init)
603 GV->setInitializer(Init);
604 GV->setConstant(IsConstant);
605 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
606 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
607 GV->setThreadLocal(ThreadLocal);
608
609 // Parse attributes on the global.
610 while (Lex.getKind() == lltok::comma) {
611 Lex.Lex();
612
613 if (Lex.getKind() == lltok::kw_section) {
614 Lex.Lex();
615 GV->setSection(Lex.getStrVal());
616 if (ParseToken(lltok::StringConstant, "expected global section string"))
617 return true;
618 } else if (Lex.getKind() == lltok::kw_align) {
619 unsigned Alignment;
620 if (ParseOptionalAlignment(Alignment)) return true;
621 GV->setAlignment(Alignment);
622 } else {
623 TokError("unknown global variable property!");
624 }
625 }
626
627 return false;
628}
629
630
631//===----------------------------------------------------------------------===//
632// GlobalValue Reference/Resolution Routines.
633//===----------------------------------------------------------------------===//
634
635/// GetGlobalVal - Get a value with the specified name or ID, creating a
636/// forward reference record if needed. This can return null if the value
637/// exists but does not have the right type.
638GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
639 LocTy Loc) {
640 const PointerType *PTy = dyn_cast<PointerType>(Ty);
641 if (PTy == 0) {
642 Error(Loc, "global variable reference must have pointer type");
643 return 0;
644 }
645
646 // Look this name up in the normal function symbol table.
647 GlobalValue *Val =
648 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
649
650 // If this is a forward reference for the value, see if we already created a
651 // forward ref record.
652 if (Val == 0) {
653 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
654 I = ForwardRefVals.find(Name);
655 if (I != ForwardRefVals.end())
656 Val = I->second.first;
657 }
658
659 // If we have the value in the symbol table or fwd-ref table, return it.
660 if (Val) {
661 if (Val->getType() == Ty) return Val;
662 Error(Loc, "'@" + Name + "' defined with type '" +
663 Val->getType()->getDescription() + "'");
664 return 0;
665 }
666
667 // Otherwise, create a new forward reference for this value and remember it.
668 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000669 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
670 // Function types can return opaque but functions can't.
671 if (isa<OpaqueType>(FT->getReturnType())) {
672 Error(Loc, "function may not return opaque type");
673 return 0;
674 }
675
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000676 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000677 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000678 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
679 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000680 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000681
682 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
683 return FwdVal;
684}
685
686GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
687 const PointerType *PTy = dyn_cast<PointerType>(Ty);
688 if (PTy == 0) {
689 Error(Loc, "global variable reference must have pointer type");
690 return 0;
691 }
692
693 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
694
695 // If this is a forward reference for the value, see if we already created a
696 // forward ref record.
697 if (Val == 0) {
698 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
699 I = ForwardRefValIDs.find(ID);
700 if (I != ForwardRefValIDs.end())
701 Val = I->second.first;
702 }
703
704 // If we have the value in the symbol table or fwd-ref table, return it.
705 if (Val) {
706 if (Val->getType() == Ty) return Val;
707 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
708 Val->getType()->getDescription() + "'");
709 return 0;
710 }
711
712 // Otherwise, create a new forward reference for this value and remember it.
713 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000714 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
715 // Function types can return opaque but functions can't.
716 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000717 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000718 return 0;
719 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000720 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000721 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000722 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
723 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000724 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000725
726 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
727 return FwdVal;
728}
729
730
731//===----------------------------------------------------------------------===//
732// Helper Routines.
733//===----------------------------------------------------------------------===//
734
735/// ParseToken - If the current token has the specified kind, eat it and return
736/// success. Otherwise, emit the specified error and return failure.
737bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
738 if (Lex.getKind() != T)
739 return TokError(ErrMsg);
740 Lex.Lex();
741 return false;
742}
743
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000744/// ParseStringConstant
745/// ::= StringConstant
746bool LLParser::ParseStringConstant(std::string &Result) {
747 if (Lex.getKind() != lltok::StringConstant)
748 return TokError("expected string constant");
749 Result = Lex.getStrVal();
750 Lex.Lex();
751 return false;
752}
753
754/// ParseUInt32
755/// ::= uint32
756bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000757 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
758 return TokError("expected integer");
759 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
760 if (Val64 != unsigned(Val64))
761 return TokError("expected 32-bit integer (too large)");
762 Val = Val64;
763 Lex.Lex();
764 return false;
765}
766
767
768/// ParseOptionalAddrSpace
769/// := /*empty*/
770/// := 'addrspace' '(' uint32 ')'
771bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
772 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000773 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000774 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000775 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000776 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000777 ParseToken(lltok::rparen, "expected ')' in address space");
778}
779
780/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
781/// indicates what kind of attribute list this is: 0: function arg, 1: result,
782/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000783/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000784bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
785 Attrs = Attribute::None;
786 LocTy AttrLoc = Lex.getLoc();
787
788 while (1) {
789 switch (Lex.getKind()) {
790 case lltok::kw_sext:
791 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000792 // Treat these as signext/zeroext if they occur in the argument list after
793 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
794 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
795 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000796 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000797 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000798 if (Lex.getKind() == lltok::kw_sext)
799 Attrs |= Attribute::SExt;
800 else
801 Attrs |= Attribute::ZExt;
802 break;
803 }
804 // FALL THROUGH.
805 default: // End of attributes.
806 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
807 return Error(AttrLoc, "invalid use of function-only attribute");
808
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000809 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000810 return Error(AttrLoc, "invalid use of parameter-only attribute");
811
812 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000813 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
814 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
815 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
816 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
817 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
818 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
819 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
820 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000821
Devang Patel578efa92009-06-05 21:57:13 +0000822 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
823 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
824 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
825 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
826 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
827 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
828 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
829 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
830 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
831 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
832 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000833 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000834
835 case lltok::kw_align: {
836 unsigned Alignment;
837 if (ParseOptionalAlignment(Alignment))
838 return true;
839 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
840 continue;
841 }
842 }
843 Lex.Lex();
844 }
845}
846
847/// ParseOptionalLinkage
848/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000849/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000850/// ::= 'linker_private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000851/// ::= 'internal'
852/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000853/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000854/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000855/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000856/// ::= 'appending'
857/// ::= 'dllexport'
858/// ::= 'common'
859/// ::= 'dllimport'
860/// ::= 'extern_weak'
861/// ::= 'external'
862bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
863 HasLinkage = false;
864 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000865 default: Res=GlobalValue::ExternalLinkage; return false;
866 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
867 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
868 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
869 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
870 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
871 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
872 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000873 case lltok::kw_available_externally:
874 Res = GlobalValue::AvailableExternallyLinkage;
875 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000876 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
877 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
878 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
879 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
880 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
881 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000882 }
883 Lex.Lex();
884 HasLinkage = true;
885 return false;
886}
887
888/// ParseOptionalVisibility
889/// ::= /*empty*/
890/// ::= 'default'
891/// ::= 'hidden'
892/// ::= 'protected'
893///
894bool LLParser::ParseOptionalVisibility(unsigned &Res) {
895 switch (Lex.getKind()) {
896 default: Res = GlobalValue::DefaultVisibility; return false;
897 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
898 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
899 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
900 }
901 Lex.Lex();
902 return false;
903}
904
905/// ParseOptionalCallingConv
906/// ::= /*empty*/
907/// ::= 'ccc'
908/// ::= 'fastcc'
909/// ::= 'coldcc'
910/// ::= 'x86_stdcallcc'
911/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000912/// ::= 'arm_apcscc'
913/// ::= 'arm_aapcscc'
914/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +0000915/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000916///
Chris Lattnerdf986172009-01-02 07:01:27 +0000917bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
918 switch (Lex.getKind()) {
919 default: CC = CallingConv::C; return false;
920 case lltok::kw_ccc: CC = CallingConv::C; break;
921 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
922 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
923 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
924 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000925 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
926 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
927 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000928 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000929 }
930 Lex.Lex();
931 return false;
932}
933
934/// ParseOptionalAlignment
935/// ::= /* empty */
936/// ::= 'align' 4
937bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
938 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000939 if (!EatIfPresent(lltok::kw_align))
940 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000941 LocTy AlignLoc = Lex.getLoc();
942 if (ParseUInt32(Alignment)) return true;
943 if (!isPowerOf2_32(Alignment))
944 return Error(AlignLoc, "alignment is not a power of two");
945 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000946}
947
948/// ParseOptionalCommaAlignment
949/// ::= /* empty */
950/// ::= ',' 'align' 4
951bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
952 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000953 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000954 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000955 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000956 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000957}
958
959/// ParseIndexList
960/// ::= (',' uint32)+
961bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
962 if (Lex.getKind() != lltok::comma)
963 return TokError("expected ',' as start of index list");
964
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000965 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000966 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000967 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000968 Indices.push_back(Idx);
969 }
970
971 return false;
972}
973
974//===----------------------------------------------------------------------===//
975// Type Parsing.
976//===----------------------------------------------------------------------===//
977
978/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +0000979bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
980 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000981 if (ParseTypeRec(Result)) return true;
982
983 // Verify no unresolved uprefs.
984 if (!UpRefs.empty())
985 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000986
Chris Lattnera9a9e072009-03-09 04:49:14 +0000987 if (!AllowVoid && Result.get() == Type::VoidTy)
988 return Error(TypeLoc, "void type only allowed for function results");
989
Chris Lattnerdf986172009-01-02 07:01:27 +0000990 return false;
991}
992
993/// HandleUpRefs - Every time we finish a new layer of types, this function is
994/// called. It loops through the UpRefs vector, which is a list of the
995/// currently active types. For each type, if the up-reference is contained in
996/// the newly completed type, we decrement the level count. When the level
997/// count reaches zero, the up-referenced type is the type that is passed in:
998/// thus we can complete the cycle.
999///
1000PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1001 // If Ty isn't abstract, or if there are no up-references in it, then there is
1002 // nothing to resolve here.
1003 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1004
1005 PATypeHolder Ty(ty);
1006#if 0
1007 errs() << "Type '" << Ty->getDescription()
1008 << "' newly formed. Resolving upreferences.\n"
1009 << UpRefs.size() << " upreferences active!\n";
1010#endif
1011
1012 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1013 // to zero), we resolve them all together before we resolve them to Ty. At
1014 // the end of the loop, if there is anything to resolve to Ty, it will be in
1015 // this variable.
1016 OpaqueType *TypeToResolve = 0;
1017
1018 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1019 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1020 bool ContainsType =
1021 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1022 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1023
1024#if 0
1025 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1026 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1027 << (ContainsType ? "true" : "false")
1028 << " level=" << UpRefs[i].NestingLevel << "\n";
1029#endif
1030 if (!ContainsType)
1031 continue;
1032
1033 // Decrement level of upreference
1034 unsigned Level = --UpRefs[i].NestingLevel;
1035 UpRefs[i].LastContainedTy = Ty;
1036
1037 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1038 if (Level != 0)
1039 continue;
1040
1041#if 0
1042 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1043#endif
1044 if (!TypeToResolve)
1045 TypeToResolve = UpRefs[i].UpRefTy;
1046 else
1047 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1048 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1049 --i; // Do not skip the next element.
1050 }
1051
1052 if (TypeToResolve)
1053 TypeToResolve->refineAbstractTypeTo(Ty);
1054
1055 return Ty;
1056}
1057
1058
1059/// ParseTypeRec - The recursive function used to process the internal
1060/// implementation details of types.
1061bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1062 switch (Lex.getKind()) {
1063 default:
1064 return TokError("expected type");
1065 case lltok::Type:
1066 // TypeRec ::= 'float' | 'void' (etc)
1067 Result = Lex.getTyVal();
1068 Lex.Lex();
1069 break;
1070 case lltok::kw_opaque:
1071 // TypeRec ::= 'opaque'
Owen Andersonfba933c2009-07-01 23:57:11 +00001072 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001073 Lex.Lex();
1074 break;
1075 case lltok::lbrace:
1076 // TypeRec ::= '{' ... '}'
1077 if (ParseStructType(Result, false))
1078 return true;
1079 break;
1080 case lltok::lsquare:
1081 // TypeRec ::= '[' ... ']'
1082 Lex.Lex(); // eat the lsquare.
1083 if (ParseArrayVectorType(Result, false))
1084 return true;
1085 break;
1086 case lltok::less: // Either vector or packed struct.
1087 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001088 Lex.Lex();
1089 if (Lex.getKind() == lltok::lbrace) {
1090 if (ParseStructType(Result, true) ||
1091 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001092 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001093 } else if (ParseArrayVectorType(Result, true))
1094 return true;
1095 break;
1096 case lltok::LocalVar:
1097 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1098 // TypeRec ::= %foo
1099 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1100 Result = T;
1101 } else {
Owen Andersonfba933c2009-07-01 23:57:11 +00001102 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001103 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1104 std::make_pair(Result,
1105 Lex.getLoc())));
1106 M->addTypeName(Lex.getStrVal(), Result.get());
1107 }
1108 Lex.Lex();
1109 break;
1110
1111 case lltok::LocalVarID:
1112 // TypeRec ::= %4
1113 if (Lex.getUIntVal() < NumberedTypes.size())
1114 Result = NumberedTypes[Lex.getUIntVal()];
1115 else {
1116 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1117 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1118 if (I != ForwardRefTypeIDs.end())
1119 Result = I->second.first;
1120 else {
Owen Andersonfba933c2009-07-01 23:57:11 +00001121 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001122 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1123 std::make_pair(Result,
1124 Lex.getLoc())));
1125 }
1126 }
1127 Lex.Lex();
1128 break;
1129 case lltok::backslash: {
1130 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001131 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001132 unsigned Val;
1133 if (ParseUInt32(Val)) return true;
Owen Andersonfba933c2009-07-01 23:57:11 +00001134 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001135 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1136 Result = OT;
1137 break;
1138 }
1139 }
1140
1141 // Parse the type suffixes.
1142 while (1) {
1143 switch (Lex.getKind()) {
1144 // End of type.
1145 default: return false;
1146
1147 // TypeRec ::= TypeRec '*'
1148 case lltok::star:
1149 if (Result.get() == Type::LabelTy)
1150 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001151 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001152 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001153 if (!PointerType::isValidElementType(Result.get()))
1154 return TokError("pointer to this type is invalid");
Owen Andersonfba933c2009-07-01 23:57:11 +00001155 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001156 Lex.Lex();
1157 break;
1158
1159 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1160 case lltok::kw_addrspace: {
1161 if (Result.get() == Type::LabelTy)
1162 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001163 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001164 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001165 if (!PointerType::isValidElementType(Result.get()))
1166 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001167 unsigned AddrSpace;
1168 if (ParseOptionalAddrSpace(AddrSpace) ||
1169 ParseToken(lltok::star, "expected '*' in address space"))
1170 return true;
1171
Owen Andersonfba933c2009-07-01 23:57:11 +00001172 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001173 break;
1174 }
1175
1176 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1177 case lltok::lparen:
1178 if (ParseFunctionType(Result))
1179 return true;
1180 break;
1181 }
1182 }
1183}
1184
1185/// ParseParameterList
1186/// ::= '(' ')'
1187/// ::= '(' Arg (',' Arg)* ')'
1188/// Arg
1189/// ::= Type OptionalAttributes Value OptionalAttributes
1190bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1191 PerFunctionState &PFS) {
1192 if (ParseToken(lltok::lparen, "expected '(' in call"))
1193 return true;
1194
1195 while (Lex.getKind() != lltok::rparen) {
1196 // If this isn't the first argument, we need a comma.
1197 if (!ArgList.empty() &&
1198 ParseToken(lltok::comma, "expected ',' in argument list"))
1199 return true;
1200
1201 // Parse the argument.
1202 LocTy ArgLoc;
1203 PATypeHolder ArgTy(Type::VoidTy);
1204 unsigned ArgAttrs1, ArgAttrs2;
1205 Value *V;
1206 if (ParseType(ArgTy, ArgLoc) ||
1207 ParseOptionalAttrs(ArgAttrs1, 0) ||
1208 ParseValue(ArgTy, V, PFS) ||
1209 // FIXME: Should not allow attributes after the argument, remove this in
1210 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001211 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001212 return true;
1213 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1214 }
1215
1216 Lex.Lex(); // Lex the ')'.
1217 return false;
1218}
1219
1220
1221
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001222/// ParseArgumentList - Parse the argument list for a function type or function
1223/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001224/// ::= '(' ArgTypeListI ')'
1225/// ArgTypeListI
1226/// ::= /*empty*/
1227/// ::= '...'
1228/// ::= ArgTypeList ',' '...'
1229/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001230///
Chris Lattnerdf986172009-01-02 07:01:27 +00001231bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001232 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001233 isVarArg = false;
1234 assert(Lex.getKind() == lltok::lparen);
1235 Lex.Lex(); // eat the (.
1236
1237 if (Lex.getKind() == lltok::rparen) {
1238 // empty
1239 } else if (Lex.getKind() == lltok::dotdotdot) {
1240 isVarArg = true;
1241 Lex.Lex();
1242 } else {
1243 LocTy TypeLoc = Lex.getLoc();
1244 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001245 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001246 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001247
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001248 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1249 // types (such as a function returning a pointer to itself). If parsing a
1250 // function prototype, we require fully resolved types.
1251 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001252 ParseOptionalAttrs(Attrs, 0)) return true;
1253
Chris Lattnera9a9e072009-03-09 04:49:14 +00001254 if (ArgTy == Type::VoidTy)
1255 return Error(TypeLoc, "argument can not have void type");
1256
Chris Lattnerdf986172009-01-02 07:01:27 +00001257 if (Lex.getKind() == lltok::LocalVar ||
1258 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1259 Name = Lex.getStrVal();
1260 Lex.Lex();
1261 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001262
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001263 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001264 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001265
1266 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1267
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001268 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001269 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001270 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001271 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001272 break;
1273 }
1274
1275 // Otherwise must be an argument type.
1276 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001277 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001278 ParseOptionalAttrs(Attrs, 0)) return true;
1279
Chris Lattnera9a9e072009-03-09 04:49:14 +00001280 if (ArgTy == Type::VoidTy)
1281 return Error(TypeLoc, "argument can not have void type");
1282
Chris Lattnerdf986172009-01-02 07:01:27 +00001283 if (Lex.getKind() == lltok::LocalVar ||
1284 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1285 Name = Lex.getStrVal();
1286 Lex.Lex();
1287 } else {
1288 Name = "";
1289 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001290
1291 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1292 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001293
1294 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1295 }
1296 }
1297
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001298 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001299}
1300
1301/// ParseFunctionType
1302/// ::= Type ArgumentList OptionalAttrs
1303bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1304 assert(Lex.getKind() == lltok::lparen);
1305
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001306 if (!FunctionType::isValidReturnType(Result))
1307 return TokError("invalid function return type");
1308
Chris Lattnerdf986172009-01-02 07:01:27 +00001309 std::vector<ArgInfo> ArgList;
1310 bool isVarArg;
1311 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001312 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001313 // FIXME: Allow, but ignore attributes on function types!
1314 // FIXME: Remove in LLVM 3.0
1315 ParseOptionalAttrs(Attrs, 2))
1316 return true;
1317
1318 // Reject names on the arguments lists.
1319 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1320 if (!ArgList[i].Name.empty())
1321 return Error(ArgList[i].Loc, "argument name invalid in function type");
1322 if (!ArgList[i].Attrs != 0) {
1323 // Allow but ignore attributes on function types; this permits
1324 // auto-upgrade.
1325 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1326 }
1327 }
1328
1329 std::vector<const Type*> ArgListTy;
1330 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1331 ArgListTy.push_back(ArgList[i].Type);
1332
Owen Andersonfba933c2009-07-01 23:57:11 +00001333 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1334 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001335 return false;
1336}
1337
1338/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1339/// TypeRec
1340/// ::= '{' '}'
1341/// ::= '{' TypeRec (',' TypeRec)* '}'
1342/// ::= '<' '{' '}' '>'
1343/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1344bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1345 assert(Lex.getKind() == lltok::lbrace);
1346 Lex.Lex(); // Consume the '{'
1347
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001348 if (EatIfPresent(lltok::rbrace)) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001349 Result = Context.getStructType(Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001350 return false;
1351 }
1352
1353 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001354 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001355 if (ParseTypeRec(Result)) return true;
1356 ParamsList.push_back(Result);
1357
Chris Lattnera9a9e072009-03-09 04:49:14 +00001358 if (Result == Type::VoidTy)
1359 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001360 if (!StructType::isValidElementType(Result))
1361 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001362
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001363 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001364 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001365 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001366
1367 if (Result == Type::VoidTy)
1368 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001369 if (!StructType::isValidElementType(Result))
1370 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001371
Chris Lattnerdf986172009-01-02 07:01:27 +00001372 ParamsList.push_back(Result);
1373 }
1374
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001375 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1376 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001377
1378 std::vector<const Type*> ParamsListTy;
1379 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1380 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersonfba933c2009-07-01 23:57:11 +00001381 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001382 return false;
1383}
1384
1385/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1386/// token has already been consumed.
1387/// TypeRec
1388/// ::= '[' APSINTVAL 'x' Types ']'
1389/// ::= '<' APSINTVAL 'x' Types '>'
1390bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1391 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1392 Lex.getAPSIntVal().getBitWidth() > 64)
1393 return TokError("expected number in address space");
1394
1395 LocTy SizeLoc = Lex.getLoc();
1396 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001397 Lex.Lex();
1398
1399 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1400 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001401
1402 LocTy TypeLoc = Lex.getLoc();
1403 PATypeHolder EltTy(Type::VoidTy);
1404 if (ParseTypeRec(EltTy)) return true;
1405
Chris Lattnera9a9e072009-03-09 04:49:14 +00001406 if (EltTy == Type::VoidTy)
1407 return Error(TypeLoc, "array and vector element type cannot be void");
1408
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001409 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1410 "expected end of sequential type"))
1411 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001412
1413 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001414 if (Size == 0)
1415 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001416 if ((unsigned)Size != Size)
1417 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001418 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001419 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersonfba933c2009-07-01 23:57:11 +00001420 Result = Context.getVectorType(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001421 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001422 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001423 return Error(TypeLoc, "invalid array element type");
Owen Andersonfba933c2009-07-01 23:57:11 +00001424 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001425 }
1426 return false;
1427}
1428
1429//===----------------------------------------------------------------------===//
1430// Function Semantic Analysis.
1431//===----------------------------------------------------------------------===//
1432
1433LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1434 : P(p), F(f) {
1435
1436 // Insert unnamed arguments into the NumberedVals list.
1437 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1438 AI != E; ++AI)
1439 if (!AI->hasName())
1440 NumberedVals.push_back(AI);
1441}
1442
1443LLParser::PerFunctionState::~PerFunctionState() {
1444 // If there were any forward referenced non-basicblock values, delete them.
1445 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1446 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1447 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001448 I->second.first->replaceAllUsesWith(
1449 P.getContext().getUndef(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001450 delete I->second.first;
1451 I->second.first = 0;
1452 }
1453
1454 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1455 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1456 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001457 I->second.first->replaceAllUsesWith(
1458 P.getContext().getUndef(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001459 delete I->second.first;
1460 I->second.first = 0;
1461 }
1462}
1463
1464bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1465 if (!ForwardRefVals.empty())
1466 return P.Error(ForwardRefVals.begin()->second.second,
1467 "use of undefined value '%" + ForwardRefVals.begin()->first +
1468 "'");
1469 if (!ForwardRefValIDs.empty())
1470 return P.Error(ForwardRefValIDs.begin()->second.second,
1471 "use of undefined value '%" +
1472 utostr(ForwardRefValIDs.begin()->first) + "'");
1473 return false;
1474}
1475
1476
1477/// GetVal - Get a value with the specified name or ID, creating a
1478/// forward reference record if needed. This can return null if the value
1479/// exists but does not have the right type.
1480Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1481 const Type *Ty, LocTy Loc) {
1482 // Look this name up in the normal function symbol table.
1483 Value *Val = F.getValueSymbolTable().lookup(Name);
1484
1485 // If this is a forward reference for the value, see if we already created a
1486 // forward ref record.
1487 if (Val == 0) {
1488 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1489 I = ForwardRefVals.find(Name);
1490 if (I != ForwardRefVals.end())
1491 Val = I->second.first;
1492 }
1493
1494 // If we have the value in the symbol table or fwd-ref table, return it.
1495 if (Val) {
1496 if (Val->getType() == Ty) return Val;
1497 if (Ty == Type::LabelTy)
1498 P.Error(Loc, "'%" + Name + "' is not a basic block");
1499 else
1500 P.Error(Loc, "'%" + Name + "' defined with type '" +
1501 Val->getType()->getDescription() + "'");
1502 return 0;
1503 }
1504
1505 // Don't make placeholders with invalid type.
1506 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1507 P.Error(Loc, "invalid use of a non-first-class type");
1508 return 0;
1509 }
1510
1511 // Otherwise, create a new forward reference for this value and remember it.
1512 Value *FwdVal;
1513 if (Ty == Type::LabelTy)
1514 FwdVal = BasicBlock::Create(Name, &F);
1515 else
1516 FwdVal = new Argument(Ty, Name);
1517
1518 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1519 return FwdVal;
1520}
1521
1522Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1523 LocTy Loc) {
1524 // Look this name up in the normal function symbol table.
1525 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1526
1527 // If this is a forward reference for the value, see if we already created a
1528 // forward ref record.
1529 if (Val == 0) {
1530 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1531 I = ForwardRefValIDs.find(ID);
1532 if (I != ForwardRefValIDs.end())
1533 Val = I->second.first;
1534 }
1535
1536 // If we have the value in the symbol table or fwd-ref table, return it.
1537 if (Val) {
1538 if (Val->getType() == Ty) return Val;
1539 if (Ty == Type::LabelTy)
1540 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1541 else
1542 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1543 Val->getType()->getDescription() + "'");
1544 return 0;
1545 }
1546
1547 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1548 P.Error(Loc, "invalid use of a non-first-class type");
1549 return 0;
1550 }
1551
1552 // Otherwise, create a new forward reference for this value and remember it.
1553 Value *FwdVal;
1554 if (Ty == Type::LabelTy)
1555 FwdVal = BasicBlock::Create("", &F);
1556 else
1557 FwdVal = new Argument(Ty);
1558
1559 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1560 return FwdVal;
1561}
1562
1563/// SetInstName - After an instruction is parsed and inserted into its
1564/// basic block, this installs its name.
1565bool LLParser::PerFunctionState::SetInstName(int NameID,
1566 const std::string &NameStr,
1567 LocTy NameLoc, Instruction *Inst) {
1568 // If this instruction has void type, it cannot have a name or ID specified.
1569 if (Inst->getType() == Type::VoidTy) {
1570 if (NameID != -1 || !NameStr.empty())
1571 return P.Error(NameLoc, "instructions returning void cannot have a name");
1572 return false;
1573 }
1574
1575 // If this was a numbered instruction, verify that the instruction is the
1576 // expected value and resolve any forward references.
1577 if (NameStr.empty()) {
1578 // If neither a name nor an ID was specified, just use the next ID.
1579 if (NameID == -1)
1580 NameID = NumberedVals.size();
1581
1582 if (unsigned(NameID) != NumberedVals.size())
1583 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1584 utostr(NumberedVals.size()) + "'");
1585
1586 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1587 ForwardRefValIDs.find(NameID);
1588 if (FI != ForwardRefValIDs.end()) {
1589 if (FI->second.first->getType() != Inst->getType())
1590 return P.Error(NameLoc, "instruction forward referenced with type '" +
1591 FI->second.first->getType()->getDescription() + "'");
1592 FI->second.first->replaceAllUsesWith(Inst);
1593 ForwardRefValIDs.erase(FI);
1594 }
1595
1596 NumberedVals.push_back(Inst);
1597 return false;
1598 }
1599
1600 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1601 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1602 FI = ForwardRefVals.find(NameStr);
1603 if (FI != ForwardRefVals.end()) {
1604 if (FI->second.first->getType() != Inst->getType())
1605 return P.Error(NameLoc, "instruction forward referenced with type '" +
1606 FI->second.first->getType()->getDescription() + "'");
1607 FI->second.first->replaceAllUsesWith(Inst);
1608 ForwardRefVals.erase(FI);
1609 }
1610
1611 // Set the name on the instruction.
1612 Inst->setName(NameStr);
1613
1614 if (Inst->getNameStr() != NameStr)
1615 return P.Error(NameLoc, "multiple definition of local value named '" +
1616 NameStr + "'");
1617 return false;
1618}
1619
1620/// GetBB - Get a basic block with the specified name or ID, creating a
1621/// forward reference record if needed.
1622BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1623 LocTy Loc) {
1624 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1625}
1626
1627BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1628 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1629}
1630
1631/// DefineBB - Define the specified basic block, which is either named or
1632/// unnamed. If there is an error, this returns null otherwise it returns
1633/// the block being defined.
1634BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1635 LocTy Loc) {
1636 BasicBlock *BB;
1637 if (Name.empty())
1638 BB = GetBB(NumberedVals.size(), Loc);
1639 else
1640 BB = GetBB(Name, Loc);
1641 if (BB == 0) return 0; // Already diagnosed error.
1642
1643 // Move the block to the end of the function. Forward ref'd blocks are
1644 // inserted wherever they happen to be referenced.
1645 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1646
1647 // Remove the block from forward ref sets.
1648 if (Name.empty()) {
1649 ForwardRefValIDs.erase(NumberedVals.size());
1650 NumberedVals.push_back(BB);
1651 } else {
1652 // BB forward references are already in the function symbol table.
1653 ForwardRefVals.erase(Name);
1654 }
1655
1656 return BB;
1657}
1658
1659//===----------------------------------------------------------------------===//
1660// Constants.
1661//===----------------------------------------------------------------------===//
1662
1663/// ParseValID - Parse an abstract value that doesn't necessarily have a
1664/// type implied. For example, if we parse "4" we don't know what integer type
1665/// it has. The value will later be combined with its type and checked for
1666/// sanity.
1667bool LLParser::ParseValID(ValID &ID) {
1668 ID.Loc = Lex.getLoc();
1669 switch (Lex.getKind()) {
1670 default: return TokError("expected value token");
1671 case lltok::GlobalID: // @42
1672 ID.UIntVal = Lex.getUIntVal();
1673 ID.Kind = ValID::t_GlobalID;
1674 break;
1675 case lltok::GlobalVar: // @foo
1676 ID.StrVal = Lex.getStrVal();
1677 ID.Kind = ValID::t_GlobalName;
1678 break;
1679 case lltok::LocalVarID: // %42
1680 ID.UIntVal = Lex.getUIntVal();
1681 ID.Kind = ValID::t_LocalID;
1682 break;
1683 case lltok::LocalVar: // %foo
1684 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1685 ID.StrVal = Lex.getStrVal();
1686 ID.Kind = ValID::t_LocalName;
1687 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001688 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
Devang Patel104cf9e2009-07-23 01:07:34 +00001689 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001690 Lex.Lex();
1691 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001692 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001693 if (ParseMDNodeVector(Elts) ||
1694 ParseToken(lltok::rbrace, "expected end of metadata node"))
1695 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001696
Devang Patel104cf9e2009-07-23 01:07:34 +00001697 ID.MetadataVal = Context.getMDNode(Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001698 return false;
1699 }
1700
Devang Patel923078c2009-07-01 19:21:12 +00001701 // Standalone metadata reference
1702 // !{ ..., !42, ... }
Devang Patel104cf9e2009-07-23 01:07:34 +00001703 if (!ParseMDNode(ID.MetadataVal))
Devang Patel923078c2009-07-01 19:21:12 +00001704 return false;
Devang Patel256be962009-07-20 19:00:08 +00001705
Nick Lewycky21cc4462009-04-04 07:22:01 +00001706 // MDString:
1707 // ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +00001708 if (ParseMDString(ID.MetadataVal)) return true;
1709 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001710 return false;
1711 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001712 case lltok::APSInt:
1713 ID.APSIntVal = Lex.getAPSIntVal();
1714 ID.Kind = ValID::t_APSInt;
1715 break;
1716 case lltok::APFloat:
1717 ID.APFloatVal = Lex.getAPFloatVal();
1718 ID.Kind = ValID::t_APFloat;
1719 break;
1720 case lltok::kw_true:
Owen Andersonb3056fa2009-07-21 18:03:38 +00001721 ID.ConstantVal = Context.getTrue();
Chris Lattnerdf986172009-01-02 07:01:27 +00001722 ID.Kind = ValID::t_Constant;
1723 break;
1724 case lltok::kw_false:
Owen Andersonb3056fa2009-07-21 18:03:38 +00001725 ID.ConstantVal = Context.getFalse();
Chris Lattnerdf986172009-01-02 07:01:27 +00001726 ID.Kind = ValID::t_Constant;
1727 break;
1728 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1729 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1730 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1731
1732 case lltok::lbrace: {
1733 // ValID ::= '{' ConstVector '}'
1734 Lex.Lex();
1735 SmallVector<Constant*, 16> Elts;
1736 if (ParseGlobalValueVector(Elts) ||
1737 ParseToken(lltok::rbrace, "expected end of struct constant"))
1738 return true;
1739
Owen Andersonfba933c2009-07-01 23:57:11 +00001740 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001741 ID.Kind = ValID::t_Constant;
1742 return false;
1743 }
1744 case lltok::less: {
1745 // ValID ::= '<' ConstVector '>' --> Vector.
1746 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1747 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001748 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001749
1750 SmallVector<Constant*, 16> Elts;
1751 LocTy FirstEltLoc = Lex.getLoc();
1752 if (ParseGlobalValueVector(Elts) ||
1753 (isPackedStruct &&
1754 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1755 ParseToken(lltok::greater, "expected end of constant"))
1756 return true;
1757
1758 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001759 ID.ConstantVal =
1760 Context.getConstantStruct(Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001761 ID.Kind = ValID::t_Constant;
1762 return false;
1763 }
1764
1765 if (Elts.empty())
1766 return Error(ID.Loc, "constant vector must not be empty");
1767
1768 if (!Elts[0]->getType()->isInteger() &&
1769 !Elts[0]->getType()->isFloatingPoint())
1770 return Error(FirstEltLoc,
1771 "vector elements must have integer or floating point type");
1772
1773 // Verify that all the vector elements have the same type.
1774 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1775 if (Elts[i]->getType() != Elts[0]->getType())
1776 return Error(FirstEltLoc,
1777 "vector element #" + utostr(i) +
1778 " is not of type '" + Elts[0]->getType()->getDescription());
1779
Owen Andersonfba933c2009-07-01 23:57:11 +00001780 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001781 ID.Kind = ValID::t_Constant;
1782 return false;
1783 }
1784 case lltok::lsquare: { // Array Constant
1785 Lex.Lex();
1786 SmallVector<Constant*, 16> Elts;
1787 LocTy FirstEltLoc = Lex.getLoc();
1788 if (ParseGlobalValueVector(Elts) ||
1789 ParseToken(lltok::rsquare, "expected end of array constant"))
1790 return true;
1791
1792 // Handle empty element.
1793 if (Elts.empty()) {
1794 // Use undef instead of an array because it's inconvenient to determine
1795 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001796 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001797 return false;
1798 }
1799
1800 if (!Elts[0]->getType()->isFirstClassType())
1801 return Error(FirstEltLoc, "invalid array element type: " +
1802 Elts[0]->getType()->getDescription());
1803
Owen Andersonfba933c2009-07-01 23:57:11 +00001804 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001805
1806 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001807 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001808 if (Elts[i]->getType() != Elts[0]->getType())
1809 return Error(FirstEltLoc,
1810 "array element #" + utostr(i) +
1811 " is not of type '" +Elts[0]->getType()->getDescription());
1812 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001813
Owen Andersonfba933c2009-07-01 23:57:11 +00001814 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001815 ID.Kind = ValID::t_Constant;
1816 return false;
1817 }
1818 case lltok::kw_c: // c "foo"
1819 Lex.Lex();
Owen Andersonfba933c2009-07-01 23:57:11 +00001820 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001821 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1822 ID.Kind = ValID::t_Constant;
1823 return false;
1824
1825 case lltok::kw_asm: {
1826 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1827 bool HasSideEffect;
1828 Lex.Lex();
1829 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001830 ParseStringConstant(ID.StrVal) ||
1831 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001832 ParseToken(lltok::StringConstant, "expected constraint string"))
1833 return true;
1834 ID.StrVal2 = Lex.getStrVal();
1835 ID.UIntVal = HasSideEffect;
1836 ID.Kind = ValID::t_InlineAsm;
1837 return false;
1838 }
1839
1840 case lltok::kw_trunc:
1841 case lltok::kw_zext:
1842 case lltok::kw_sext:
1843 case lltok::kw_fptrunc:
1844 case lltok::kw_fpext:
1845 case lltok::kw_bitcast:
1846 case lltok::kw_uitofp:
1847 case lltok::kw_sitofp:
1848 case lltok::kw_fptoui:
1849 case lltok::kw_fptosi:
1850 case lltok::kw_inttoptr:
1851 case lltok::kw_ptrtoint: {
1852 unsigned Opc = Lex.getUIntVal();
1853 PATypeHolder DestTy(Type::VoidTy);
1854 Constant *SrcVal;
1855 Lex.Lex();
1856 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1857 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00001858 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001859 ParseType(DestTy) ||
1860 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1861 return true;
1862 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1863 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1864 SrcVal->getType()->getDescription() + "' to '" +
1865 DestTy->getDescription() + "'");
Owen Andersonfba933c2009-07-01 23:57:11 +00001866 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1867 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001868 ID.Kind = ValID::t_Constant;
1869 return false;
1870 }
1871 case lltok::kw_extractvalue: {
1872 Lex.Lex();
1873 Constant *Val;
1874 SmallVector<unsigned, 4> Indices;
1875 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1876 ParseGlobalTypeAndValue(Val) ||
1877 ParseIndexList(Indices) ||
1878 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1879 return true;
1880 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1881 return Error(ID.Loc, "extractvalue operand must be array or struct");
1882 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1883 Indices.end()))
1884 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001885 ID.ConstantVal =
Owen Andersonfba933c2009-07-01 23:57:11 +00001886 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001887 ID.Kind = ValID::t_Constant;
1888 return false;
1889 }
1890 case lltok::kw_insertvalue: {
1891 Lex.Lex();
1892 Constant *Val0, *Val1;
1893 SmallVector<unsigned, 4> Indices;
1894 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1895 ParseGlobalTypeAndValue(Val0) ||
1896 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1897 ParseGlobalTypeAndValue(Val1) ||
1898 ParseIndexList(Indices) ||
1899 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1900 return true;
1901 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1902 return Error(ID.Loc, "extractvalue operand must be array or struct");
1903 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1904 Indices.end()))
1905 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonfba933c2009-07-01 23:57:11 +00001906 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1907 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001908 ID.Kind = ValID::t_Constant;
1909 return false;
1910 }
1911 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001912 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00001913 unsigned PredVal, Opc = Lex.getUIntVal();
1914 Constant *Val0, *Val1;
1915 Lex.Lex();
1916 if (ParseCmpPredicate(PredVal, Opc) ||
1917 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1918 ParseGlobalTypeAndValue(Val0) ||
1919 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1920 ParseGlobalTypeAndValue(Val1) ||
1921 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1922 return true;
1923
1924 if (Val0->getType() != Val1->getType())
1925 return Error(ID.Loc, "compare operands must have the same type");
1926
1927 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1928
1929 if (Opc == Instruction::FCmp) {
1930 if (!Val0->getType()->isFPOrFPVector())
1931 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001932 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001933 } else {
1934 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00001935 if (!Val0->getType()->isIntOrIntVector() &&
1936 !isa<PointerType>(Val0->getType()))
1937 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001938 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001939 }
1940 ID.Kind = ValID::t_Constant;
1941 return false;
1942 }
1943
1944 // Binary Operators.
1945 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001946 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00001947 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001948 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00001949 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001950 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00001951 case lltok::kw_udiv:
1952 case lltok::kw_sdiv:
1953 case lltok::kw_fdiv:
1954 case lltok::kw_urem:
1955 case lltok::kw_srem:
1956 case lltok::kw_frem: {
1957 unsigned Opc = Lex.getUIntVal();
1958 Constant *Val0, *Val1;
1959 Lex.Lex();
1960 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1961 ParseGlobalTypeAndValue(Val0) ||
1962 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1963 ParseGlobalTypeAndValue(Val1) ||
1964 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1965 return true;
1966 if (Val0->getType() != Val1->getType())
1967 return Error(ID.Loc, "operands of constexpr must have same type");
1968 if (!Val0->getType()->isIntOrIntVector() &&
1969 !Val0->getType()->isFPOrFPVector())
1970 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001971 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001972 ID.Kind = ValID::t_Constant;
1973 return false;
1974 }
1975
1976 // Logical Operations
1977 case lltok::kw_shl:
1978 case lltok::kw_lshr:
1979 case lltok::kw_ashr:
1980 case lltok::kw_and:
1981 case lltok::kw_or:
1982 case lltok::kw_xor: {
1983 unsigned Opc = Lex.getUIntVal();
1984 Constant *Val0, *Val1;
1985 Lex.Lex();
1986 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1987 ParseGlobalTypeAndValue(Val0) ||
1988 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1989 ParseGlobalTypeAndValue(Val1) ||
1990 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1991 return true;
1992 if (Val0->getType() != Val1->getType())
1993 return Error(ID.Loc, "operands of constexpr must have same type");
1994 if (!Val0->getType()->isIntOrIntVector())
1995 return Error(ID.Loc,
1996 "constexpr requires integer or integer vector operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001997 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001998 ID.Kind = ValID::t_Constant;
1999 return false;
2000 }
2001
2002 case lltok::kw_getelementptr:
2003 case lltok::kw_shufflevector:
2004 case lltok::kw_insertelement:
2005 case lltok::kw_extractelement:
2006 case lltok::kw_select: {
2007 unsigned Opc = Lex.getUIntVal();
2008 SmallVector<Constant*, 16> Elts;
2009 Lex.Lex();
2010 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2011 ParseGlobalValueVector(Elts) ||
2012 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2013 return true;
2014
2015 if (Opc == Instruction::GetElementPtr) {
2016 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2017 return Error(ID.Loc, "getelementptr requires pointer operand");
2018
2019 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2020 (Value**)&Elts[1], Elts.size()-1))
2021 return Error(ID.Loc, "invalid indices for getelementptr");
Owen Andersonfba933c2009-07-01 23:57:11 +00002022 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
Chris Lattnerdf986172009-01-02 07:01:27 +00002023 &Elts[1], Elts.size()-1);
2024 } else if (Opc == Instruction::Select) {
2025 if (Elts.size() != 3)
2026 return Error(ID.Loc, "expected three operands to select");
2027 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2028 Elts[2]))
2029 return Error(ID.Loc, Reason);
Owen Andersonfba933c2009-07-01 23:57:11 +00002030 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002031 } else if (Opc == Instruction::ShuffleVector) {
2032 if (Elts.size() != 3)
2033 return Error(ID.Loc, "expected three operands to shufflevector");
2034 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2035 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002036 ID.ConstantVal =
2037 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002038 } else if (Opc == Instruction::ExtractElement) {
2039 if (Elts.size() != 2)
2040 return Error(ID.Loc, "expected two operands to extractelement");
2041 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2042 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002043 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002044 } else {
2045 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2046 if (Elts.size() != 3)
2047 return Error(ID.Loc, "expected three operands to insertelement");
2048 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2049 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002050 ID.ConstantVal =
2051 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002052 }
2053
2054 ID.Kind = ValID::t_Constant;
2055 return false;
2056 }
Dan Gohman08d012e2009-07-22 22:44:56 +00002057 case lltok::kw_nuw: {
Dan Gohman1224c382009-07-20 21:19:07 +00002058 Lex.Lex();
Dan Gohman08d012e2009-07-22 22:44:56 +00002059 bool AlsoSigned = EatIfPresent(lltok::kw_nsw);
Dan Gohman1224c382009-07-20 21:19:07 +00002060 if (Lex.getKind() != lltok::kw_add &&
2061 Lex.getKind() != lltok::kw_sub &&
2062 Lex.getKind() != lltok::kw_mul)
2063 return TokError("expected 'add', 'sub', or 'mul'");
2064 bool Result = LLParser::ParseValID(ID);
2065 if (!Result) {
2066 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2067 ->setHasNoUnsignedOverflow(true);
2068 if (AlsoSigned)
2069 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2070 ->setHasNoSignedOverflow(true);
2071 }
2072 return Result;
2073 }
Dan Gohman08d012e2009-07-22 22:44:56 +00002074 case lltok::kw_nsw: {
2075 Lex.Lex();
2076 bool AlsoUnsigned = EatIfPresent(lltok::kw_nuw);
2077 if (Lex.getKind() != lltok::kw_add &&
2078 Lex.getKind() != lltok::kw_sub &&
2079 Lex.getKind() != lltok::kw_mul)
2080 return TokError("expected 'add', 'sub', or 'mul'");
2081 bool Result = LLParser::ParseValID(ID);
2082 if (!Result) {
2083 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2084 ->setHasNoSignedOverflow(true);
2085 if (AlsoUnsigned)
2086 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2087 ->setHasNoUnsignedOverflow(true);
2088 }
2089 return Result;
2090 }
Dan Gohman1224c382009-07-20 21:19:07 +00002091 case lltok::kw_exact: {
2092 Lex.Lex();
2093 if (Lex.getKind() != lltok::kw_sdiv)
2094 return TokError("expected 'sdiv'");
2095 bool Result = LLParser::ParseValID(ID);
2096 if (!Result)
2097 cast<SDivOperator>(ID.ConstantVal)->setIsExact(true);
2098 return Result;
2099 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002100 }
2101
2102 Lex.Lex();
2103 return false;
2104}
2105
2106/// ParseGlobalValue - Parse a global value with the specified type.
2107bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2108 V = 0;
2109 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002110 return ParseValID(ID) ||
2111 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002112}
2113
2114/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2115/// constant.
2116bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2117 Constant *&V) {
2118 if (isa<FunctionType>(Ty))
2119 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2120
2121 switch (ID.Kind) {
Devang Patele54abc92009-07-22 17:43:22 +00002122 default: llvm_unreachable("Unknown ValID!");
2123 case ValID::t_Metadata:
2124 return Error(ID.Loc, "invalid use of metadata");
Chris Lattnerdf986172009-01-02 07:01:27 +00002125 case ValID::t_LocalID:
2126 case ValID::t_LocalName:
2127 return Error(ID.Loc, "invalid use of function-local name");
2128 case ValID::t_InlineAsm:
2129 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2130 case ValID::t_GlobalName:
2131 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2132 return V == 0;
2133 case ValID::t_GlobalID:
2134 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2135 return V == 0;
2136 case ValID::t_APSInt:
2137 if (!isa<IntegerType>(Ty))
2138 return Error(ID.Loc, "integer constant must have integer type");
2139 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonfba933c2009-07-01 23:57:11 +00002140 V = Context.getConstantInt(ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002141 return false;
2142 case ValID::t_APFloat:
2143 if (!Ty->isFloatingPoint() ||
2144 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2145 return Error(ID.Loc, "floating point constant invalid for type");
2146
2147 // The lexer has no type info, so builds all float and double FP constants
2148 // as double. Fix this here. Long double does not need this.
2149 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2150 Ty == Type::FloatTy) {
2151 bool Ignored;
2152 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2153 &Ignored);
2154 }
Owen Andersonfba933c2009-07-01 23:57:11 +00002155 V = Context.getConstantFP(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00002156
2157 if (V->getType() != Ty)
2158 return Error(ID.Loc, "floating point constant does not have type '" +
2159 Ty->getDescription() + "'");
2160
Chris Lattnerdf986172009-01-02 07:01:27 +00002161 return false;
2162 case ValID::t_Null:
2163 if (!isa<PointerType>(Ty))
2164 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonfba933c2009-07-01 23:57:11 +00002165 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002166 return false;
2167 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002168 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00002169 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2170 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002171 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb43eae72009-07-02 17:04:01 +00002172 V = Context.getUndef(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002173 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002174 case ValID::t_EmptyArray:
2175 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2176 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb43eae72009-07-02 17:04:01 +00002177 V = Context.getUndef(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002178 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002179 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002180 // FIXME: LabelTy should not be a first-class type.
2181 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00002182 return Error(ID.Loc, "invalid type for null constant");
Owen Andersonfba933c2009-07-01 23:57:11 +00002183 V = Context.getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002184 return false;
2185 case ValID::t_Constant:
2186 if (ID.ConstantVal->getType() != Ty)
2187 return Error(ID.Loc, "constant expression type mismatch");
2188 V = ID.ConstantVal;
2189 return false;
2190 }
2191}
2192
2193bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2194 PATypeHolder Type(Type::VoidTy);
2195 return ParseType(Type) ||
2196 ParseGlobalValue(Type, V);
2197}
2198
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002199/// ParseGlobalValueVector
2200/// ::= /*empty*/
2201/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002202bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2203 // Empty list.
2204 if (Lex.getKind() == lltok::rbrace ||
2205 Lex.getKind() == lltok::rsquare ||
2206 Lex.getKind() == lltok::greater ||
2207 Lex.getKind() == lltok::rparen)
2208 return false;
2209
2210 Constant *C;
2211 if (ParseGlobalTypeAndValue(C)) return true;
2212 Elts.push_back(C);
2213
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002214 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002215 if (ParseGlobalTypeAndValue(C)) return true;
2216 Elts.push_back(C);
2217 }
2218
2219 return false;
2220}
2221
2222
2223//===----------------------------------------------------------------------===//
2224// Function Parsing.
2225//===----------------------------------------------------------------------===//
2226
2227bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2228 PerFunctionState &PFS) {
2229 if (ID.Kind == ValID::t_LocalID)
2230 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2231 else if (ID.Kind == ValID::t_LocalName)
2232 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002233 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002234 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2235 const FunctionType *FTy =
2236 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2237 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2238 return Error(ID.Loc, "invalid type for inline asm constraint string");
2239 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2240 return false;
Devang Patele54abc92009-07-22 17:43:22 +00002241 } else if (ID.Kind == ValID::t_Metadata) {
2242 V = ID.MetadataVal;
Chris Lattnerdf986172009-01-02 07:01:27 +00002243 } else {
2244 Constant *C;
2245 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2246 V = C;
2247 return false;
2248 }
2249
2250 return V == 0;
2251}
2252
2253bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2254 V = 0;
2255 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002256 return ParseValID(ID) ||
2257 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002258}
2259
2260bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2261 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002262 return ParseType(T) ||
2263 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002264}
2265
2266/// FunctionHeader
2267/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2268/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2269/// OptionalAlign OptGC
2270bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2271 // Parse the linkage.
2272 LocTy LinkageLoc = Lex.getLoc();
2273 unsigned Linkage;
2274
2275 unsigned Visibility, CC, RetAttrs;
2276 PATypeHolder RetType(Type::VoidTy);
2277 LocTy RetTypeLoc = Lex.getLoc();
2278 if (ParseOptionalLinkage(Linkage) ||
2279 ParseOptionalVisibility(Visibility) ||
2280 ParseOptionalCallingConv(CC) ||
2281 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002282 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002283 return true;
2284
2285 // Verify that the linkage is ok.
2286 switch ((GlobalValue::LinkageTypes)Linkage) {
2287 case GlobalValue::ExternalLinkage:
2288 break; // always ok.
2289 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002290 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002291 if (isDefine)
2292 return Error(LinkageLoc, "invalid linkage for function definition");
2293 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002294 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002295 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002296 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002297 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002298 case GlobalValue::LinkOnceAnyLinkage:
2299 case GlobalValue::LinkOnceODRLinkage:
2300 case GlobalValue::WeakAnyLinkage:
2301 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002302 case GlobalValue::DLLExportLinkage:
2303 if (!isDefine)
2304 return Error(LinkageLoc, "invalid linkage for function declaration");
2305 break;
2306 case GlobalValue::AppendingLinkage:
2307 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002308 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002309 return Error(LinkageLoc, "invalid function linkage type");
2310 }
2311
Chris Lattner99bb3152009-01-05 08:00:30 +00002312 if (!FunctionType::isValidReturnType(RetType) ||
2313 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002314 return Error(RetTypeLoc, "invalid function return type");
2315
Chris Lattnerdf986172009-01-02 07:01:27 +00002316 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002317
2318 std::string FunctionName;
2319 if (Lex.getKind() == lltok::GlobalVar) {
2320 FunctionName = Lex.getStrVal();
2321 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2322 unsigned NameID = Lex.getUIntVal();
2323
2324 if (NameID != NumberedVals.size())
2325 return TokError("function expected to be numbered '%" +
2326 utostr(NumberedVals.size()) + "'");
2327 } else {
2328 return TokError("expected function name");
2329 }
2330
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002331 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002332
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002333 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002334 return TokError("expected '(' in function argument list");
2335
2336 std::vector<ArgInfo> ArgList;
2337 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002338 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002339 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002340 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002341 std::string GC;
2342
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002343 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002344 ParseOptionalAttrs(FuncAttrs, 2) ||
2345 (EatIfPresent(lltok::kw_section) &&
2346 ParseStringConstant(Section)) ||
2347 ParseOptionalAlignment(Alignment) ||
2348 (EatIfPresent(lltok::kw_gc) &&
2349 ParseStringConstant(GC)))
2350 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002351
2352 // If the alignment was parsed as an attribute, move to the alignment field.
2353 if (FuncAttrs & Attribute::Alignment) {
2354 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2355 FuncAttrs &= ~Attribute::Alignment;
2356 }
2357
Chris Lattnerdf986172009-01-02 07:01:27 +00002358 // Okay, if we got here, the function is syntactically valid. Convert types
2359 // and do semantic checks.
2360 std::vector<const Type*> ParamTypeList;
2361 SmallVector<AttributeWithIndex, 8> Attrs;
2362 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2363 // attributes.
2364 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2365 if (FuncAttrs & ObsoleteFuncAttrs) {
2366 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2367 FuncAttrs &= ~ObsoleteFuncAttrs;
2368 }
2369
2370 if (RetAttrs != Attribute::None)
2371 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2372
2373 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2374 ParamTypeList.push_back(ArgList[i].Type);
2375 if (ArgList[i].Attrs != Attribute::None)
2376 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2377 }
2378
2379 if (FuncAttrs != Attribute::None)
2380 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2381
2382 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2383
Chris Lattnera9a9e072009-03-09 04:49:14 +00002384 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2385 RetType != Type::VoidTy)
2386 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2387
Owen Andersonfba933c2009-07-01 23:57:11 +00002388 const FunctionType *FT =
2389 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2390 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002391
2392 Fn = 0;
2393 if (!FunctionName.empty()) {
2394 // If this was a definition of a forward reference, remove the definition
2395 // from the forward reference table and fill in the forward ref.
2396 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2397 ForwardRefVals.find(FunctionName);
2398 if (FRVI != ForwardRefVals.end()) {
2399 Fn = M->getFunction(FunctionName);
2400 ForwardRefVals.erase(FRVI);
2401 } else if ((Fn = M->getFunction(FunctionName))) {
2402 // If this function already exists in the symbol table, then it is
2403 // multiply defined. We accept a few cases for old backwards compat.
2404 // FIXME: Remove this stuff for LLVM 3.0.
2405 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2406 (!Fn->isDeclaration() && isDefine)) {
2407 // If the redefinition has different type or different attributes,
2408 // reject it. If both have bodies, reject it.
2409 return Error(NameLoc, "invalid redefinition of function '" +
2410 FunctionName + "'");
2411 } else if (Fn->isDeclaration()) {
2412 // Make sure to strip off any argument names so we can't get conflicts.
2413 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2414 AI != AE; ++AI)
2415 AI->setName("");
2416 }
2417 }
2418
2419 } else if (FunctionName.empty()) {
2420 // If this is a definition of a forward referenced function, make sure the
2421 // types agree.
2422 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2423 = ForwardRefValIDs.find(NumberedVals.size());
2424 if (I != ForwardRefValIDs.end()) {
2425 Fn = cast<Function>(I->second.first);
2426 if (Fn->getType() != PFT)
2427 return Error(NameLoc, "type of definition and forward reference of '@" +
2428 utostr(NumberedVals.size()) +"' disagree");
2429 ForwardRefValIDs.erase(I);
2430 }
2431 }
2432
2433 if (Fn == 0)
2434 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2435 else // Move the forward-reference to the correct spot in the module.
2436 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2437
2438 if (FunctionName.empty())
2439 NumberedVals.push_back(Fn);
2440
2441 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2442 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2443 Fn->setCallingConv(CC);
2444 Fn->setAttributes(PAL);
2445 Fn->setAlignment(Alignment);
2446 Fn->setSection(Section);
2447 if (!GC.empty()) Fn->setGC(GC.c_str());
2448
2449 // Add all of the arguments we parsed to the function.
2450 Function::arg_iterator ArgIt = Fn->arg_begin();
2451 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2452 // If the argument has a name, insert it into the argument symbol table.
2453 if (ArgList[i].Name.empty()) continue;
2454
2455 // Set the name, if it conflicted, it will be auto-renamed.
2456 ArgIt->setName(ArgList[i].Name);
2457
2458 if (ArgIt->getNameStr() != ArgList[i].Name)
2459 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2460 ArgList[i].Name + "'");
2461 }
2462
2463 return false;
2464}
2465
2466
2467/// ParseFunctionBody
2468/// ::= '{' BasicBlock+ '}'
2469/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2470///
2471bool LLParser::ParseFunctionBody(Function &Fn) {
2472 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2473 return TokError("expected '{' in function body");
2474 Lex.Lex(); // eat the {.
2475
2476 PerFunctionState PFS(*this, Fn);
2477
2478 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2479 if (ParseBasicBlock(PFS)) return true;
2480
2481 // Eat the }.
2482 Lex.Lex();
2483
2484 // Verify function is ok.
2485 return PFS.VerifyFunctionComplete();
2486}
2487
2488/// ParseBasicBlock
2489/// ::= LabelStr? Instruction*
2490bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2491 // If this basic block starts out with a name, remember it.
2492 std::string Name;
2493 LocTy NameLoc = Lex.getLoc();
2494 if (Lex.getKind() == lltok::LabelStr) {
2495 Name = Lex.getStrVal();
2496 Lex.Lex();
2497 }
2498
2499 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2500 if (BB == 0) return true;
2501
2502 std::string NameStr;
2503
2504 // Parse the instructions in this block until we get a terminator.
2505 Instruction *Inst;
2506 do {
2507 // This instruction may have three possibilities for a name: a) none
2508 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2509 LocTy NameLoc = Lex.getLoc();
2510 int NameID = -1;
2511 NameStr = "";
2512
2513 if (Lex.getKind() == lltok::LocalVarID) {
2514 NameID = Lex.getUIntVal();
2515 Lex.Lex();
2516 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2517 return true;
2518 } else if (Lex.getKind() == lltok::LocalVar ||
2519 // FIXME: REMOVE IN LLVM 3.0
2520 Lex.getKind() == lltok::StringConstant) {
2521 NameStr = Lex.getStrVal();
2522 Lex.Lex();
2523 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2524 return true;
2525 }
2526
2527 if (ParseInstruction(Inst, BB, PFS)) return true;
2528
2529 BB->getInstList().push_back(Inst);
2530
2531 // Set the name on the instruction.
2532 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2533 } while (!isa<TerminatorInst>(Inst));
2534
2535 return false;
2536}
2537
2538//===----------------------------------------------------------------------===//
2539// Instruction Parsing.
2540//===----------------------------------------------------------------------===//
2541
2542/// ParseInstruction - Parse one of the many different instructions.
2543///
2544bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2545 PerFunctionState &PFS) {
2546 lltok::Kind Token = Lex.getKind();
2547 if (Token == lltok::Eof)
2548 return TokError("found end of file when expecting more instructions");
2549 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002550 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002551 Lex.Lex(); // Eat the keyword.
2552
2553 switch (Token) {
2554 default: return Error(Loc, "expected instruction opcode");
2555 // Terminator Instructions.
2556 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2557 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2558 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2559 case lltok::kw_br: return ParseBr(Inst, PFS);
2560 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2561 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2562 // Binary Operators.
2563 case lltok::kw_add:
2564 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002565 case lltok::kw_mul:
2566 // API compatibility: Accept either integer or floating-point types.
2567 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2568 case lltok::kw_fadd:
2569 case lltok::kw_fsub:
2570 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2571
Chris Lattnerdf986172009-01-02 07:01:27 +00002572 case lltok::kw_udiv:
2573 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002574 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002575 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002576 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002577 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002578 case lltok::kw_shl:
2579 case lltok::kw_lshr:
2580 case lltok::kw_ashr:
2581 case lltok::kw_and:
2582 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002583 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002584 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002585 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002586 // Casts.
2587 case lltok::kw_trunc:
2588 case lltok::kw_zext:
2589 case lltok::kw_sext:
2590 case lltok::kw_fptrunc:
2591 case lltok::kw_fpext:
2592 case lltok::kw_bitcast:
2593 case lltok::kw_uitofp:
2594 case lltok::kw_sitofp:
2595 case lltok::kw_fptoui:
2596 case lltok::kw_fptosi:
2597 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002598 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002599 // Other.
2600 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002601 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002602 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2603 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2604 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2605 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2606 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2607 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2608 // Memory.
2609 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002610 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002611 case lltok::kw_free: return ParseFree(Inst, PFS);
2612 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2613 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2614 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002615 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002616 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002617 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002618 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002619 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002620 return TokError("expected 'load' or 'store'");
Dan Gohman08d012e2009-07-22 22:44:56 +00002621 case lltok::kw_nuw: {
2622 bool AlsoSigned = EatIfPresent(lltok::kw_nsw);
Dan Gohman1224c382009-07-20 21:19:07 +00002623 if (Lex.getKind() == lltok::kw_add ||
2624 Lex.getKind() == lltok::kw_sub ||
2625 Lex.getKind() == lltok::kw_mul) {
2626 Lex.Lex();
2627 KeywordVal = Lex.getUIntVal();
2628 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2629 if (!Result) {
Dan Gohman08d012e2009-07-22 22:44:56 +00002630 cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
2631 if (AlsoSigned)
2632 cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
Dan Gohman1224c382009-07-20 21:19:07 +00002633 }
2634 return Result;
2635 }
2636 return TokError("expected 'add', 'sub', or 'mul'");
2637 }
Dan Gohman08d012e2009-07-22 22:44:56 +00002638 case lltok::kw_nsw: {
2639 bool AlsoUnsigned = EatIfPresent(lltok::kw_nuw);
Dan Gohman1224c382009-07-20 21:19:07 +00002640 if (Lex.getKind() == lltok::kw_add ||
2641 Lex.getKind() == lltok::kw_sub ||
2642 Lex.getKind() == lltok::kw_mul) {
2643 Lex.Lex();
2644 KeywordVal = Lex.getUIntVal();
2645 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2646 if (!Result) {
Dan Gohman08d012e2009-07-22 22:44:56 +00002647 cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
2648 if (AlsoUnsigned)
2649 cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
Dan Gohman1224c382009-07-20 21:19:07 +00002650 }
2651 return Result;
2652 }
2653 return TokError("expected 'add', 'sub', or 'mul'");
2654 }
2655 case lltok::kw_exact:
2656 if (Lex.getKind() == lltok::kw_sdiv) {
2657 Lex.Lex();
2658 KeywordVal = Lex.getUIntVal();
2659 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2660 if (!Result)
2661 cast<SDivOperator>(Inst)->setIsExact(true);
2662 return Result;
2663 }
2664 return TokError("expected 'udiv'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002665 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2666 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2667 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2668 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2669 }
2670}
2671
2672/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2673bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002674 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002675 switch (Lex.getKind()) {
2676 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2677 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2678 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2679 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2680 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2681 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2682 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2683 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2684 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2685 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2686 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2687 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2688 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2689 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2690 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2691 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2692 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2693 }
2694 } else {
2695 switch (Lex.getKind()) {
2696 default: TokError("expected icmp predicate (e.g. 'eq')");
2697 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2698 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2699 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2700 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2701 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2702 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2703 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2704 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2705 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2706 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2707 }
2708 }
2709 Lex.Lex();
2710 return false;
2711}
2712
2713//===----------------------------------------------------------------------===//
2714// Terminator Instructions.
2715//===----------------------------------------------------------------------===//
2716
2717/// ParseRet - Parse a return instruction.
2718/// ::= 'ret' void
2719/// ::= 'ret' TypeAndValue
2720/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2721bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2722 PerFunctionState &PFS) {
2723 PATypeHolder Ty(Type::VoidTy);
Chris Lattnera9a9e072009-03-09 04:49:14 +00002724 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002725
2726 if (Ty == Type::VoidTy) {
2727 Inst = ReturnInst::Create();
2728 return false;
2729 }
2730
2731 Value *RV;
2732 if (ParseValue(Ty, RV, PFS)) return true;
2733
2734 // The normal case is one return value.
2735 if (Lex.getKind() == lltok::comma) {
2736 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2737 // of 'ret {i32,i32} {i32 1, i32 2}'
2738 SmallVector<Value*, 8> RVs;
2739 RVs.push_back(RV);
2740
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002741 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002742 if (ParseTypeAndValue(RV, PFS)) return true;
2743 RVs.push_back(RV);
2744 }
2745
Owen Andersonb43eae72009-07-02 17:04:01 +00002746 RV = Context.getUndef(PFS.getFunction().getReturnType());
Chris Lattnerdf986172009-01-02 07:01:27 +00002747 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2748 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2749 BB->getInstList().push_back(I);
2750 RV = I;
2751 }
2752 }
2753 Inst = ReturnInst::Create(RV);
2754 return false;
2755}
2756
2757
2758/// ParseBr
2759/// ::= 'br' TypeAndValue
2760/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2761bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2762 LocTy Loc, Loc2;
2763 Value *Op0, *Op1, *Op2;
2764 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2765
2766 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2767 Inst = BranchInst::Create(BB);
2768 return false;
2769 }
2770
2771 if (Op0->getType() != Type::Int1Ty)
2772 return Error(Loc, "branch condition must have 'i1' type");
2773
2774 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2775 ParseTypeAndValue(Op1, Loc, PFS) ||
2776 ParseToken(lltok::comma, "expected ',' after true destination") ||
2777 ParseTypeAndValue(Op2, Loc2, PFS))
2778 return true;
2779
2780 if (!isa<BasicBlock>(Op1))
2781 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002782 if (!isa<BasicBlock>(Op2))
2783 return Error(Loc2, "true destination of branch must be a basic block");
2784
2785 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2786 return false;
2787}
2788
2789/// ParseSwitch
2790/// Instruction
2791/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2792/// JumpTable
2793/// ::= (TypeAndValue ',' TypeAndValue)*
2794bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2795 LocTy CondLoc, BBLoc;
2796 Value *Cond, *DefaultBB;
2797 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2798 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2799 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2800 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2801 return true;
2802
2803 if (!isa<IntegerType>(Cond->getType()))
2804 return Error(CondLoc, "switch condition must have integer type");
2805 if (!isa<BasicBlock>(DefaultBB))
2806 return Error(BBLoc, "default destination must be a basic block");
2807
2808 // Parse the jump table pairs.
2809 SmallPtrSet<Value*, 32> SeenCases;
2810 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2811 while (Lex.getKind() != lltok::rsquare) {
2812 Value *Constant, *DestBB;
2813
2814 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2815 ParseToken(lltok::comma, "expected ',' after case value") ||
2816 ParseTypeAndValue(DestBB, BBLoc, PFS))
2817 return true;
2818
2819 if (!SeenCases.insert(Constant))
2820 return Error(CondLoc, "duplicate case value in switch");
2821 if (!isa<ConstantInt>(Constant))
2822 return Error(CondLoc, "case value is not a constant integer");
2823 if (!isa<BasicBlock>(DestBB))
2824 return Error(BBLoc, "case destination is not a basic block");
2825
2826 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2827 cast<BasicBlock>(DestBB)));
2828 }
2829
2830 Lex.Lex(); // Eat the ']'.
2831
2832 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2833 Table.size());
2834 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2835 SI->addCase(Table[i].first, Table[i].second);
2836 Inst = SI;
2837 return false;
2838}
2839
2840/// ParseInvoke
2841/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2842/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2843bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2844 LocTy CallLoc = Lex.getLoc();
2845 unsigned CC, RetAttrs, FnAttrs;
2846 PATypeHolder RetType(Type::VoidTy);
2847 LocTy RetTypeLoc;
2848 ValID CalleeID;
2849 SmallVector<ParamInfo, 16> ArgList;
2850
2851 Value *NormalBB, *UnwindBB;
2852 if (ParseOptionalCallingConv(CC) ||
2853 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002854 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002855 ParseValID(CalleeID) ||
2856 ParseParameterList(ArgList, PFS) ||
2857 ParseOptionalAttrs(FnAttrs, 2) ||
2858 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2859 ParseTypeAndValue(NormalBB, PFS) ||
2860 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2861 ParseTypeAndValue(UnwindBB, PFS))
2862 return true;
2863
2864 if (!isa<BasicBlock>(NormalBB))
2865 return Error(CallLoc, "normal destination is not a basic block");
2866 if (!isa<BasicBlock>(UnwindBB))
2867 return Error(CallLoc, "unwind destination is not a basic block");
2868
2869 // If RetType is a non-function pointer type, then this is the short syntax
2870 // for the call, which means that RetType is just the return type. Infer the
2871 // rest of the function argument types from the arguments that are present.
2872 const PointerType *PFTy = 0;
2873 const FunctionType *Ty = 0;
2874 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2875 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2876 // Pull out the types of all of the arguments...
2877 std::vector<const Type*> ParamTypes;
2878 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2879 ParamTypes.push_back(ArgList[i].V->getType());
2880
2881 if (!FunctionType::isValidReturnType(RetType))
2882 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2883
Owen Andersonfba933c2009-07-01 23:57:11 +00002884 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2885 PFTy = Context.getPointerTypeUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002886 }
2887
2888 // Look up the callee.
2889 Value *Callee;
2890 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2891
2892 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2893 // function attributes.
2894 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2895 if (FnAttrs & ObsoleteFuncAttrs) {
2896 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2897 FnAttrs &= ~ObsoleteFuncAttrs;
2898 }
2899
2900 // Set up the Attributes for the function.
2901 SmallVector<AttributeWithIndex, 8> Attrs;
2902 if (RetAttrs != Attribute::None)
2903 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2904
2905 SmallVector<Value*, 8> Args;
2906
2907 // Loop through FunctionType's arguments and ensure they are specified
2908 // correctly. Also, gather any parameter attributes.
2909 FunctionType::param_iterator I = Ty->param_begin();
2910 FunctionType::param_iterator E = Ty->param_end();
2911 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2912 const Type *ExpectedTy = 0;
2913 if (I != E) {
2914 ExpectedTy = *I++;
2915 } else if (!Ty->isVarArg()) {
2916 return Error(ArgList[i].Loc, "too many arguments specified");
2917 }
2918
2919 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2920 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2921 ExpectedTy->getDescription() + "'");
2922 Args.push_back(ArgList[i].V);
2923 if (ArgList[i].Attrs != Attribute::None)
2924 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2925 }
2926
2927 if (I != E)
2928 return Error(CallLoc, "not enough parameters specified for call");
2929
2930 if (FnAttrs != Attribute::None)
2931 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2932
2933 // Finish off the Attributes and check them
2934 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2935
2936 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2937 cast<BasicBlock>(UnwindBB),
2938 Args.begin(), Args.end());
2939 II->setCallingConv(CC);
2940 II->setAttributes(PAL);
2941 Inst = II;
2942 return false;
2943}
2944
2945
2946
2947//===----------------------------------------------------------------------===//
2948// Binary Operators.
2949//===----------------------------------------------------------------------===//
2950
2951/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002952/// ::= ArithmeticOps TypeAndValue ',' Value
2953///
2954/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2955/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002956bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002957 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002958 LocTy Loc; Value *LHS, *RHS;
2959 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2960 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2961 ParseValue(LHS->getType(), RHS, PFS))
2962 return true;
2963
Chris Lattnere914b592009-01-05 08:24:46 +00002964 bool Valid;
2965 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002966 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00002967 case 0: // int or FP.
2968 Valid = LHS->getType()->isIntOrIntVector() ||
2969 LHS->getType()->isFPOrFPVector();
2970 break;
2971 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2972 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2973 }
2974
2975 if (!Valid)
2976 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002977
2978 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2979 return false;
2980}
2981
2982/// ParseLogical
2983/// ::= ArithmeticOps TypeAndValue ',' Value {
2984bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2985 unsigned Opc) {
2986 LocTy Loc; Value *LHS, *RHS;
2987 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2988 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2989 ParseValue(LHS->getType(), RHS, PFS))
2990 return true;
2991
2992 if (!LHS->getType()->isIntOrIntVector())
2993 return Error(Loc,"instruction requires integer or integer vector operands");
2994
2995 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2996 return false;
2997}
2998
2999
3000/// ParseCompare
3001/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3002/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003003bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3004 unsigned Opc) {
3005 // Parse the integer/fp comparison predicate.
3006 LocTy Loc;
3007 unsigned Pred;
3008 Value *LHS, *RHS;
3009 if (ParseCmpPredicate(Pred, Opc) ||
3010 ParseTypeAndValue(LHS, Loc, PFS) ||
3011 ParseToken(lltok::comma, "expected ',' after compare value") ||
3012 ParseValue(LHS->getType(), RHS, PFS))
3013 return true;
3014
3015 if (Opc == Instruction::FCmp) {
3016 if (!LHS->getType()->isFPOrFPVector())
3017 return Error(Loc, "fcmp requires floating point operands");
Owen Anderson333c4002009-07-09 23:48:35 +00003018 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003019 } else {
3020 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00003021 if (!LHS->getType()->isIntOrIntVector() &&
3022 !isa<PointerType>(LHS->getType()))
3023 return Error(Loc, "icmp requires integer operands");
Owen Anderson333c4002009-07-09 23:48:35 +00003024 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003025 }
3026 return false;
3027}
3028
3029//===----------------------------------------------------------------------===//
3030// Other Instructions.
3031//===----------------------------------------------------------------------===//
3032
3033
3034/// ParseCast
3035/// ::= CastOpc TypeAndValue 'to' Type
3036bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3037 unsigned Opc) {
3038 LocTy Loc; Value *Op;
3039 PATypeHolder DestTy(Type::VoidTy);
3040 if (ParseTypeAndValue(Op, Loc, PFS) ||
3041 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3042 ParseType(DestTy))
3043 return true;
3044
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003045 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3046 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003047 return Error(Loc, "invalid cast opcode for cast from '" +
3048 Op->getType()->getDescription() + "' to '" +
3049 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003050 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003051 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3052 return false;
3053}
3054
3055/// ParseSelect
3056/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3057bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3058 LocTy Loc;
3059 Value *Op0, *Op1, *Op2;
3060 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3061 ParseToken(lltok::comma, "expected ',' after select condition") ||
3062 ParseTypeAndValue(Op1, PFS) ||
3063 ParseToken(lltok::comma, "expected ',' after select value") ||
3064 ParseTypeAndValue(Op2, PFS))
3065 return true;
3066
3067 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3068 return Error(Loc, Reason);
3069
3070 Inst = SelectInst::Create(Op0, Op1, Op2);
3071 return false;
3072}
3073
Chris Lattner0088a5c2009-01-05 08:18:44 +00003074/// ParseVA_Arg
3075/// ::= 'va_arg' TypeAndValue ',' Type
3076bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003077 Value *Op;
3078 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003079 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003080 if (ParseTypeAndValue(Op, PFS) ||
3081 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003082 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003083 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003084
3085 if (!EltTy->isFirstClassType())
3086 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003087
3088 Inst = new VAArgInst(Op, EltTy);
3089 return false;
3090}
3091
3092/// ParseExtractElement
3093/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3094bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3095 LocTy Loc;
3096 Value *Op0, *Op1;
3097 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3098 ParseToken(lltok::comma, "expected ',' after extract value") ||
3099 ParseTypeAndValue(Op1, PFS))
3100 return true;
3101
3102 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3103 return Error(Loc, "invalid extractelement operands");
3104
3105 Inst = new ExtractElementInst(Op0, Op1);
3106 return false;
3107}
3108
3109/// ParseInsertElement
3110/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3111bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3112 LocTy Loc;
3113 Value *Op0, *Op1, *Op2;
3114 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3115 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3116 ParseTypeAndValue(Op1, PFS) ||
3117 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3118 ParseTypeAndValue(Op2, PFS))
3119 return true;
3120
3121 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003122 return Error(Loc, "invalid insertelement operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00003123
3124 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3125 return false;
3126}
3127
3128/// ParseShuffleVector
3129/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3130bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3131 LocTy Loc;
3132 Value *Op0, *Op1, *Op2;
3133 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3134 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3135 ParseTypeAndValue(Op1, PFS) ||
3136 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3137 ParseTypeAndValue(Op2, PFS))
3138 return true;
3139
3140 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3141 return Error(Loc, "invalid extractelement operands");
3142
3143 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3144 return false;
3145}
3146
3147/// ParsePHI
3148/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3149bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3150 PATypeHolder Ty(Type::VoidTy);
3151 Value *Op0, *Op1;
3152 LocTy TypeLoc = Lex.getLoc();
3153
3154 if (ParseType(Ty) ||
3155 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3156 ParseValue(Ty, Op0, PFS) ||
3157 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3158 ParseValue(Type::LabelTy, Op1, PFS) ||
3159 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3160 return true;
3161
3162 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3163 while (1) {
3164 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3165
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003166 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003167 break;
3168
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003169 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003170 ParseValue(Ty, Op0, PFS) ||
3171 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3172 ParseValue(Type::LabelTy, Op1, PFS) ||
3173 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3174 return true;
3175 }
3176
3177 if (!Ty->isFirstClassType())
3178 return Error(TypeLoc, "phi node must have first class type");
3179
3180 PHINode *PN = PHINode::Create(Ty);
3181 PN->reserveOperandSpace(PHIVals.size());
3182 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3183 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3184 Inst = PN;
3185 return false;
3186}
3187
3188/// ParseCall
3189/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3190/// ParameterList OptionalAttrs
3191bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3192 bool isTail) {
3193 unsigned CC, RetAttrs, FnAttrs;
3194 PATypeHolder RetType(Type::VoidTy);
3195 LocTy RetTypeLoc;
3196 ValID CalleeID;
3197 SmallVector<ParamInfo, 16> ArgList;
3198 LocTy CallLoc = Lex.getLoc();
3199
3200 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3201 ParseOptionalCallingConv(CC) ||
3202 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003203 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003204 ParseValID(CalleeID) ||
3205 ParseParameterList(ArgList, PFS) ||
3206 ParseOptionalAttrs(FnAttrs, 2))
3207 return true;
3208
3209 // If RetType is a non-function pointer type, then this is the short syntax
3210 // for the call, which means that RetType is just the return type. Infer the
3211 // rest of the function argument types from the arguments that are present.
3212 const PointerType *PFTy = 0;
3213 const FunctionType *Ty = 0;
3214 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3215 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3216 // Pull out the types of all of the arguments...
3217 std::vector<const Type*> ParamTypes;
3218 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3219 ParamTypes.push_back(ArgList[i].V->getType());
3220
3221 if (!FunctionType::isValidReturnType(RetType))
3222 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3223
Owen Andersonfba933c2009-07-01 23:57:11 +00003224 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3225 PFTy = Context.getPointerTypeUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003226 }
3227
3228 // Look up the callee.
3229 Value *Callee;
3230 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3231
Chris Lattnerdf986172009-01-02 07:01:27 +00003232 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3233 // function attributes.
3234 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3235 if (FnAttrs & ObsoleteFuncAttrs) {
3236 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3237 FnAttrs &= ~ObsoleteFuncAttrs;
3238 }
3239
3240 // Set up the Attributes for the function.
3241 SmallVector<AttributeWithIndex, 8> Attrs;
3242 if (RetAttrs != Attribute::None)
3243 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3244
3245 SmallVector<Value*, 8> Args;
3246
3247 // Loop through FunctionType's arguments and ensure they are specified
3248 // correctly. Also, gather any parameter attributes.
3249 FunctionType::param_iterator I = Ty->param_begin();
3250 FunctionType::param_iterator E = Ty->param_end();
3251 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3252 const Type *ExpectedTy = 0;
3253 if (I != E) {
3254 ExpectedTy = *I++;
3255 } else if (!Ty->isVarArg()) {
3256 return Error(ArgList[i].Loc, "too many arguments specified");
3257 }
3258
3259 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3260 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3261 ExpectedTy->getDescription() + "'");
3262 Args.push_back(ArgList[i].V);
3263 if (ArgList[i].Attrs != Attribute::None)
3264 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3265 }
3266
3267 if (I != E)
3268 return Error(CallLoc, "not enough parameters specified for call");
3269
3270 if (FnAttrs != Attribute::None)
3271 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3272
3273 // Finish off the Attributes and check them
3274 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3275
3276 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3277 CI->setTailCall(isTail);
3278 CI->setCallingConv(CC);
3279 CI->setAttributes(PAL);
3280 Inst = CI;
3281 return false;
3282}
3283
3284//===----------------------------------------------------------------------===//
3285// Memory Instructions.
3286//===----------------------------------------------------------------------===//
3287
3288/// ParseAlloc
3289/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3290/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3291bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3292 unsigned Opc) {
3293 PATypeHolder Ty(Type::VoidTy);
3294 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003295 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003296 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003297 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003298
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003299 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003300 if (Lex.getKind() == lltok::kw_align) {
3301 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003302 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3303 ParseOptionalCommaAlignment(Alignment)) {
3304 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003305 }
3306 }
3307
3308 if (Size && Size->getType() != Type::Int32Ty)
3309 return Error(SizeLoc, "element count must be i32");
3310
3311 if (Opc == Instruction::Malloc)
Owen Anderson50dead02009-07-15 23:53:25 +00003312 Inst = new MallocInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003313 else
Owen Anderson50dead02009-07-15 23:53:25 +00003314 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003315 return false;
3316}
3317
3318/// ParseFree
3319/// ::= 'free' TypeAndValue
3320bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3321 Value *Val; LocTy Loc;
3322 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3323 if (!isa<PointerType>(Val->getType()))
3324 return Error(Loc, "operand to free must be a pointer");
3325 Inst = new FreeInst(Val);
3326 return false;
3327}
3328
3329/// ParseLoad
Dan Gohmana119de82009-06-14 23:30:43 +00003330/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003331bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3332 bool isVolatile) {
3333 Value *Val; LocTy Loc;
3334 unsigned Alignment;
3335 if (ParseTypeAndValue(Val, Loc, PFS) ||
3336 ParseOptionalCommaAlignment(Alignment))
3337 return true;
3338
3339 if (!isa<PointerType>(Val->getType()) ||
3340 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3341 return Error(Loc, "load operand must be a pointer to a first class type");
3342
3343 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3344 return false;
3345}
3346
3347/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003348/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003349bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3350 bool isVolatile) {
3351 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3352 unsigned Alignment;
3353 if (ParseTypeAndValue(Val, Loc, PFS) ||
3354 ParseToken(lltok::comma, "expected ',' after store operand") ||
3355 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3356 ParseOptionalCommaAlignment(Alignment))
3357 return true;
3358
3359 if (!isa<PointerType>(Ptr->getType()))
3360 return Error(PtrLoc, "store operand must be a pointer");
3361 if (!Val->getType()->isFirstClassType())
3362 return Error(Loc, "store operand must be a first class value");
3363 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3364 return Error(Loc, "stored value and pointer type do not match");
3365
3366 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3367 return false;
3368}
3369
3370/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003371/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003372/// FIXME: Remove support for getresult in LLVM 3.0
3373bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3374 Value *Val; LocTy ValLoc, EltLoc;
3375 unsigned Element;
3376 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3377 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003378 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003379 return true;
3380
3381 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3382 return Error(ValLoc, "getresult inst requires an aggregate operand");
3383 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3384 return Error(EltLoc, "invalid getresult index for value");
3385 Inst = ExtractValueInst::Create(Val, Element);
3386 return false;
3387}
3388
3389/// ParseGetElementPtr
3390/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3391bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3392 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003393 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003394
3395 if (!isa<PointerType>(Ptr->getType()))
3396 return Error(Loc, "base of getelementptr must be a pointer");
3397
3398 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003399 while (EatIfPresent(lltok::comma)) {
3400 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003401 if (!isa<IntegerType>(Val->getType()))
3402 return Error(EltLoc, "getelementptr index must be an integer");
3403 Indices.push_back(Val);
3404 }
3405
3406 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3407 Indices.begin(), Indices.end()))
3408 return Error(Loc, "invalid getelementptr indices");
3409 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3410 return false;
3411}
3412
3413/// ParseExtractValue
3414/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3415bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3416 Value *Val; LocTy Loc;
3417 SmallVector<unsigned, 4> Indices;
3418 if (ParseTypeAndValue(Val, Loc, PFS) ||
3419 ParseIndexList(Indices))
3420 return true;
3421
3422 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3423 return Error(Loc, "extractvalue operand must be array or struct");
3424
3425 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3426 Indices.end()))
3427 return Error(Loc, "invalid indices for extractvalue");
3428 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3429 return false;
3430}
3431
3432/// ParseInsertValue
3433/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3434bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3435 Value *Val0, *Val1; LocTy Loc0, Loc1;
3436 SmallVector<unsigned, 4> Indices;
3437 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3438 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3439 ParseTypeAndValue(Val1, Loc1, PFS) ||
3440 ParseIndexList(Indices))
3441 return true;
3442
3443 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3444 return Error(Loc0, "extractvalue operand must be array or struct");
3445
3446 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3447 Indices.end()))
3448 return Error(Loc0, "invalid indices for insertvalue");
3449 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3450 return false;
3451}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003452
3453//===----------------------------------------------------------------------===//
3454// Embedded metadata.
3455//===----------------------------------------------------------------------===//
3456
3457/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003458/// ::= Element (',' Element)*
3459/// Element
3460/// ::= 'null' | TypeAndValue
3461bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003462 assert(Lex.getKind() == lltok::lbrace);
3463 Lex.Lex();
3464 do {
Nick Lewyckycb337992009-05-10 20:57:05 +00003465 Value *V;
3466 if (Lex.getKind() == lltok::kw_null) {
3467 Lex.Lex();
3468 V = 0;
3469 } else {
Devang Patele54abc92009-07-22 17:43:22 +00003470 PATypeHolder Ty(Type::VoidTy);
3471 if (ParseType(Ty)) return true;
3472 if (Lex.getKind() == lltok::Metadata) {
3473 Lex.Lex();
Devang Patel104cf9e2009-07-23 01:07:34 +00003474 MetadataBase *Node = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003475 if (!ParseMDNode(Node))
3476 V = Node;
3477 else {
3478 MetadataBase *MDS = 0;
3479 if (ParseMDString(MDS)) return true;
3480 V = MDS;
3481 }
3482 } else {
3483 Constant *C;
3484 if (ParseGlobalValue(Ty, C)) return true;
3485 V = C;
3486 }
Nick Lewyckycb337992009-05-10 20:57:05 +00003487 }
3488 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003489 } while (EatIfPresent(lltok::comma));
3490
3491 return false;
3492}