blob: cf16e42b6a85a6e26c6a082229e5e5b3b14ecbda [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"
Devang Patel0a9f7b92009-07-28 21:49:47 +000022#include "llvm/Metadata.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;
Daniel Dunbara279bc32009-09-20 02:20:51 +000048
Chris Lattnerdf986172009-01-02 07:01:27 +000049 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() {
Victor Hernandez68afa542009-10-21 19:11:40 +000072 // Update auto-upgraded malloc calls to "malloc".
Chris Lattnercf4d2f12009-10-18 05:09:15 +000073 // FIXME: Remove in LLVM 3.0.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000074 if (MallocF) {
75 MallocF->setName("malloc");
76 // If setName() does not set the name to "malloc", then there is already a
77 // declaration of "malloc". In that case, iterate over all calls to MallocF
78 // and get them to call the declared "malloc" instead.
79 if (MallocF->getName() != "malloc") {
Victor Hernandez68afa542009-10-21 19:11:40 +000080 Constant* RealMallocF = M->getFunction("malloc");
81 if (RealMallocF->getType() != MallocF->getType())
82 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
83 MallocF->replaceAllUsesWith(RealMallocF);
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000084 MallocF->eraseFromParent();
85 MallocF = NULL;
86 }
87 }
88
Chris Lattnerdf986172009-01-02 07:01:27 +000089 if (!ForwardRefTypes.empty())
90 return Error(ForwardRefTypes.begin()->second.second,
91 "use of undefined type named '" +
92 ForwardRefTypes.begin()->first + "'");
93 if (!ForwardRefTypeIDs.empty())
94 return Error(ForwardRefTypeIDs.begin()->second.second,
95 "use of undefined type '%" +
96 utostr(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +000097
Chris Lattnerdf986172009-01-02 07:01:27 +000098 if (!ForwardRefVals.empty())
99 return Error(ForwardRefVals.begin()->second.second,
100 "use of undefined value '@" + ForwardRefVals.begin()->first +
101 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000102
Chris Lattnerdf986172009-01-02 07:01:27 +0000103 if (!ForwardRefValIDs.empty())
104 return Error(ForwardRefValIDs.begin()->second.second,
105 "use of undefined value '@" +
106 utostr(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000107
Devang Patel1c7eea62009-07-08 19:23:54 +0000108 if (!ForwardRefMDNodes.empty())
109 return Error(ForwardRefMDNodes.begin()->second.second,
110 "use of undefined metadata '!" +
111 utostr(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000112
Devang Patel1c7eea62009-07-08 19:23:54 +0000113
Chris Lattnerdf986172009-01-02 07:01:27 +0000114 // Look for intrinsic functions and CallInst that need to be upgraded
115 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
116 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000117
Devang Patele4b27562009-08-28 23:24:31 +0000118 // Check debug info intrinsics.
119 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000120 return false;
121}
122
123//===----------------------------------------------------------------------===//
124// Top-Level Entities
125//===----------------------------------------------------------------------===//
126
127bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000128 while (1) {
129 switch (Lex.getKind()) {
130 default: return TokError("expected top-level entity");
131 case lltok::Eof: return false;
132 //case lltok::kw_define:
133 case lltok::kw_declare: if (ParseDeclare()) return true; break;
134 case lltok::kw_define: if (ParseDefine()) return true; break;
135 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
136 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
137 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
138 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000139 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000140 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
141 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000142 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000143 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Devang Patel923078c2009-07-01 19:21:12 +0000144 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
Devang Patel0475c912009-09-29 00:01:14 +0000145 case lltok::NamedOrCustomMD: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000146
147 // The Global variable production with no name can have many different
148 // optional leading prefixes, the production is:
149 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
150 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000151 case lltok::kw_private : // OptionalLinkage
152 case lltok::kw_linker_private: // OptionalLinkage
153 case lltok::kw_internal: // OptionalLinkage
154 case lltok::kw_weak: // OptionalLinkage
155 case lltok::kw_weak_odr: // OptionalLinkage
156 case lltok::kw_linkonce: // OptionalLinkage
157 case lltok::kw_linkonce_odr: // OptionalLinkage
158 case lltok::kw_appending: // OptionalLinkage
159 case lltok::kw_dllexport: // OptionalLinkage
160 case lltok::kw_common: // OptionalLinkage
161 case lltok::kw_dllimport: // OptionalLinkage
162 case lltok::kw_extern_weak: // OptionalLinkage
163 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000164 unsigned Linkage, Visibility;
165 if (ParseOptionalLinkage(Linkage) ||
166 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000167 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000168 return true;
169 break;
170 }
171 case lltok::kw_default: // OptionalVisibility
172 case lltok::kw_hidden: // OptionalVisibility
173 case lltok::kw_protected: { // OptionalVisibility
174 unsigned Visibility;
175 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000176 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000177 return true;
178 break;
179 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000180
Chris Lattnerdf986172009-01-02 07:01:27 +0000181 case lltok::kw_thread_local: // OptionalThreadLocal
182 case lltok::kw_addrspace: // OptionalAddrSpace
183 case lltok::kw_constant: // GlobalType
184 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000185 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000186 break;
187 }
188 }
189}
190
191
192/// toplevelentity
193/// ::= 'module' 'asm' STRINGCONSTANT
194bool LLParser::ParseModuleAsm() {
195 assert(Lex.getKind() == lltok::kw_module);
196 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000197
198 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000199 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
200 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000201
Chris Lattnerdf986172009-01-02 07:01:27 +0000202 const std::string &AsmSoFar = M->getModuleInlineAsm();
203 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000204 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000205 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000206 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000207 return false;
208}
209
210/// toplevelentity
211/// ::= 'target' 'triple' '=' STRINGCONSTANT
212/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
213bool LLParser::ParseTargetDefinition() {
214 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000215 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000216 switch (Lex.Lex()) {
217 default: return TokError("unknown target property");
218 case lltok::kw_triple:
219 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000220 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
221 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000222 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000223 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000224 return false;
225 case lltok::kw_datalayout:
226 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000227 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
228 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000229 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000230 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000231 return false;
232 }
233}
234
235/// toplevelentity
236/// ::= 'deplibs' '=' '[' ']'
237/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
238bool LLParser::ParseDepLibs() {
239 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000240 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000241 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
242 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
243 return true;
244
245 if (EatIfPresent(lltok::rsquare))
246 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000247
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000248 std::string Str;
249 if (ParseStringConstant(Str)) return true;
250 M->addLibrary(Str);
251
252 while (EatIfPresent(lltok::comma)) {
253 if (ParseStringConstant(Str)) return true;
254 M->addLibrary(Str);
255 }
256
257 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000258}
259
Dan Gohman3845e502009-08-12 23:32:33 +0000260/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000261/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000262/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000263bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000264 unsigned TypeID = NumberedTypes.size();
265
266 // Handle the LocalVarID form.
267 if (Lex.getKind() == lltok::LocalVarID) {
268 if (Lex.getUIntVal() != TypeID)
269 return Error(Lex.getLoc(), "type expected to be numbered '%" +
270 utostr(TypeID) + "'");
271 Lex.Lex(); // eat LocalVarID;
272
273 if (ParseToken(lltok::equal, "expected '=' after name"))
274 return true;
275 }
276
Chris Lattnerdf986172009-01-02 07:01:27 +0000277 assert(Lex.getKind() == lltok::kw_type);
278 LocTy TypeLoc = Lex.getLoc();
279 Lex.Lex(); // eat kw_type
280
Owen Anderson1d0be152009-08-13 21:58:54 +0000281 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000282 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000283
Chris Lattnerdf986172009-01-02 07:01:27 +0000284 // See if this type was previously referenced.
285 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
286 FI = ForwardRefTypeIDs.find(TypeID);
287 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000288 if (FI->second.first.get() == Ty)
289 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000290
Chris Lattnerdf986172009-01-02 07:01:27 +0000291 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
292 Ty = FI->second.first.get();
293 ForwardRefTypeIDs.erase(FI);
294 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000295
Chris Lattnerdf986172009-01-02 07:01:27 +0000296 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000297
Chris Lattnerdf986172009-01-02 07:01:27 +0000298 return false;
299}
300
301/// toplevelentity
302/// ::= LocalVar '=' 'type' type
303bool LLParser::ParseNamedType() {
304 std::string Name = Lex.getStrVal();
305 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000306 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000307
Owen Anderson1d0be152009-08-13 21:58:54 +0000308 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000309
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000310 if (ParseToken(lltok::equal, "expected '=' after name") ||
311 ParseToken(lltok::kw_type, "expected 'type' after name") ||
312 ParseType(Ty))
313 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000314
Chris Lattnerdf986172009-01-02 07:01:27 +0000315 // Set the type name, checking for conflicts as we do so.
316 bool AlreadyExists = M->addTypeName(Name, Ty);
317 if (!AlreadyExists) return false;
318
319 // See if this type is a forward reference. We need to eagerly resolve
320 // types to allow recursive type redefinitions below.
321 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
322 FI = ForwardRefTypes.find(Name);
323 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000324 if (FI->second.first.get() == Ty)
325 return Error(NameLoc, "self referential type is invalid");
326
Chris Lattnerdf986172009-01-02 07:01:27 +0000327 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
328 Ty = FI->second.first.get();
329 ForwardRefTypes.erase(FI);
330 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000331
Chris Lattnerdf986172009-01-02 07:01:27 +0000332 // Inserting a name that is already defined, get the existing name.
333 const Type *Existing = M->getTypeByName(Name);
334 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000335
Chris Lattnerdf986172009-01-02 07:01:27 +0000336 // Otherwise, this is an attempt to redefine a type. That's okay if
337 // the redefinition is identical to the original.
338 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
339 if (Existing == Ty) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000340
Chris Lattnerdf986172009-01-02 07:01:27 +0000341 // Any other kind of (non-equivalent) redefinition is an error.
342 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
343 Ty->getDescription() + "'");
344}
345
346
347/// toplevelentity
348/// ::= 'declare' FunctionHeader
349bool LLParser::ParseDeclare() {
350 assert(Lex.getKind() == lltok::kw_declare);
351 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000352
Chris Lattnerdf986172009-01-02 07:01:27 +0000353 Function *F;
354 return ParseFunctionHeader(F, false);
355}
356
357/// toplevelentity
358/// ::= 'define' FunctionHeader '{' ...
359bool LLParser::ParseDefine() {
360 assert(Lex.getKind() == lltok::kw_define);
361 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000362
Chris Lattnerdf986172009-01-02 07:01:27 +0000363 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000364 return ParseFunctionHeader(F, true) ||
365 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000366}
367
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000368/// ParseGlobalType
369/// ::= 'constant'
370/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000371bool LLParser::ParseGlobalType(bool &IsConstant) {
372 if (Lex.getKind() == lltok::kw_constant)
373 IsConstant = true;
374 else if (Lex.getKind() == lltok::kw_global)
375 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000376 else {
377 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000378 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000379 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000380 Lex.Lex();
381 return false;
382}
383
Dan Gohman3845e502009-08-12 23:32:33 +0000384/// ParseUnnamedGlobal:
385/// OptionalVisibility ALIAS ...
386/// OptionalLinkage OptionalVisibility ... -> global variable
387/// GlobalID '=' OptionalVisibility ALIAS ...
388/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
389bool LLParser::ParseUnnamedGlobal() {
390 unsigned VarID = NumberedVals.size();
391 std::string Name;
392 LocTy NameLoc = Lex.getLoc();
393
394 // Handle the GlobalID form.
395 if (Lex.getKind() == lltok::GlobalID) {
396 if (Lex.getUIntVal() != VarID)
397 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
398 utostr(VarID) + "'");
399 Lex.Lex(); // eat GlobalID;
400
401 if (ParseToken(lltok::equal, "expected '=' after name"))
402 return true;
403 }
404
405 bool HasLinkage;
406 unsigned Linkage, Visibility;
407 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
408 ParseOptionalVisibility(Visibility))
409 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000410
Dan Gohman3845e502009-08-12 23:32:33 +0000411 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
412 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
413 return ParseAlias(Name, NameLoc, Visibility);
414}
415
Chris Lattnerdf986172009-01-02 07:01:27 +0000416/// ParseNamedGlobal:
417/// GlobalVar '=' OptionalVisibility ALIAS ...
418/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
419bool LLParser::ParseNamedGlobal() {
420 assert(Lex.getKind() == lltok::GlobalVar);
421 LocTy NameLoc = Lex.getLoc();
422 std::string Name = Lex.getStrVal();
423 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000424
Chris Lattnerdf986172009-01-02 07:01:27 +0000425 bool HasLinkage;
426 unsigned Linkage, Visibility;
427 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
428 ParseOptionalLinkage(Linkage, HasLinkage) ||
429 ParseOptionalVisibility(Visibility))
430 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000431
Chris Lattnerdf986172009-01-02 07:01:27 +0000432 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
433 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
434 return ParseAlias(Name, NameLoc, Visibility);
435}
436
Devang Patel256be962009-07-20 19:00:08 +0000437// MDString:
438// ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +0000439bool LLParser::ParseMDString(MetadataBase *&MDS) {
Devang Patel256be962009-07-20 19:00:08 +0000440 std::string Str;
441 if (ParseStringConstant(Str)) return true;
Owen Anderson647e3012009-07-31 21:35:40 +0000442 MDS = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000443 return false;
444}
445
446// MDNode:
447// ::= '!' MDNodeNumber
Devang Patel104cf9e2009-07-23 01:07:34 +0000448bool LLParser::ParseMDNode(MetadataBase *&Node) {
Devang Patel256be962009-07-20 19:00:08 +0000449 // !{ ..., !42, ... }
450 unsigned MID = 0;
451 if (ParseUInt32(MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000452
Devang Patel256be962009-07-20 19:00:08 +0000453 // Check existing MDNode.
Devang Patel104cf9e2009-07-23 01:07:34 +0000454 std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
Devang Patel256be962009-07-20 19:00:08 +0000455 if (I != MetadataCache.end()) {
456 Node = I->second;
457 return false;
458 }
459
460 // Check known forward references.
Devang Patel104cf9e2009-07-23 01:07:34 +0000461 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel256be962009-07-20 19:00:08 +0000462 FI = ForwardRefMDNodes.find(MID);
463 if (FI != ForwardRefMDNodes.end()) {
464 Node = FI->second.first;
465 return false;
466 }
467
468 // Create MDNode forward reference
469 SmallVector<Value *, 1> Elts;
470 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Owen Anderson647e3012009-07-31 21:35:40 +0000471 Elts.push_back(MDString::get(Context, FwdRefName));
472 MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel256be962009-07-20 19:00:08 +0000473 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
474 Node = FwdNode;
475 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000476}
Devang Patel256be962009-07-20 19:00:08 +0000477
Devang Pateleff2ab62009-07-29 00:34:02 +0000478///ParseNamedMetadata:
479/// !foo = !{ !1, !2 }
480bool LLParser::ParseNamedMetadata() {
Devang Patel0475c912009-09-29 00:01:14 +0000481 assert(Lex.getKind() == lltok::NamedOrCustomMD);
Devang Pateleff2ab62009-07-29 00:34:02 +0000482 Lex.Lex();
483 std::string Name = Lex.getStrVal();
484
485 if (ParseToken(lltok::equal, "expected '=' here"))
486 return true;
487
488 if (Lex.getKind() != lltok::Metadata)
489 return TokError("Expected '!' here");
490 Lex.Lex();
491
492 if (Lex.getKind() != lltok::lbrace)
493 return TokError("Expected '{' here");
494 Lex.Lex();
495 SmallVector<MetadataBase *, 8> Elts;
496 do {
497 if (Lex.getKind() != lltok::Metadata)
498 return TokError("Expected '!' here");
499 Lex.Lex();
500 MetadataBase *N = 0;
501 if (ParseMDNode(N)) return true;
502 Elts.push_back(N);
503 } while (EatIfPresent(lltok::comma));
504
505 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
506 return true;
507
Owen Anderson1d0be152009-08-13 21:58:54 +0000508 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
Devang Pateleff2ab62009-07-29 00:34:02 +0000509 return false;
510}
511
Devang Patel923078c2009-07-01 19:21:12 +0000512/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000513/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000514bool LLParser::ParseStandaloneMetadata() {
515 assert(Lex.getKind() == lltok::Metadata);
516 Lex.Lex();
517 unsigned MetadataID = 0;
518 if (ParseUInt32(MetadataID))
519 return true;
520 if (MetadataCache.find(MetadataID) != MetadataCache.end())
521 return TokError("Metadata id is already used");
522 if (ParseToken(lltok::equal, "expected '=' here"))
523 return true;
524
525 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000526 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel2214c942009-07-08 21:57:07 +0000527 if (ParseType(Ty, TyLoc))
Devang Patel923078c2009-07-01 19:21:12 +0000528 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000529
Devang Patel104cf9e2009-07-23 01:07:34 +0000530 if (Lex.getKind() != lltok::Metadata)
531 return TokError("Expected metadata here");
Devang Patel923078c2009-07-01 19:21:12 +0000532
Devang Patel104cf9e2009-07-23 01:07:34 +0000533 Lex.Lex();
534 if (Lex.getKind() != lltok::lbrace)
535 return TokError("Expected '{' here");
536
537 SmallVector<Value *, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000538 if (ParseMDNodeVector(Elts)
Benjamin Kramer30d3b912009-07-27 09:06:52 +0000539 || ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000540 return true;
541
Owen Anderson647e3012009-07-31 21:35:40 +0000542 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel923078c2009-07-01 19:21:12 +0000543 MetadataCache[MetadataID] = Init;
Devang Patel104cf9e2009-07-23 01:07:34 +0000544 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000545 FI = ForwardRefMDNodes.find(MetadataID);
546 if (FI != ForwardRefMDNodes.end()) {
Devang Patel104cf9e2009-07-23 01:07:34 +0000547 MDNode *FwdNode = cast<MDNode>(FI->second.first);
Devang Patel1c7eea62009-07-08 19:23:54 +0000548 FwdNode->replaceAllUsesWith(Init);
549 ForwardRefMDNodes.erase(FI);
550 }
551
Devang Patel923078c2009-07-01 19:21:12 +0000552 return false;
553}
554
Chris Lattnerdf986172009-01-02 07:01:27 +0000555/// ParseAlias:
556/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
557/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000558/// ::= TypeAndValue
559/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000560/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000561///
562/// Everything through visibility has already been parsed.
563///
564bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
565 unsigned Visibility) {
566 assert(Lex.getKind() == lltok::kw_alias);
567 Lex.Lex();
568 unsigned Linkage;
569 LocTy LinkageLoc = Lex.getLoc();
570 if (ParseOptionalLinkage(Linkage))
571 return true;
572
573 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000574 Linkage != GlobalValue::WeakAnyLinkage &&
575 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000576 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000577 Linkage != GlobalValue::PrivateLinkage &&
578 Linkage != GlobalValue::LinkerPrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000579 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000580
Chris Lattnerdf986172009-01-02 07:01:27 +0000581 Constant *Aliasee;
582 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000583 if (Lex.getKind() != lltok::kw_bitcast &&
584 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000585 if (ParseGlobalTypeAndValue(Aliasee)) return true;
586 } else {
587 // The bitcast dest type is not present, it is implied by the dest type.
588 ValID ID;
589 if (ParseValID(ID)) return true;
590 if (ID.Kind != ValID::t_Constant)
591 return Error(AliaseeLoc, "invalid aliasee");
592 Aliasee = ID.ConstantVal;
593 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000594
Chris Lattnerdf986172009-01-02 07:01:27 +0000595 if (!isa<PointerType>(Aliasee->getType()))
596 return Error(AliaseeLoc, "alias must have pointer type");
597
598 // Okay, create the alias but do not insert it into the module yet.
599 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
600 (GlobalValue::LinkageTypes)Linkage, Name,
601 Aliasee);
602 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000603
Chris Lattnerdf986172009-01-02 07:01:27 +0000604 // See if this value already exists in the symbol table. If so, it is either
605 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000606 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000607 // See if this was a redefinition. If so, there is no entry in
608 // ForwardRefVals.
609 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
610 I = ForwardRefVals.find(Name);
611 if (I == ForwardRefVals.end())
612 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
613
614 // Otherwise, this was a definition of forward ref. Verify that types
615 // agree.
616 if (Val->getType() != GA->getType())
617 return Error(NameLoc,
618 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000619
Chris Lattnerdf986172009-01-02 07:01:27 +0000620 // If they agree, just RAUW the old value with the alias and remove the
621 // forward ref info.
622 Val->replaceAllUsesWith(GA);
623 Val->eraseFromParent();
624 ForwardRefVals.erase(I);
625 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000626
Chris Lattnerdf986172009-01-02 07:01:27 +0000627 // Insert into the module, we know its name won't collide now.
628 M->getAliasList().push_back(GA);
629 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000630
Chris Lattnerdf986172009-01-02 07:01:27 +0000631 return false;
632}
633
634/// ParseGlobal
635/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
636/// OptionalAddrSpace GlobalType Type Const
637/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
638/// OptionalAddrSpace GlobalType Type Const
639///
640/// Everything through visibility has been parsed already.
641///
642bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
643 unsigned Linkage, bool HasLinkage,
644 unsigned Visibility) {
645 unsigned AddrSpace;
646 bool ThreadLocal, IsConstant;
647 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000648
Owen Anderson1d0be152009-08-13 21:58:54 +0000649 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000650 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
651 ParseOptionalAddrSpace(AddrSpace) ||
652 ParseGlobalType(IsConstant) ||
653 ParseType(Ty, TyLoc))
654 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000655
Chris Lattnerdf986172009-01-02 07:01:27 +0000656 // If the linkage is specified and is external, then no initializer is
657 // present.
658 Constant *Init = 0;
659 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000660 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000661 Linkage != GlobalValue::ExternalLinkage)) {
662 if (ParseGlobalValue(Ty, Init))
663 return true;
664 }
665
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000666 if (isa<FunctionType>(Ty) || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000667 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000668
Chris Lattnerdf986172009-01-02 07:01:27 +0000669 GlobalVariable *GV = 0;
670
671 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000672 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000673 if (GlobalValue *GVal = M->getNamedValue(Name)) {
674 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
675 return Error(NameLoc, "redefinition of global '@" + Name + "'");
676 GV = cast<GlobalVariable>(GVal);
677 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000678 } else {
679 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
680 I = ForwardRefValIDs.find(NumberedVals.size());
681 if (I != ForwardRefValIDs.end()) {
682 GV = cast<GlobalVariable>(I->second.first);
683 ForwardRefValIDs.erase(I);
684 }
685 }
686
687 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000688 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000689 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000690 } else {
691 if (GV->getType()->getElementType() != Ty)
692 return Error(TyLoc,
693 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000694
Chris Lattnerdf986172009-01-02 07:01:27 +0000695 // Move the forward-reference to the correct spot in the module.
696 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
697 }
698
699 if (Name.empty())
700 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000701
Chris Lattnerdf986172009-01-02 07:01:27 +0000702 // Set the parsed properties on the global.
703 if (Init)
704 GV->setInitializer(Init);
705 GV->setConstant(IsConstant);
706 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
707 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
708 GV->setThreadLocal(ThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000709
Chris Lattnerdf986172009-01-02 07:01:27 +0000710 // Parse attributes on the global.
711 while (Lex.getKind() == lltok::comma) {
712 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000713
Chris Lattnerdf986172009-01-02 07:01:27 +0000714 if (Lex.getKind() == lltok::kw_section) {
715 Lex.Lex();
716 GV->setSection(Lex.getStrVal());
717 if (ParseToken(lltok::StringConstant, "expected global section string"))
718 return true;
719 } else if (Lex.getKind() == lltok::kw_align) {
720 unsigned Alignment;
721 if (ParseOptionalAlignment(Alignment)) return true;
722 GV->setAlignment(Alignment);
723 } else {
724 TokError("unknown global variable property!");
725 }
726 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000727
Chris Lattnerdf986172009-01-02 07:01:27 +0000728 return false;
729}
730
731
732//===----------------------------------------------------------------------===//
733// GlobalValue Reference/Resolution Routines.
734//===----------------------------------------------------------------------===//
735
736/// GetGlobalVal - Get a value with the specified name or ID, creating a
737/// forward reference record if needed. This can return null if the value
738/// exists but does not have the right type.
739GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
740 LocTy Loc) {
741 const PointerType *PTy = dyn_cast<PointerType>(Ty);
742 if (PTy == 0) {
743 Error(Loc, "global variable reference must have pointer type");
744 return 0;
745 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000746
Chris Lattnerdf986172009-01-02 07:01:27 +0000747 // Look this name up in the normal function symbol table.
748 GlobalValue *Val =
749 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000750
Chris Lattnerdf986172009-01-02 07:01:27 +0000751 // If this is a forward reference for the value, see if we already created a
752 // forward ref record.
753 if (Val == 0) {
754 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
755 I = ForwardRefVals.find(Name);
756 if (I != ForwardRefVals.end())
757 Val = I->second.first;
758 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000759
Chris Lattnerdf986172009-01-02 07:01:27 +0000760 // If we have the value in the symbol table or fwd-ref table, return it.
761 if (Val) {
762 if (Val->getType() == Ty) return Val;
763 Error(Loc, "'@" + Name + "' defined with type '" +
764 Val->getType()->getDescription() + "'");
765 return 0;
766 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000767
Chris Lattnerdf986172009-01-02 07:01:27 +0000768 // Otherwise, create a new forward reference for this value and remember it.
769 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000770 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
771 // Function types can return opaque but functions can't.
772 if (isa<OpaqueType>(FT->getReturnType())) {
773 Error(Loc, "function may not return opaque type");
774 return 0;
775 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000776
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000777 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000778 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000779 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
780 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000781 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000782
Chris Lattnerdf986172009-01-02 07:01:27 +0000783 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
784 return FwdVal;
785}
786
787GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
788 const PointerType *PTy = dyn_cast<PointerType>(Ty);
789 if (PTy == 0) {
790 Error(Loc, "global variable reference must have pointer type");
791 return 0;
792 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000793
Chris Lattnerdf986172009-01-02 07:01:27 +0000794 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000795
Chris Lattnerdf986172009-01-02 07:01:27 +0000796 // If this is a forward reference for the value, see if we already created a
797 // forward ref record.
798 if (Val == 0) {
799 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
800 I = ForwardRefValIDs.find(ID);
801 if (I != ForwardRefValIDs.end())
802 Val = I->second.first;
803 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000804
Chris Lattnerdf986172009-01-02 07:01:27 +0000805 // If we have the value in the symbol table or fwd-ref table, return it.
806 if (Val) {
807 if (Val->getType() == Ty) return Val;
808 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
809 Val->getType()->getDescription() + "'");
810 return 0;
811 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000812
Chris Lattnerdf986172009-01-02 07:01:27 +0000813 // Otherwise, create a new forward reference for this value and remember it.
814 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000815 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
816 // Function types can return opaque but functions can't.
817 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000818 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000819 return 0;
820 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000821 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000822 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000823 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
824 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000825 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000826
Chris Lattnerdf986172009-01-02 07:01:27 +0000827 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
828 return FwdVal;
829}
830
831
832//===----------------------------------------------------------------------===//
833// Helper Routines.
834//===----------------------------------------------------------------------===//
835
836/// ParseToken - If the current token has the specified kind, eat it and return
837/// success. Otherwise, emit the specified error and return failure.
838bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
839 if (Lex.getKind() != T)
840 return TokError(ErrMsg);
841 Lex.Lex();
842 return false;
843}
844
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000845/// ParseStringConstant
846/// ::= StringConstant
847bool LLParser::ParseStringConstant(std::string &Result) {
848 if (Lex.getKind() != lltok::StringConstant)
849 return TokError("expected string constant");
850 Result = Lex.getStrVal();
851 Lex.Lex();
852 return false;
853}
854
855/// ParseUInt32
856/// ::= uint32
857bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000858 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
859 return TokError("expected integer");
860 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
861 if (Val64 != unsigned(Val64))
862 return TokError("expected 32-bit integer (too large)");
863 Val = Val64;
864 Lex.Lex();
865 return false;
866}
867
868
869/// ParseOptionalAddrSpace
870/// := /*empty*/
871/// := 'addrspace' '(' uint32 ')'
872bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
873 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000874 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000875 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000876 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000877 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000878 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000879}
Chris Lattnerdf986172009-01-02 07:01:27 +0000880
881/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
882/// indicates what kind of attribute list this is: 0: function arg, 1: result,
883/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000884/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000885bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
886 Attrs = Attribute::None;
887 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000888
Chris Lattnerdf986172009-01-02 07:01:27 +0000889 while (1) {
890 switch (Lex.getKind()) {
891 case lltok::kw_sext:
892 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000893 // Treat these as signext/zeroext if they occur in the argument list after
894 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
895 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
896 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000897 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000898 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000899 if (Lex.getKind() == lltok::kw_sext)
900 Attrs |= Attribute::SExt;
901 else
902 Attrs |= Attribute::ZExt;
903 break;
904 }
905 // FALL THROUGH.
906 default: // End of attributes.
907 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
908 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000909
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000910 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000911 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000912
Chris Lattnerdf986172009-01-02 07:01:27 +0000913 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000914 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
915 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
916 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
917 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
918 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
919 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
920 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
921 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000922
Devang Patel578efa92009-06-05 21:57:13 +0000923 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
924 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
925 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
926 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
927 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Dale Johannesende86d472009-08-26 01:08:21 +0000928 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000929 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
930 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
931 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
932 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
933 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
934 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000935 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000936
Chris Lattnerdf986172009-01-02 07:01:27 +0000937 case lltok::kw_align: {
938 unsigned Alignment;
939 if (ParseOptionalAlignment(Alignment))
940 return true;
941 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
942 continue;
943 }
944 }
945 Lex.Lex();
946 }
947}
948
949/// ParseOptionalLinkage
950/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000951/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000952/// ::= 'linker_private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000953/// ::= 'internal'
954/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000955/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000956/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000957/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000958/// ::= 'appending'
959/// ::= 'dllexport'
960/// ::= 'common'
961/// ::= 'dllimport'
962/// ::= 'extern_weak'
963/// ::= 'external'
964bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
965 HasLinkage = false;
966 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000967 default: Res=GlobalValue::ExternalLinkage; return false;
968 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
969 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
970 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
971 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
972 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
973 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
974 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000975 case lltok::kw_available_externally:
976 Res = GlobalValue::AvailableExternallyLinkage;
977 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000978 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
979 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
980 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
981 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
982 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
983 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000984 }
985 Lex.Lex();
986 HasLinkage = true;
987 return false;
988}
989
990/// ParseOptionalVisibility
991/// ::= /*empty*/
992/// ::= 'default'
993/// ::= 'hidden'
994/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +0000995///
Chris Lattnerdf986172009-01-02 07:01:27 +0000996bool LLParser::ParseOptionalVisibility(unsigned &Res) {
997 switch (Lex.getKind()) {
998 default: Res = GlobalValue::DefaultVisibility; return false;
999 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1000 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1001 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1002 }
1003 Lex.Lex();
1004 return false;
1005}
1006
1007/// ParseOptionalCallingConv
1008/// ::= /*empty*/
1009/// ::= 'ccc'
1010/// ::= 'fastcc'
1011/// ::= 'coldcc'
1012/// ::= 'x86_stdcallcc'
1013/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001014/// ::= 'arm_apcscc'
1015/// ::= 'arm_aapcscc'
1016/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001017/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001018///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001019bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001020 switch (Lex.getKind()) {
1021 default: CC = CallingConv::C; return false;
1022 case lltok::kw_ccc: CC = CallingConv::C; break;
1023 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1024 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1025 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1026 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001027 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1028 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1029 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001030 case lltok::kw_cc: {
1031 unsigned ArbitraryCC;
1032 Lex.Lex();
1033 if (ParseUInt32(ArbitraryCC)) {
1034 return true;
1035 } else
1036 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1037 return false;
1038 }
1039 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001040 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001041
Chris Lattnerdf986172009-01-02 07:01:27 +00001042 Lex.Lex();
1043 return false;
1044}
1045
Devang Patel0475c912009-09-29 00:01:14 +00001046/// ParseOptionalCustomMetadata
Devang Patelf633a062009-09-17 23:04:48 +00001047/// ::= /* empty */
Devang Patel0475c912009-09-29 00:01:14 +00001048/// ::= !dbg !42
1049bool LLParser::ParseOptionalCustomMetadata() {
Chris Lattner52e20312009-10-19 05:31:10 +00001050 if (Lex.getKind() != lltok::NamedOrCustomMD)
Devang Patelf633a062009-09-17 23:04:48 +00001051 return false;
Devang Patel0475c912009-09-29 00:01:14 +00001052
Chris Lattner52e20312009-10-19 05:31:10 +00001053 std::string Name = Lex.getStrVal();
1054 Lex.Lex();
1055
Devang Patelf633a062009-09-17 23:04:48 +00001056 if (Lex.getKind() != lltok::Metadata)
1057 return TokError("Expected '!' here");
1058 Lex.Lex();
Devang Patel0475c912009-09-29 00:01:14 +00001059
Devang Patelf633a062009-09-17 23:04:48 +00001060 MetadataBase *Node;
1061 if (ParseMDNode(Node)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001062
Devang Patele30e6782009-09-28 21:41:20 +00001063 MetadataContext &TheMetadata = M->getContext().getMetadata();
Devang Patel0475c912009-09-29 00:01:14 +00001064 unsigned MDK = TheMetadata.getMDKind(Name.c_str());
1065 if (!MDK)
Devang Pateld9723e92009-10-20 22:50:27 +00001066 MDK = TheMetadata.registerMDKind(Name.c_str());
Devang Patel0475c912009-09-29 00:01:14 +00001067 MDsOnInst.push_back(std::make_pair(MDK, cast<MDNode>(Node)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001068
Devang Patelf633a062009-09-17 23:04:48 +00001069 return false;
1070}
1071
Chris Lattnerdf986172009-01-02 07:01:27 +00001072/// ParseOptionalAlignment
1073/// ::= /* empty */
1074/// ::= 'align' 4
1075bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1076 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001077 if (!EatIfPresent(lltok::kw_align))
1078 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001079 LocTy AlignLoc = Lex.getLoc();
1080 if (ParseUInt32(Alignment)) return true;
1081 if (!isPowerOf2_32(Alignment))
1082 return Error(AlignLoc, "alignment is not a power of two");
1083 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001084}
1085
Devang Patelf633a062009-09-17 23:04:48 +00001086/// ParseOptionalInfo
1087/// ::= OptionalInfo (',' OptionalInfo)+
1088bool LLParser::ParseOptionalInfo(unsigned &Alignment) {
1089
1090 // FIXME: Handle customized metadata info attached with an instruction.
1091 do {
Devang Patel0475c912009-09-29 00:01:14 +00001092 if (Lex.getKind() == lltok::NamedOrCustomMD) {
1093 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00001094 } else if (Lex.getKind() == lltok::kw_align) {
1095 if (ParseOptionalAlignment(Alignment)) return true;
1096 } else
1097 return true;
1098 } while (EatIfPresent(lltok::comma));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001099
Devang Patelf633a062009-09-17 23:04:48 +00001100 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001101}
1102
Devang Patelf633a062009-09-17 23:04:48 +00001103
Chris Lattnerdf986172009-01-02 07:01:27 +00001104/// ParseIndexList
1105/// ::= (',' uint32)+
1106bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1107 if (Lex.getKind() != lltok::comma)
1108 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001109
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001110 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001111 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001112 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001113 Indices.push_back(Idx);
1114 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001115
Chris Lattnerdf986172009-01-02 07:01:27 +00001116 return false;
1117}
1118
1119//===----------------------------------------------------------------------===//
1120// Type Parsing.
1121//===----------------------------------------------------------------------===//
1122
1123/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001124bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1125 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001126 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001127
Chris Lattnerdf986172009-01-02 07:01:27 +00001128 // Verify no unresolved uprefs.
1129 if (!UpRefs.empty())
1130 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001131
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001132 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001133 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001134
Chris Lattnerdf986172009-01-02 07:01:27 +00001135 return false;
1136}
1137
1138/// HandleUpRefs - Every time we finish a new layer of types, this function is
1139/// called. It loops through the UpRefs vector, which is a list of the
1140/// currently active types. For each type, if the up-reference is contained in
1141/// the newly completed type, we decrement the level count. When the level
1142/// count reaches zero, the up-referenced type is the type that is passed in:
1143/// thus we can complete the cycle.
1144///
1145PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1146 // If Ty isn't abstract, or if there are no up-references in it, then there is
1147 // nothing to resolve here.
1148 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001149
Chris Lattnerdf986172009-01-02 07:01:27 +00001150 PATypeHolder Ty(ty);
1151#if 0
1152 errs() << "Type '" << Ty->getDescription()
1153 << "' newly formed. Resolving upreferences.\n"
1154 << UpRefs.size() << " upreferences active!\n";
1155#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001156
Chris Lattnerdf986172009-01-02 07:01:27 +00001157 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1158 // to zero), we resolve them all together before we resolve them to Ty. At
1159 // the end of the loop, if there is anything to resolve to Ty, it will be in
1160 // this variable.
1161 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001162
Chris Lattnerdf986172009-01-02 07:01:27 +00001163 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1164 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1165 bool ContainsType =
1166 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1167 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001168
Chris Lattnerdf986172009-01-02 07:01:27 +00001169#if 0
1170 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1171 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1172 << (ContainsType ? "true" : "false")
1173 << " level=" << UpRefs[i].NestingLevel << "\n";
1174#endif
1175 if (!ContainsType)
1176 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001177
Chris Lattnerdf986172009-01-02 07:01:27 +00001178 // Decrement level of upreference
1179 unsigned Level = --UpRefs[i].NestingLevel;
1180 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001181
Chris Lattnerdf986172009-01-02 07:01:27 +00001182 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1183 if (Level != 0)
1184 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001185
Chris Lattnerdf986172009-01-02 07:01:27 +00001186#if 0
1187 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1188#endif
1189 if (!TypeToResolve)
1190 TypeToResolve = UpRefs[i].UpRefTy;
1191 else
1192 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1193 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1194 --i; // Do not skip the next element.
1195 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001196
Chris Lattnerdf986172009-01-02 07:01:27 +00001197 if (TypeToResolve)
1198 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001199
Chris Lattnerdf986172009-01-02 07:01:27 +00001200 return Ty;
1201}
1202
1203
1204/// ParseTypeRec - The recursive function used to process the internal
1205/// implementation details of types.
1206bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1207 switch (Lex.getKind()) {
1208 default:
1209 return TokError("expected type");
1210 case lltok::Type:
1211 // TypeRec ::= 'float' | 'void' (etc)
1212 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001213 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001214 break;
1215 case lltok::kw_opaque:
1216 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001217 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001218 Lex.Lex();
1219 break;
1220 case lltok::lbrace:
1221 // TypeRec ::= '{' ... '}'
1222 if (ParseStructType(Result, false))
1223 return true;
1224 break;
1225 case lltok::lsquare:
1226 // TypeRec ::= '[' ... ']'
1227 Lex.Lex(); // eat the lsquare.
1228 if (ParseArrayVectorType(Result, false))
1229 return true;
1230 break;
1231 case lltok::less: // Either vector or packed struct.
1232 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001233 Lex.Lex();
1234 if (Lex.getKind() == lltok::lbrace) {
1235 if (ParseStructType(Result, true) ||
1236 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001237 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001238 } else if (ParseArrayVectorType(Result, true))
1239 return true;
1240 break;
1241 case lltok::LocalVar:
1242 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1243 // TypeRec ::= %foo
1244 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1245 Result = T;
1246 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001247 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001248 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1249 std::make_pair(Result,
1250 Lex.getLoc())));
1251 M->addTypeName(Lex.getStrVal(), Result.get());
1252 }
1253 Lex.Lex();
1254 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001255
Chris Lattnerdf986172009-01-02 07:01:27 +00001256 case lltok::LocalVarID:
1257 // TypeRec ::= %4
1258 if (Lex.getUIntVal() < NumberedTypes.size())
1259 Result = NumberedTypes[Lex.getUIntVal()];
1260 else {
1261 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1262 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1263 if (I != ForwardRefTypeIDs.end())
1264 Result = I->second.first;
1265 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001266 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001267 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1268 std::make_pair(Result,
1269 Lex.getLoc())));
1270 }
1271 }
1272 Lex.Lex();
1273 break;
1274 case lltok::backslash: {
1275 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001276 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001277 unsigned Val;
1278 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001279 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001280 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1281 Result = OT;
1282 break;
1283 }
1284 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001285
1286 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001287 while (1) {
1288 switch (Lex.getKind()) {
1289 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001290 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001291
1292 // TypeRec ::= TypeRec '*'
1293 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001294 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001295 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001296 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001297 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001298 if (!PointerType::isValidElementType(Result.get()))
1299 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001300 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001301 Lex.Lex();
1302 break;
1303
1304 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1305 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001306 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001307 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001308 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001309 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001310 if (!PointerType::isValidElementType(Result.get()))
1311 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001312 unsigned AddrSpace;
1313 if (ParseOptionalAddrSpace(AddrSpace) ||
1314 ParseToken(lltok::star, "expected '*' in address space"))
1315 return true;
1316
Owen Andersondebcb012009-07-29 22:17:13 +00001317 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001318 break;
1319 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001320
Chris Lattnerdf986172009-01-02 07:01:27 +00001321 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1322 case lltok::lparen:
1323 if (ParseFunctionType(Result))
1324 return true;
1325 break;
1326 }
1327 }
1328}
1329
1330/// ParseParameterList
1331/// ::= '(' ')'
1332/// ::= '(' Arg (',' Arg)* ')'
1333/// Arg
1334/// ::= Type OptionalAttributes Value OptionalAttributes
1335bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1336 PerFunctionState &PFS) {
1337 if (ParseToken(lltok::lparen, "expected '(' in call"))
1338 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001339
Chris Lattnerdf986172009-01-02 07:01:27 +00001340 while (Lex.getKind() != lltok::rparen) {
1341 // If this isn't the first argument, we need a comma.
1342 if (!ArgList.empty() &&
1343 ParseToken(lltok::comma, "expected ',' in argument list"))
1344 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001345
Chris Lattnerdf986172009-01-02 07:01:27 +00001346 // Parse the argument.
1347 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001348 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001349 unsigned ArgAttrs1, ArgAttrs2;
1350 Value *V;
1351 if (ParseType(ArgTy, ArgLoc) ||
1352 ParseOptionalAttrs(ArgAttrs1, 0) ||
1353 ParseValue(ArgTy, V, PFS) ||
1354 // FIXME: Should not allow attributes after the argument, remove this in
1355 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001356 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001357 return true;
1358 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1359 }
1360
1361 Lex.Lex(); // Lex the ')'.
1362 return false;
1363}
1364
1365
1366
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001367/// ParseArgumentList - Parse the argument list for a function type or function
1368/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001369/// ::= '(' ArgTypeListI ')'
1370/// ArgTypeListI
1371/// ::= /*empty*/
1372/// ::= '...'
1373/// ::= ArgTypeList ',' '...'
1374/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001375///
Chris Lattnerdf986172009-01-02 07:01:27 +00001376bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001377 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001378 isVarArg = false;
1379 assert(Lex.getKind() == lltok::lparen);
1380 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001381
Chris Lattnerdf986172009-01-02 07:01:27 +00001382 if (Lex.getKind() == lltok::rparen) {
1383 // empty
1384 } else if (Lex.getKind() == lltok::dotdotdot) {
1385 isVarArg = true;
1386 Lex.Lex();
1387 } else {
1388 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001389 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001390 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001391 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001392
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001393 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1394 // types (such as a function returning a pointer to itself). If parsing a
1395 // function prototype, we require fully resolved types.
1396 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001397 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001398
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001399 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001400 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001401
Chris Lattnerdf986172009-01-02 07:01:27 +00001402 if (Lex.getKind() == lltok::LocalVar ||
1403 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1404 Name = Lex.getStrVal();
1405 Lex.Lex();
1406 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001407
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001408 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001409 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001410
Chris Lattnerdf986172009-01-02 07:01:27 +00001411 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001412
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001413 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001414 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001415 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001416 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001417 break;
1418 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001419
Chris Lattnerdf986172009-01-02 07:01:27 +00001420 // Otherwise must be an argument type.
1421 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001422 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001423 ParseOptionalAttrs(Attrs, 0)) return true;
1424
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001425 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001426 return Error(TypeLoc, "argument can not have void type");
1427
Chris Lattnerdf986172009-01-02 07:01:27 +00001428 if (Lex.getKind() == lltok::LocalVar ||
1429 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1430 Name = Lex.getStrVal();
1431 Lex.Lex();
1432 } else {
1433 Name = "";
1434 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001435
1436 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1437 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001438
Chris Lattnerdf986172009-01-02 07:01:27 +00001439 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1440 }
1441 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001442
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001443 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001444}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001445
Chris Lattnerdf986172009-01-02 07:01:27 +00001446/// ParseFunctionType
1447/// ::= Type ArgumentList OptionalAttrs
1448bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1449 assert(Lex.getKind() == lltok::lparen);
1450
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001451 if (!FunctionType::isValidReturnType(Result))
1452 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001453
Chris Lattnerdf986172009-01-02 07:01:27 +00001454 std::vector<ArgInfo> ArgList;
1455 bool isVarArg;
1456 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001457 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001458 // FIXME: Allow, but ignore attributes on function types!
1459 // FIXME: Remove in LLVM 3.0
1460 ParseOptionalAttrs(Attrs, 2))
1461 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001462
Chris Lattnerdf986172009-01-02 07:01:27 +00001463 // Reject names on the arguments lists.
1464 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1465 if (!ArgList[i].Name.empty())
1466 return Error(ArgList[i].Loc, "argument name invalid in function type");
1467 if (!ArgList[i].Attrs != 0) {
1468 // Allow but ignore attributes on function types; this permits
1469 // auto-upgrade.
1470 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1471 }
1472 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001473
Chris Lattnerdf986172009-01-02 07:01:27 +00001474 std::vector<const Type*> ArgListTy;
1475 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1476 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001477
Owen Andersondebcb012009-07-29 22:17:13 +00001478 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001479 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001480 return false;
1481}
1482
1483/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1484/// TypeRec
1485/// ::= '{' '}'
1486/// ::= '{' TypeRec (',' TypeRec)* '}'
1487/// ::= '<' '{' '}' '>'
1488/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1489bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1490 assert(Lex.getKind() == lltok::lbrace);
1491 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001492
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001493 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001494 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001495 return false;
1496 }
1497
1498 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001499 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001500 if (ParseTypeRec(Result)) return true;
1501 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001502
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001503 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001504 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001505 if (!StructType::isValidElementType(Result))
1506 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001507
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001508 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001509 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001510 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001511
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001512 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001513 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001514 if (!StructType::isValidElementType(Result))
1515 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001516
Chris Lattnerdf986172009-01-02 07:01:27 +00001517 ParamsList.push_back(Result);
1518 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001519
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001520 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1521 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001522
Chris Lattnerdf986172009-01-02 07:01:27 +00001523 std::vector<const Type*> ParamsListTy;
1524 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1525 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001526 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001527 return false;
1528}
1529
1530/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1531/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001532/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001533/// ::= '[' APSINTVAL 'x' Types ']'
1534/// ::= '<' APSINTVAL 'x' Types '>'
1535bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1536 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1537 Lex.getAPSIntVal().getBitWidth() > 64)
1538 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001539
Chris Lattnerdf986172009-01-02 07:01:27 +00001540 LocTy SizeLoc = Lex.getLoc();
1541 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001542 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001543
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001544 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1545 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001546
1547 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001548 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001549 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001550
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001551 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001552 return Error(TypeLoc, "array and vector element type cannot be void");
1553
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001554 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1555 "expected end of sequential type"))
1556 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001557
Chris Lattnerdf986172009-01-02 07:01:27 +00001558 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001559 if (Size == 0)
1560 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001561 if ((unsigned)Size != Size)
1562 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001563 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001564 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001565 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001566 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001567 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001568 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001569 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001570 }
1571 return false;
1572}
1573
1574//===----------------------------------------------------------------------===//
1575// Function Semantic Analysis.
1576//===----------------------------------------------------------------------===//
1577
1578LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1579 : P(p), F(f) {
1580
1581 // Insert unnamed arguments into the NumberedVals list.
1582 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1583 AI != E; ++AI)
1584 if (!AI->hasName())
1585 NumberedVals.push_back(AI);
1586}
1587
1588LLParser::PerFunctionState::~PerFunctionState() {
1589 // If there were any forward referenced non-basicblock values, delete them.
1590 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1591 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1592 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001593 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001594 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001595 delete I->second.first;
1596 I->second.first = 0;
1597 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001598
Chris Lattnerdf986172009-01-02 07:01:27 +00001599 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1600 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1601 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001602 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001603 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001604 delete I->second.first;
1605 I->second.first = 0;
1606 }
1607}
1608
1609bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1610 if (!ForwardRefVals.empty())
1611 return P.Error(ForwardRefVals.begin()->second.second,
1612 "use of undefined value '%" + ForwardRefVals.begin()->first +
1613 "'");
1614 if (!ForwardRefValIDs.empty())
1615 return P.Error(ForwardRefValIDs.begin()->second.second,
1616 "use of undefined value '%" +
1617 utostr(ForwardRefValIDs.begin()->first) + "'");
1618 return false;
1619}
1620
1621
1622/// GetVal - Get a value with the specified name or ID, creating a
1623/// forward reference record if needed. This can return null if the value
1624/// exists but does not have the right type.
1625Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1626 const Type *Ty, LocTy Loc) {
1627 // Look this name up in the normal function symbol table.
1628 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001629
Chris Lattnerdf986172009-01-02 07:01:27 +00001630 // If this is a forward reference for the value, see if we already created a
1631 // forward ref record.
1632 if (Val == 0) {
1633 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1634 I = ForwardRefVals.find(Name);
1635 if (I != ForwardRefVals.end())
1636 Val = I->second.first;
1637 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001638
Chris Lattnerdf986172009-01-02 07:01:27 +00001639 // If we have the value in the symbol table or fwd-ref table, return it.
1640 if (Val) {
1641 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001642 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001643 P.Error(Loc, "'%" + Name + "' is not a basic block");
1644 else
1645 P.Error(Loc, "'%" + Name + "' defined with type '" +
1646 Val->getType()->getDescription() + "'");
1647 return 0;
1648 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001649
Chris Lattnerdf986172009-01-02 07:01:27 +00001650 // Don't make placeholders with invalid type.
Owen Anderson1d0be152009-08-13 21:58:54 +00001651 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1652 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001653 P.Error(Loc, "invalid use of a non-first-class type");
1654 return 0;
1655 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001656
Chris Lattnerdf986172009-01-02 07:01:27 +00001657 // Otherwise, create a new forward reference for this value and remember it.
1658 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001659 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001660 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001661 else
1662 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001663
Chris Lattnerdf986172009-01-02 07:01:27 +00001664 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1665 return FwdVal;
1666}
1667
1668Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1669 LocTy Loc) {
1670 // Look this name up in the normal function symbol table.
1671 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001672
Chris Lattnerdf986172009-01-02 07:01:27 +00001673 // If this is a forward reference for the value, see if we already created a
1674 // forward ref record.
1675 if (Val == 0) {
1676 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1677 I = ForwardRefValIDs.find(ID);
1678 if (I != ForwardRefValIDs.end())
1679 Val = I->second.first;
1680 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001681
Chris Lattnerdf986172009-01-02 07:01:27 +00001682 // If we have the value in the symbol table or fwd-ref table, return it.
1683 if (Val) {
1684 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001685 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001686 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1687 else
1688 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1689 Val->getType()->getDescription() + "'");
1690 return 0;
1691 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001692
Owen Anderson1d0be152009-08-13 21:58:54 +00001693 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1694 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001695 P.Error(Loc, "invalid use of a non-first-class type");
1696 return 0;
1697 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001698
Chris Lattnerdf986172009-01-02 07:01:27 +00001699 // Otherwise, create a new forward reference for this value and remember it.
1700 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001701 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001702 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001703 else
1704 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001705
Chris Lattnerdf986172009-01-02 07:01:27 +00001706 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1707 return FwdVal;
1708}
1709
1710/// SetInstName - After an instruction is parsed and inserted into its
1711/// basic block, this installs its name.
1712bool LLParser::PerFunctionState::SetInstName(int NameID,
1713 const std::string &NameStr,
1714 LocTy NameLoc, Instruction *Inst) {
1715 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001716 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001717 if (NameID != -1 || !NameStr.empty())
1718 return P.Error(NameLoc, "instructions returning void cannot have a name");
1719 return false;
1720 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001721
Chris Lattnerdf986172009-01-02 07:01:27 +00001722 // If this was a numbered instruction, verify that the instruction is the
1723 // expected value and resolve any forward references.
1724 if (NameStr.empty()) {
1725 // If neither a name nor an ID was specified, just use the next ID.
1726 if (NameID == -1)
1727 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001728
Chris Lattnerdf986172009-01-02 07:01:27 +00001729 if (unsigned(NameID) != NumberedVals.size())
1730 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1731 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001732
Chris Lattnerdf986172009-01-02 07:01:27 +00001733 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1734 ForwardRefValIDs.find(NameID);
1735 if (FI != ForwardRefValIDs.end()) {
1736 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001737 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001738 FI->second.first->getType()->getDescription() + "'");
1739 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001740 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001741 ForwardRefValIDs.erase(FI);
1742 }
1743
1744 NumberedVals.push_back(Inst);
1745 return false;
1746 }
1747
1748 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1749 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1750 FI = ForwardRefVals.find(NameStr);
1751 if (FI != ForwardRefVals.end()) {
1752 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001753 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001754 FI->second.first->getType()->getDescription() + "'");
1755 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001756 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001757 ForwardRefVals.erase(FI);
1758 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001759
Chris Lattnerdf986172009-01-02 07:01:27 +00001760 // Set the name on the instruction.
1761 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001762
Chris Lattnerdf986172009-01-02 07:01:27 +00001763 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001764 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001765 NameStr + "'");
1766 return false;
1767}
1768
1769/// GetBB - Get a basic block with the specified name or ID, creating a
1770/// forward reference record if needed.
1771BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1772 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001773 return cast_or_null<BasicBlock>(GetVal(Name,
1774 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001775}
1776
1777BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001778 return cast_or_null<BasicBlock>(GetVal(ID,
1779 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001780}
1781
1782/// DefineBB - Define the specified basic block, which is either named or
1783/// unnamed. If there is an error, this returns null otherwise it returns
1784/// the block being defined.
1785BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1786 LocTy Loc) {
1787 BasicBlock *BB;
1788 if (Name.empty())
1789 BB = GetBB(NumberedVals.size(), Loc);
1790 else
1791 BB = GetBB(Name, Loc);
1792 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001793
Chris Lattnerdf986172009-01-02 07:01:27 +00001794 // Move the block to the end of the function. Forward ref'd blocks are
1795 // inserted wherever they happen to be referenced.
1796 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001797
Chris Lattnerdf986172009-01-02 07:01:27 +00001798 // Remove the block from forward ref sets.
1799 if (Name.empty()) {
1800 ForwardRefValIDs.erase(NumberedVals.size());
1801 NumberedVals.push_back(BB);
1802 } else {
1803 // BB forward references are already in the function symbol table.
1804 ForwardRefVals.erase(Name);
1805 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001806
Chris Lattnerdf986172009-01-02 07:01:27 +00001807 return BB;
1808}
1809
1810//===----------------------------------------------------------------------===//
1811// Constants.
1812//===----------------------------------------------------------------------===//
1813
1814/// ParseValID - Parse an abstract value that doesn't necessarily have a
1815/// type implied. For example, if we parse "4" we don't know what integer type
1816/// it has. The value will later be combined with its type and checked for
1817/// sanity.
1818bool LLParser::ParseValID(ValID &ID) {
1819 ID.Loc = Lex.getLoc();
1820 switch (Lex.getKind()) {
1821 default: return TokError("expected value token");
1822 case lltok::GlobalID: // @42
1823 ID.UIntVal = Lex.getUIntVal();
1824 ID.Kind = ValID::t_GlobalID;
1825 break;
1826 case lltok::GlobalVar: // @foo
1827 ID.StrVal = Lex.getStrVal();
1828 ID.Kind = ValID::t_GlobalName;
1829 break;
1830 case lltok::LocalVarID: // %42
1831 ID.UIntVal = Lex.getUIntVal();
1832 ID.Kind = ValID::t_LocalID;
1833 break;
1834 case lltok::LocalVar: // %foo
1835 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1836 ID.StrVal = Lex.getStrVal();
1837 ID.Kind = ValID::t_LocalName;
1838 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001839 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
Devang Patel104cf9e2009-07-23 01:07:34 +00001840 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001841 Lex.Lex();
1842 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001843 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001844 if (ParseMDNodeVector(Elts) ||
1845 ParseToken(lltok::rbrace, "expected end of metadata node"))
1846 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001847
Owen Anderson647e3012009-07-31 21:35:40 +00001848 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001849 return false;
1850 }
1851
Devang Patel923078c2009-07-01 19:21:12 +00001852 // Standalone metadata reference
1853 // !{ ..., !42, ... }
Devang Patel104cf9e2009-07-23 01:07:34 +00001854 if (!ParseMDNode(ID.MetadataVal))
Devang Patel923078c2009-07-01 19:21:12 +00001855 return false;
Devang Patel256be962009-07-20 19:00:08 +00001856
Nick Lewycky21cc4462009-04-04 07:22:01 +00001857 // MDString:
1858 // ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +00001859 if (ParseMDString(ID.MetadataVal)) return true;
1860 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001861 return false;
1862 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001863 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001864 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001865 ID.Kind = ValID::t_APSInt;
1866 break;
1867 case lltok::APFloat:
1868 ID.APFloatVal = Lex.getAPFloatVal();
1869 ID.Kind = ValID::t_APFloat;
1870 break;
1871 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001872 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001873 ID.Kind = ValID::t_Constant;
1874 break;
1875 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001876 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001877 ID.Kind = ValID::t_Constant;
1878 break;
1879 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1880 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1881 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001882
Chris Lattnerdf986172009-01-02 07:01:27 +00001883 case lltok::lbrace: {
1884 // ValID ::= '{' ConstVector '}'
1885 Lex.Lex();
1886 SmallVector<Constant*, 16> Elts;
1887 if (ParseGlobalValueVector(Elts) ||
1888 ParseToken(lltok::rbrace, "expected end of struct constant"))
1889 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001890
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001891 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1892 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001893 ID.Kind = ValID::t_Constant;
1894 return false;
1895 }
1896 case lltok::less: {
1897 // ValID ::= '<' ConstVector '>' --> Vector.
1898 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1899 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001900 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001901
Chris Lattnerdf986172009-01-02 07:01:27 +00001902 SmallVector<Constant*, 16> Elts;
1903 LocTy FirstEltLoc = Lex.getLoc();
1904 if (ParseGlobalValueVector(Elts) ||
1905 (isPackedStruct &&
1906 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1907 ParseToken(lltok::greater, "expected end of constant"))
1908 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001909
Chris Lattnerdf986172009-01-02 07:01:27 +00001910 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001911 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001912 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001913 ID.Kind = ValID::t_Constant;
1914 return false;
1915 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001916
Chris Lattnerdf986172009-01-02 07:01:27 +00001917 if (Elts.empty())
1918 return Error(ID.Loc, "constant vector must not be empty");
1919
1920 if (!Elts[0]->getType()->isInteger() &&
1921 !Elts[0]->getType()->isFloatingPoint())
1922 return Error(FirstEltLoc,
1923 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001924
Chris Lattnerdf986172009-01-02 07:01:27 +00001925 // Verify that all the vector elements have the same type.
1926 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1927 if (Elts[i]->getType() != Elts[0]->getType())
1928 return Error(FirstEltLoc,
1929 "vector element #" + utostr(i) +
1930 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001931
Owen Andersonaf7ec972009-07-28 21:19:26 +00001932 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001933 ID.Kind = ValID::t_Constant;
1934 return false;
1935 }
1936 case lltok::lsquare: { // Array Constant
1937 Lex.Lex();
1938 SmallVector<Constant*, 16> Elts;
1939 LocTy FirstEltLoc = Lex.getLoc();
1940 if (ParseGlobalValueVector(Elts) ||
1941 ParseToken(lltok::rsquare, "expected end of array constant"))
1942 return true;
1943
1944 // Handle empty element.
1945 if (Elts.empty()) {
1946 // Use undef instead of an array because it's inconvenient to determine
1947 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001948 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001949 return false;
1950 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001951
Chris Lattnerdf986172009-01-02 07:01:27 +00001952 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001953 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00001954 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001955
Owen Andersondebcb012009-07-29 22:17:13 +00001956 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001957
Chris Lattnerdf986172009-01-02 07:01:27 +00001958 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001959 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001960 if (Elts[i]->getType() != Elts[0]->getType())
1961 return Error(FirstEltLoc,
1962 "array element #" + utostr(i) +
1963 " is not of type '" +Elts[0]->getType()->getDescription());
1964 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001965
Owen Anderson1fd70962009-07-28 18:32:17 +00001966 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001967 ID.Kind = ValID::t_Constant;
1968 return false;
1969 }
1970 case lltok::kw_c: // c "foo"
1971 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00001972 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001973 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1974 ID.Kind = ValID::t_Constant;
1975 return false;
1976
1977 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001978 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
1979 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00001980 Lex.Lex();
1981 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001982 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001983 ParseStringConstant(ID.StrVal) ||
1984 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001985 ParseToken(lltok::StringConstant, "expected constraint string"))
1986 return true;
1987 ID.StrVal2 = Lex.getStrVal();
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001988 ID.UIntVal = HasSideEffect | ((unsigned)AlignStack<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001989 ID.Kind = ValID::t_InlineAsm;
1990 return false;
1991 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001992
Chris Lattnerdf986172009-01-02 07:01:27 +00001993 case lltok::kw_trunc:
1994 case lltok::kw_zext:
1995 case lltok::kw_sext:
1996 case lltok::kw_fptrunc:
1997 case lltok::kw_fpext:
1998 case lltok::kw_bitcast:
1999 case lltok::kw_uitofp:
2000 case lltok::kw_sitofp:
2001 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002002 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002003 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002004 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002005 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002006 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002007 Constant *SrcVal;
2008 Lex.Lex();
2009 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2010 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002011 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002012 ParseType(DestTy) ||
2013 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2014 return true;
2015 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2016 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2017 SrcVal->getType()->getDescription() + "' to '" +
2018 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002019 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002020 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002021 ID.Kind = ValID::t_Constant;
2022 return false;
2023 }
2024 case lltok::kw_extractvalue: {
2025 Lex.Lex();
2026 Constant *Val;
2027 SmallVector<unsigned, 4> Indices;
2028 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2029 ParseGlobalTypeAndValue(Val) ||
2030 ParseIndexList(Indices) ||
2031 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2032 return true;
2033 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
2034 return Error(ID.Loc, "extractvalue operand must be array or struct");
2035 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2036 Indices.end()))
2037 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002038 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002039 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002040 ID.Kind = ValID::t_Constant;
2041 return false;
2042 }
2043 case lltok::kw_insertvalue: {
2044 Lex.Lex();
2045 Constant *Val0, *Val1;
2046 SmallVector<unsigned, 4> Indices;
2047 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2048 ParseGlobalTypeAndValue(Val0) ||
2049 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2050 ParseGlobalTypeAndValue(Val1) ||
2051 ParseIndexList(Indices) ||
2052 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2053 return true;
2054 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2055 return Error(ID.Loc, "extractvalue operand must be array or struct");
2056 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2057 Indices.end()))
2058 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002059 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002060 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002061 ID.Kind = ValID::t_Constant;
2062 return false;
2063 }
2064 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002065 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002066 unsigned PredVal, Opc = Lex.getUIntVal();
2067 Constant *Val0, *Val1;
2068 Lex.Lex();
2069 if (ParseCmpPredicate(PredVal, Opc) ||
2070 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2071 ParseGlobalTypeAndValue(Val0) ||
2072 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2073 ParseGlobalTypeAndValue(Val1) ||
2074 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2075 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002076
Chris Lattnerdf986172009-01-02 07:01:27 +00002077 if (Val0->getType() != Val1->getType())
2078 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002079
Chris Lattnerdf986172009-01-02 07:01:27 +00002080 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002081
Chris Lattnerdf986172009-01-02 07:01:27 +00002082 if (Opc == Instruction::FCmp) {
2083 if (!Val0->getType()->isFPOrFPVector())
2084 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002085 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002086 } else {
2087 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002088 if (!Val0->getType()->isIntOrIntVector() &&
2089 !isa<PointerType>(Val0->getType()))
2090 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002091 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002092 }
2093 ID.Kind = ValID::t_Constant;
2094 return false;
2095 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002096
Chris Lattnerdf986172009-01-02 07:01:27 +00002097 // Binary Operators.
2098 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002099 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002100 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002101 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002102 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002103 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002104 case lltok::kw_udiv:
2105 case lltok::kw_sdiv:
2106 case lltok::kw_fdiv:
2107 case lltok::kw_urem:
2108 case lltok::kw_srem:
2109 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002110 bool NUW = false;
2111 bool NSW = false;
2112 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002113 unsigned Opc = Lex.getUIntVal();
2114 Constant *Val0, *Val1;
2115 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002116 LocTy ModifierLoc = Lex.getLoc();
2117 if (Opc == Instruction::Add ||
2118 Opc == Instruction::Sub ||
2119 Opc == Instruction::Mul) {
2120 if (EatIfPresent(lltok::kw_nuw))
2121 NUW = true;
2122 if (EatIfPresent(lltok::kw_nsw)) {
2123 NSW = true;
2124 if (EatIfPresent(lltok::kw_nuw))
2125 NUW = true;
2126 }
2127 } else if (Opc == Instruction::SDiv) {
2128 if (EatIfPresent(lltok::kw_exact))
2129 Exact = true;
2130 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002131 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2132 ParseGlobalTypeAndValue(Val0) ||
2133 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2134 ParseGlobalTypeAndValue(Val1) ||
2135 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2136 return true;
2137 if (Val0->getType() != Val1->getType())
2138 return Error(ID.Loc, "operands of constexpr must have same type");
Dan Gohman59858cf2009-07-27 16:11:46 +00002139 if (!Val0->getType()->isIntOrIntVector()) {
2140 if (NUW)
2141 return Error(ModifierLoc, "nuw only applies to integer operations");
2142 if (NSW)
2143 return Error(ModifierLoc, "nsw only applies to integer operations");
2144 }
2145 // API compatibility: Accept either integer or floating-point types with
2146 // add, sub, and mul.
Chris Lattnerdf986172009-01-02 07:01:27 +00002147 if (!Val0->getType()->isIntOrIntVector() &&
2148 !Val0->getType()->isFPOrFPVector())
2149 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002150 unsigned Flags = 0;
2151 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2152 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2153 if (Exact) Flags |= SDivOperator::IsExact;
2154 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002155 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002156 ID.Kind = ValID::t_Constant;
2157 return false;
2158 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002159
Chris Lattnerdf986172009-01-02 07:01:27 +00002160 // Logical Operations
2161 case lltok::kw_shl:
2162 case lltok::kw_lshr:
2163 case lltok::kw_ashr:
2164 case lltok::kw_and:
2165 case lltok::kw_or:
2166 case lltok::kw_xor: {
2167 unsigned Opc = Lex.getUIntVal();
2168 Constant *Val0, *Val1;
2169 Lex.Lex();
2170 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2171 ParseGlobalTypeAndValue(Val0) ||
2172 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2173 ParseGlobalTypeAndValue(Val1) ||
2174 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2175 return true;
2176 if (Val0->getType() != Val1->getType())
2177 return Error(ID.Loc, "operands of constexpr must have same type");
2178 if (!Val0->getType()->isIntOrIntVector())
2179 return Error(ID.Loc,
2180 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002181 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002182 ID.Kind = ValID::t_Constant;
2183 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002184 }
2185
Chris Lattnerdf986172009-01-02 07:01:27 +00002186 case lltok::kw_getelementptr:
2187 case lltok::kw_shufflevector:
2188 case lltok::kw_insertelement:
2189 case lltok::kw_extractelement:
2190 case lltok::kw_select: {
2191 unsigned Opc = Lex.getUIntVal();
2192 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002193 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002194 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002195 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002196 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002197 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2198 ParseGlobalValueVector(Elts) ||
2199 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2200 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002201
Chris Lattnerdf986172009-01-02 07:01:27 +00002202 if (Opc == Instruction::GetElementPtr) {
2203 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2204 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002205
Chris Lattnerdf986172009-01-02 07:01:27 +00002206 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002207 (Value**)(Elts.data() + 1),
2208 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002209 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002210 ID.ConstantVal = InBounds ?
2211 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2212 Elts.data() + 1,
2213 Elts.size() - 1) :
2214 ConstantExpr::getGetElementPtr(Elts[0],
2215 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002216 } else if (Opc == Instruction::Select) {
2217 if (Elts.size() != 3)
2218 return Error(ID.Loc, "expected three operands to select");
2219 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2220 Elts[2]))
2221 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002222 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002223 } else if (Opc == Instruction::ShuffleVector) {
2224 if (Elts.size() != 3)
2225 return Error(ID.Loc, "expected three operands to shufflevector");
2226 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2227 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002228 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002229 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002230 } else if (Opc == Instruction::ExtractElement) {
2231 if (Elts.size() != 2)
2232 return Error(ID.Loc, "expected two operands to extractelement");
2233 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2234 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002235 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002236 } else {
2237 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2238 if (Elts.size() != 3)
2239 return Error(ID.Loc, "expected three operands to insertelement");
2240 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2241 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002242 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002243 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002244 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002245
Chris Lattnerdf986172009-01-02 07:01:27 +00002246 ID.Kind = ValID::t_Constant;
2247 return false;
2248 }
2249 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002250
Chris Lattnerdf986172009-01-02 07:01:27 +00002251 Lex.Lex();
2252 return false;
2253}
2254
2255/// ParseGlobalValue - Parse a global value with the specified type.
2256bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2257 V = 0;
2258 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002259 return ParseValID(ID) ||
2260 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002261}
2262
2263/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2264/// constant.
2265bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2266 Constant *&V) {
2267 if (isa<FunctionType>(Ty))
2268 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002269
Chris Lattnerdf986172009-01-02 07:01:27 +00002270 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002271 default: llvm_unreachable("Unknown ValID!");
Devang Patele54abc92009-07-22 17:43:22 +00002272 case ValID::t_Metadata:
2273 return Error(ID.Loc, "invalid use of metadata");
Chris Lattnerdf986172009-01-02 07:01:27 +00002274 case ValID::t_LocalID:
2275 case ValID::t_LocalName:
2276 return Error(ID.Loc, "invalid use of function-local name");
2277 case ValID::t_InlineAsm:
2278 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2279 case ValID::t_GlobalName:
2280 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2281 return V == 0;
2282 case ValID::t_GlobalID:
2283 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2284 return V == 0;
2285 case ValID::t_APSInt:
2286 if (!isa<IntegerType>(Ty))
2287 return Error(ID.Loc, "integer constant must have integer type");
2288 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002289 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002290 return false;
2291 case ValID::t_APFloat:
2292 if (!Ty->isFloatingPoint() ||
2293 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2294 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002295
Chris Lattnerdf986172009-01-02 07:01:27 +00002296 // The lexer has no type info, so builds all float and double FP constants
2297 // as double. Fix this here. Long double does not need this.
2298 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002299 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002300 bool Ignored;
2301 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2302 &Ignored);
2303 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002304 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002305
Chris Lattner959873d2009-01-05 18:24:23 +00002306 if (V->getType() != Ty)
2307 return Error(ID.Loc, "floating point constant does not have type '" +
2308 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002309
Chris Lattnerdf986172009-01-02 07:01:27 +00002310 return false;
2311 case ValID::t_Null:
2312 if (!isa<PointerType>(Ty))
2313 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002314 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002315 return false;
2316 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002317 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002318 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Chris Lattner0b616352009-01-05 18:12:21 +00002319 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002320 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002321 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002322 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002323 case ValID::t_EmptyArray:
2324 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2325 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002326 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002327 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002328 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002329 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002330 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002331 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002332 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002333 return false;
2334 case ValID::t_Constant:
2335 if (ID.ConstantVal->getType() != Ty)
2336 return Error(ID.Loc, "constant expression type mismatch");
2337 V = ID.ConstantVal;
2338 return false;
2339 }
2340}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002341
Chris Lattnerdf986172009-01-02 07:01:27 +00002342bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002343 PATypeHolder Type(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002344 return ParseType(Type) ||
2345 ParseGlobalValue(Type, V);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002346}
Chris Lattnerdf986172009-01-02 07:01:27 +00002347
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002348/// ParseGlobalValueVector
2349/// ::= /*empty*/
2350/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002351bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2352 // Empty list.
2353 if (Lex.getKind() == lltok::rbrace ||
2354 Lex.getKind() == lltok::rsquare ||
2355 Lex.getKind() == lltok::greater ||
2356 Lex.getKind() == lltok::rparen)
2357 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002358
Chris Lattnerdf986172009-01-02 07:01:27 +00002359 Constant *C;
2360 if (ParseGlobalTypeAndValue(C)) return true;
2361 Elts.push_back(C);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002362
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002363 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002364 if (ParseGlobalTypeAndValue(C)) return true;
2365 Elts.push_back(C);
2366 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002367
Chris Lattnerdf986172009-01-02 07:01:27 +00002368 return false;
2369}
2370
2371
2372//===----------------------------------------------------------------------===//
2373// Function Parsing.
2374//===----------------------------------------------------------------------===//
2375
2376bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2377 PerFunctionState &PFS) {
2378 if (ID.Kind == ValID::t_LocalID)
2379 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2380 else if (ID.Kind == ValID::t_LocalName)
2381 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002382 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002383 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2384 const FunctionType *FTy =
2385 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2386 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2387 return Error(ID.Loc, "invalid type for inline asm constraint string");
Dale Johannesen43602982009-10-13 20:46:56 +00002388 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002389 return false;
Devang Patele54abc92009-07-22 17:43:22 +00002390 } else if (ID.Kind == ValID::t_Metadata) {
2391 V = ID.MetadataVal;
Chris Lattnerdf986172009-01-02 07:01:27 +00002392 } else {
2393 Constant *C;
2394 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2395 V = C;
2396 return false;
2397 }
2398
2399 return V == 0;
2400}
2401
2402bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2403 V = 0;
2404 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002405 return ParseValID(ID) ||
2406 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002407}
2408
2409bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002410 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002411 return ParseType(T) ||
2412 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002413}
2414
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002415bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2416 PerFunctionState &PFS) {
2417 Value *V;
2418 Loc = Lex.getLoc();
2419 if (ParseTypeAndValue(V, PFS)) return true;
2420 if (!isa<BasicBlock>(V))
2421 return Error(Loc, "expected a basic block");
2422 BB = cast<BasicBlock>(V);
2423 return false;
2424}
2425
2426
Chris Lattnerdf986172009-01-02 07:01:27 +00002427/// FunctionHeader
2428/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2429/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2430/// OptionalAlign OptGC
2431bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2432 // Parse the linkage.
2433 LocTy LinkageLoc = Lex.getLoc();
2434 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002435
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002436 unsigned Visibility, RetAttrs;
2437 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002438 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002439 LocTy RetTypeLoc = Lex.getLoc();
2440 if (ParseOptionalLinkage(Linkage) ||
2441 ParseOptionalVisibility(Visibility) ||
2442 ParseOptionalCallingConv(CC) ||
2443 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002444 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002445 return true;
2446
2447 // Verify that the linkage is ok.
2448 switch ((GlobalValue::LinkageTypes)Linkage) {
2449 case GlobalValue::ExternalLinkage:
2450 break; // always ok.
2451 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002452 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002453 if (isDefine)
2454 return Error(LinkageLoc, "invalid linkage for function definition");
2455 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002456 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002457 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002458 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002459 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002460 case GlobalValue::LinkOnceAnyLinkage:
2461 case GlobalValue::LinkOnceODRLinkage:
2462 case GlobalValue::WeakAnyLinkage:
2463 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002464 case GlobalValue::DLLExportLinkage:
2465 if (!isDefine)
2466 return Error(LinkageLoc, "invalid linkage for function declaration");
2467 break;
2468 case GlobalValue::AppendingLinkage:
2469 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002470 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002471 return Error(LinkageLoc, "invalid function linkage type");
2472 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002473
Chris Lattner99bb3152009-01-05 08:00:30 +00002474 if (!FunctionType::isValidReturnType(RetType) ||
2475 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002476 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002477
Chris Lattnerdf986172009-01-02 07:01:27 +00002478 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002479
2480 std::string FunctionName;
2481 if (Lex.getKind() == lltok::GlobalVar) {
2482 FunctionName = Lex.getStrVal();
2483 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2484 unsigned NameID = Lex.getUIntVal();
2485
2486 if (NameID != NumberedVals.size())
2487 return TokError("function expected to be numbered '%" +
2488 utostr(NumberedVals.size()) + "'");
2489 } else {
2490 return TokError("expected function name");
2491 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002492
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002493 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002494
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002495 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002496 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002497
Chris Lattnerdf986172009-01-02 07:01:27 +00002498 std::vector<ArgInfo> ArgList;
2499 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002500 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002501 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002502 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002503 std::string GC;
2504
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002505 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002506 ParseOptionalAttrs(FuncAttrs, 2) ||
2507 (EatIfPresent(lltok::kw_section) &&
2508 ParseStringConstant(Section)) ||
2509 ParseOptionalAlignment(Alignment) ||
2510 (EatIfPresent(lltok::kw_gc) &&
2511 ParseStringConstant(GC)))
2512 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002513
2514 // If the alignment was parsed as an attribute, move to the alignment field.
2515 if (FuncAttrs & Attribute::Alignment) {
2516 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2517 FuncAttrs &= ~Attribute::Alignment;
2518 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002519
Chris Lattnerdf986172009-01-02 07:01:27 +00002520 // Okay, if we got here, the function is syntactically valid. Convert types
2521 // and do semantic checks.
2522 std::vector<const Type*> ParamTypeList;
2523 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002524 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002525 // attributes.
2526 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2527 if (FuncAttrs & ObsoleteFuncAttrs) {
2528 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2529 FuncAttrs &= ~ObsoleteFuncAttrs;
2530 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002531
Chris Lattnerdf986172009-01-02 07:01:27 +00002532 if (RetAttrs != Attribute::None)
2533 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002534
Chris Lattnerdf986172009-01-02 07:01:27 +00002535 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2536 ParamTypeList.push_back(ArgList[i].Type);
2537 if (ArgList[i].Attrs != Attribute::None)
2538 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2539 }
2540
2541 if (FuncAttrs != Attribute::None)
2542 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2543
2544 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002545
Chris Lattnera9a9e072009-03-09 04:49:14 +00002546 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002547 RetType != Type::getVoidTy(Context))
Daniel Dunbara279bc32009-09-20 02:20:51 +00002548 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2549
Owen Andersonfba933c2009-07-01 23:57:11 +00002550 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002551 FunctionType::get(RetType, ParamTypeList, isVarArg);
2552 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002553
2554 Fn = 0;
2555 if (!FunctionName.empty()) {
2556 // If this was a definition of a forward reference, remove the definition
2557 // from the forward reference table and fill in the forward ref.
2558 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2559 ForwardRefVals.find(FunctionName);
2560 if (FRVI != ForwardRefVals.end()) {
2561 Fn = M->getFunction(FunctionName);
2562 ForwardRefVals.erase(FRVI);
2563 } else if ((Fn = M->getFunction(FunctionName))) {
2564 // If this function already exists in the symbol table, then it is
2565 // multiply defined. We accept a few cases for old backwards compat.
2566 // FIXME: Remove this stuff for LLVM 3.0.
2567 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2568 (!Fn->isDeclaration() && isDefine)) {
2569 // If the redefinition has different type or different attributes,
2570 // reject it. If both have bodies, reject it.
2571 return Error(NameLoc, "invalid redefinition of function '" +
2572 FunctionName + "'");
2573 } else if (Fn->isDeclaration()) {
2574 // Make sure to strip off any argument names so we can't get conflicts.
2575 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2576 AI != AE; ++AI)
2577 AI->setName("");
2578 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002579 } else if (M->getNamedValue(FunctionName)) {
2580 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002581 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002582
Dan Gohman41905542009-08-29 23:37:49 +00002583 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002584 // If this is a definition of a forward referenced function, make sure the
2585 // types agree.
2586 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2587 = ForwardRefValIDs.find(NumberedVals.size());
2588 if (I != ForwardRefValIDs.end()) {
2589 Fn = cast<Function>(I->second.first);
2590 if (Fn->getType() != PFT)
2591 return Error(NameLoc, "type of definition and forward reference of '@" +
2592 utostr(NumberedVals.size()) +"' disagree");
2593 ForwardRefValIDs.erase(I);
2594 }
2595 }
2596
2597 if (Fn == 0)
2598 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2599 else // Move the forward-reference to the correct spot in the module.
2600 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2601
2602 if (FunctionName.empty())
2603 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002604
Chris Lattnerdf986172009-01-02 07:01:27 +00002605 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2606 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2607 Fn->setCallingConv(CC);
2608 Fn->setAttributes(PAL);
2609 Fn->setAlignment(Alignment);
2610 Fn->setSection(Section);
2611 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002612
Chris Lattnerdf986172009-01-02 07:01:27 +00002613 // Add all of the arguments we parsed to the function.
2614 Function::arg_iterator ArgIt = Fn->arg_begin();
2615 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2616 // If the argument has a name, insert it into the argument symbol table.
2617 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002618
Chris Lattnerdf986172009-01-02 07:01:27 +00002619 // Set the name, if it conflicted, it will be auto-renamed.
2620 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002621
Chris Lattnerdf986172009-01-02 07:01:27 +00002622 if (ArgIt->getNameStr() != ArgList[i].Name)
2623 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2624 ArgList[i].Name + "'");
2625 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002626
Chris Lattnerdf986172009-01-02 07:01:27 +00002627 return false;
2628}
2629
2630
2631/// ParseFunctionBody
2632/// ::= '{' BasicBlock+ '}'
2633/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2634///
2635bool LLParser::ParseFunctionBody(Function &Fn) {
2636 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2637 return TokError("expected '{' in function body");
2638 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002639
Chris Lattnerdf986172009-01-02 07:01:27 +00002640 PerFunctionState PFS(*this, Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002641
Chris Lattnerdf986172009-01-02 07:01:27 +00002642 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2643 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002644
Chris Lattnerdf986172009-01-02 07:01:27 +00002645 // Eat the }.
2646 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002647
Chris Lattnerdf986172009-01-02 07:01:27 +00002648 // Verify function is ok.
2649 return PFS.VerifyFunctionComplete();
2650}
2651
2652/// ParseBasicBlock
2653/// ::= LabelStr? Instruction*
2654bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2655 // If this basic block starts out with a name, remember it.
2656 std::string Name;
2657 LocTy NameLoc = Lex.getLoc();
2658 if (Lex.getKind() == lltok::LabelStr) {
2659 Name = Lex.getStrVal();
2660 Lex.Lex();
2661 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002662
Chris Lattnerdf986172009-01-02 07:01:27 +00002663 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2664 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002665
Chris Lattnerdf986172009-01-02 07:01:27 +00002666 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002667
Chris Lattnerdf986172009-01-02 07:01:27 +00002668 // Parse the instructions in this block until we get a terminator.
2669 Instruction *Inst;
2670 do {
2671 // This instruction may have three possibilities for a name: a) none
2672 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2673 LocTy NameLoc = Lex.getLoc();
2674 int NameID = -1;
2675 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002676
Chris Lattnerdf986172009-01-02 07:01:27 +00002677 if (Lex.getKind() == lltok::LocalVarID) {
2678 NameID = Lex.getUIntVal();
2679 Lex.Lex();
2680 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2681 return true;
2682 } else if (Lex.getKind() == lltok::LocalVar ||
2683 // FIXME: REMOVE IN LLVM 3.0
2684 Lex.getKind() == lltok::StringConstant) {
2685 NameStr = Lex.getStrVal();
2686 Lex.Lex();
2687 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2688 return true;
2689 }
Devang Patelf633a062009-09-17 23:04:48 +00002690
Chris Lattnerdf986172009-01-02 07:01:27 +00002691 if (ParseInstruction(Inst, BB, PFS)) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002692 if (EatIfPresent(lltok::comma))
Devang Patel0475c912009-09-29 00:01:14 +00002693 ParseOptionalCustomMetadata();
Devang Patelf633a062009-09-17 23:04:48 +00002694
2695 // Set metadata attached with this instruction.
Devang Patele30e6782009-09-28 21:41:20 +00002696 MetadataContext &TheMetadata = M->getContext().getMetadata();
Devang Patela2148402009-09-28 21:14:55 +00002697 for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
Daniel Dunbara279bc32009-09-20 02:20:51 +00002698 MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
Devang Patel58a230a2009-09-29 20:30:57 +00002699 TheMetadata.addMD(MDI->first, MDI->second, Inst);
Devang Patelf633a062009-09-17 23:04:48 +00002700 MDsOnInst.clear();
2701
Chris Lattnerdf986172009-01-02 07:01:27 +00002702 BB->getInstList().push_back(Inst);
2703
2704 // Set the name on the instruction.
2705 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2706 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002707
Chris Lattnerdf986172009-01-02 07:01:27 +00002708 return false;
2709}
2710
2711//===----------------------------------------------------------------------===//
2712// Instruction Parsing.
2713//===----------------------------------------------------------------------===//
2714
2715/// ParseInstruction - Parse one of the many different instructions.
2716///
2717bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2718 PerFunctionState &PFS) {
2719 lltok::Kind Token = Lex.getKind();
2720 if (Token == lltok::Eof)
2721 return TokError("found end of file when expecting more instructions");
2722 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002723 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002724 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002725
Chris Lattnerdf986172009-01-02 07:01:27 +00002726 switch (Token) {
2727 default: return Error(Loc, "expected instruction opcode");
2728 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002729 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2730 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002731 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2732 case lltok::kw_br: return ParseBr(Inst, PFS);
2733 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002734 case lltok::kw_indbr: return ParseIndBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002735 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2736 // Binary Operators.
2737 case lltok::kw_add:
2738 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002739 case lltok::kw_mul: {
2740 bool NUW = false;
2741 bool NSW = false;
2742 LocTy ModifierLoc = Lex.getLoc();
2743 if (EatIfPresent(lltok::kw_nuw))
2744 NUW = true;
2745 if (EatIfPresent(lltok::kw_nsw)) {
2746 NSW = true;
2747 if (EatIfPresent(lltok::kw_nuw))
2748 NUW = true;
2749 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002750 // API compatibility: Accept either integer or floating-point types.
Dan Gohman59858cf2009-07-27 16:11:46 +00002751 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2752 if (!Result) {
2753 if (!Inst->getType()->isIntOrIntVector()) {
2754 if (NUW)
2755 return Error(ModifierLoc, "nuw only applies to integer operations");
2756 if (NSW)
2757 return Error(ModifierLoc, "nsw only applies to integer operations");
2758 }
2759 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002760 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002761 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002762 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002763 }
2764 return Result;
2765 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002766 case lltok::kw_fadd:
2767 case lltok::kw_fsub:
2768 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2769
Dan Gohman59858cf2009-07-27 16:11:46 +00002770 case lltok::kw_sdiv: {
2771 bool Exact = false;
2772 if (EatIfPresent(lltok::kw_exact))
2773 Exact = true;
2774 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2775 if (!Result)
2776 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002777 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002778 return Result;
2779 }
2780
Chris Lattnerdf986172009-01-02 07:01:27 +00002781 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002782 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002783 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002784 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002785 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002786 case lltok::kw_shl:
2787 case lltok::kw_lshr:
2788 case lltok::kw_ashr:
2789 case lltok::kw_and:
2790 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002791 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002792 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002793 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002794 // Casts.
2795 case lltok::kw_trunc:
2796 case lltok::kw_zext:
2797 case lltok::kw_sext:
2798 case lltok::kw_fptrunc:
2799 case lltok::kw_fpext:
2800 case lltok::kw_bitcast:
2801 case lltok::kw_uitofp:
2802 case lltok::kw_sitofp:
2803 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002804 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002805 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002806 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002807 // Other.
2808 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002809 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002810 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2811 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2812 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2813 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2814 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2815 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2816 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002817 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2818 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00002819 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00002820 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2821 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2822 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002823 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002824 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002825 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002826 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002827 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002828 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002829 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2830 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2831 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2832 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2833 }
2834}
2835
2836/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2837bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002838 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002839 switch (Lex.getKind()) {
2840 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2841 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2842 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2843 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2844 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2845 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2846 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2847 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2848 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2849 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2850 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2851 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2852 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2853 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2854 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2855 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2856 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2857 }
2858 } else {
2859 switch (Lex.getKind()) {
2860 default: TokError("expected icmp predicate (e.g. 'eq')");
2861 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2862 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2863 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2864 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2865 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2866 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2867 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2868 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2869 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2870 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2871 }
2872 }
2873 Lex.Lex();
2874 return false;
2875}
2876
2877//===----------------------------------------------------------------------===//
2878// Terminator Instructions.
2879//===----------------------------------------------------------------------===//
2880
2881/// ParseRet - Parse a return instruction.
Devang Patel0475c912009-09-29 00:01:14 +00002882/// ::= 'ret' void (',' !dbg, !1)
2883/// ::= 'ret' TypeAndValue (',' !dbg, !1)
2884/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)
Devang Patelf633a062009-09-17 23:04:48 +00002885/// [[obsolete: LLVM 3.0]]
Chris Lattnerdf986172009-01-02 07:01:27 +00002886bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2887 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002888 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00002889 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002890
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002891 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002892 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002893 return false;
2894 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002895
Chris Lattnerdf986172009-01-02 07:01:27 +00002896 Value *RV;
2897 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002898
Devang Patelf633a062009-09-17 23:04:48 +00002899 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00002900 // Parse optional custom metadata, e.g. !dbg
2901 if (Lex.getKind() == lltok::NamedOrCustomMD) {
2902 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002903 } else {
2904 // The normal case is one return value.
2905 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2906 // of 'ret {i32,i32} {i32 1, i32 2}'
2907 SmallVector<Value*, 8> RVs;
2908 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002909
Devang Patelf633a062009-09-17 23:04:48 +00002910 do {
Devang Patel0475c912009-09-29 00:01:14 +00002911 // If optional custom metadata, e.g. !dbg is seen then this is the
2912 // end of MRV.
2913 if (Lex.getKind() == lltok::NamedOrCustomMD)
Daniel Dunbara279bc32009-09-20 02:20:51 +00002914 break;
2915 if (ParseTypeAndValue(RV, PFS)) return true;
2916 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00002917 } while (EatIfPresent(lltok::comma));
2918
2919 RV = UndefValue::get(PFS.getFunction().getReturnType());
2920 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002921 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2922 BB->getInstList().push_back(I);
2923 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00002924 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002925 }
2926 }
Devang Patelf633a062009-09-17 23:04:48 +00002927
Owen Anderson1d0be152009-08-13 21:58:54 +00002928 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerdf986172009-01-02 07:01:27 +00002929 return false;
2930}
2931
2932
2933/// ParseBr
2934/// ::= 'br' TypeAndValue
2935/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2936bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2937 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002938 Value *Op0;
2939 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00002940 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002941
Chris Lattnerdf986172009-01-02 07:01:27 +00002942 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2943 Inst = BranchInst::Create(BB);
2944 return false;
2945 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002946
Owen Anderson1d0be152009-08-13 21:58:54 +00002947 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00002948 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002949
Chris Lattnerdf986172009-01-02 07:01:27 +00002950 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002951 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002952 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002953 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00002954 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002955
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002956 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002957 return false;
2958}
2959
2960/// ParseSwitch
2961/// Instruction
2962/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2963/// JumpTable
2964/// ::= (TypeAndValue ',' TypeAndValue)*
2965bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2966 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002967 Value *Cond;
2968 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00002969 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2970 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002971 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002972 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2973 return true;
2974
2975 if (!isa<IntegerType>(Cond->getType()))
2976 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002977
Chris Lattnerdf986172009-01-02 07:01:27 +00002978 // Parse the jump table pairs.
2979 SmallPtrSet<Value*, 32> SeenCases;
2980 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2981 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002982 Value *Constant;
2983 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002984
Chris Lattnerdf986172009-01-02 07:01:27 +00002985 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2986 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002987 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00002988 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002989
Chris Lattnerdf986172009-01-02 07:01:27 +00002990 if (!SeenCases.insert(Constant))
2991 return Error(CondLoc, "duplicate case value in switch");
2992 if (!isa<ConstantInt>(Constant))
2993 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002994
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002995 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00002996 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002997
Chris Lattnerdf986172009-01-02 07:01:27 +00002998 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002999
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003000 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003001 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3002 SI->addCase(Table[i].first, Table[i].second);
3003 Inst = SI;
3004 return false;
3005}
3006
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003007/// ParseIndBr
3008/// Instruction
3009/// ::= 'indbr' TypeAndValue ',' '[' LabelList ']'
3010bool LLParser::ParseIndBr(Instruction *&Inst, PerFunctionState &PFS) {
3011 LocTy AddrLoc;
3012 Value *Address;
3013 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3014 ParseToken(lltok::comma, "expected ',' after indbr address") ||
3015 ParseToken(lltok::lsquare, "expected '[' with indbr"))
3016 return true;
3017
3018 if (!isa<PointerType>(Address->getType()))
3019 return Error(AddrLoc, "indbr address must have pointer type");
3020
3021 // Parse the destination list.
3022 SmallVector<BasicBlock*, 16> DestList;
3023
3024 if (Lex.getKind() != lltok::rsquare) {
3025 BasicBlock *DestBB;
3026 if (ParseTypeAndBasicBlock(DestBB, PFS))
3027 return true;
3028 DestList.push_back(DestBB);
3029
3030 while (EatIfPresent(lltok::comma)) {
3031 if (ParseTypeAndBasicBlock(DestBB, PFS))
3032 return true;
3033 DestList.push_back(DestBB);
3034 }
3035 }
3036
3037 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3038 return true;
3039
3040 IndBrInst *IBI = IndBrInst::Create(Address, DestList.size());
3041 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3042 IBI->addDestination(DestList[i]);
3043 Inst = IBI;
3044 return false;
3045}
3046
3047
Chris Lattnerdf986172009-01-02 07:01:27 +00003048/// ParseInvoke
3049/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3050/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3051bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3052 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003053 unsigned RetAttrs, FnAttrs;
3054 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003055 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003056 LocTy RetTypeLoc;
3057 ValID CalleeID;
3058 SmallVector<ParamInfo, 16> ArgList;
3059
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003060 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003061 if (ParseOptionalCallingConv(CC) ||
3062 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003063 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003064 ParseValID(CalleeID) ||
3065 ParseParameterList(ArgList, PFS) ||
3066 ParseOptionalAttrs(FnAttrs, 2) ||
3067 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003068 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003069 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003070 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003071 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003072
Chris Lattnerdf986172009-01-02 07:01:27 +00003073 // If RetType is a non-function pointer type, then this is the short syntax
3074 // for the call, which means that RetType is just the return type. Infer the
3075 // rest of the function argument types from the arguments that are present.
3076 const PointerType *PFTy = 0;
3077 const FunctionType *Ty = 0;
3078 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3079 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3080 // Pull out the types of all of the arguments...
3081 std::vector<const Type*> ParamTypes;
3082 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3083 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003084
Chris Lattnerdf986172009-01-02 07:01:27 +00003085 if (!FunctionType::isValidReturnType(RetType))
3086 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003087
Owen Andersondebcb012009-07-29 22:17:13 +00003088 Ty = FunctionType::get(RetType, ParamTypes, false);
3089 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003090 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003091
Chris Lattnerdf986172009-01-02 07:01:27 +00003092 // Look up the callee.
3093 Value *Callee;
3094 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003095
Chris Lattnerdf986172009-01-02 07:01:27 +00003096 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3097 // function attributes.
3098 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3099 if (FnAttrs & ObsoleteFuncAttrs) {
3100 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3101 FnAttrs &= ~ObsoleteFuncAttrs;
3102 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003103
Chris Lattnerdf986172009-01-02 07:01:27 +00003104 // Set up the Attributes for the function.
3105 SmallVector<AttributeWithIndex, 8> Attrs;
3106 if (RetAttrs != Attribute::None)
3107 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003108
Chris Lattnerdf986172009-01-02 07:01:27 +00003109 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003110
Chris Lattnerdf986172009-01-02 07:01:27 +00003111 // Loop through FunctionType's arguments and ensure they are specified
3112 // correctly. Also, gather any parameter attributes.
3113 FunctionType::param_iterator I = Ty->param_begin();
3114 FunctionType::param_iterator E = Ty->param_end();
3115 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3116 const Type *ExpectedTy = 0;
3117 if (I != E) {
3118 ExpectedTy = *I++;
3119 } else if (!Ty->isVarArg()) {
3120 return Error(ArgList[i].Loc, "too many arguments specified");
3121 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003122
Chris Lattnerdf986172009-01-02 07:01:27 +00003123 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3124 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3125 ExpectedTy->getDescription() + "'");
3126 Args.push_back(ArgList[i].V);
3127 if (ArgList[i].Attrs != Attribute::None)
3128 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3129 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003130
Chris Lattnerdf986172009-01-02 07:01:27 +00003131 if (I != E)
3132 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003133
Chris Lattnerdf986172009-01-02 07:01:27 +00003134 if (FnAttrs != Attribute::None)
3135 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003136
Chris Lattnerdf986172009-01-02 07:01:27 +00003137 // Finish off the Attributes and check them
3138 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003139
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003140 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003141 Args.begin(), Args.end());
3142 II->setCallingConv(CC);
3143 II->setAttributes(PAL);
3144 Inst = II;
3145 return false;
3146}
3147
3148
3149
3150//===----------------------------------------------------------------------===//
3151// Binary Operators.
3152//===----------------------------------------------------------------------===//
3153
3154/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003155/// ::= ArithmeticOps TypeAndValue ',' Value
3156///
3157/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3158/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003159bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003160 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003161 LocTy Loc; Value *LHS, *RHS;
3162 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3163 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3164 ParseValue(LHS->getType(), RHS, PFS))
3165 return true;
3166
Chris Lattnere914b592009-01-05 08:24:46 +00003167 bool Valid;
3168 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003169 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003170 case 0: // int or FP.
3171 Valid = LHS->getType()->isIntOrIntVector() ||
3172 LHS->getType()->isFPOrFPVector();
3173 break;
3174 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3175 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3176 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003177
Chris Lattnere914b592009-01-05 08:24:46 +00003178 if (!Valid)
3179 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003180
Chris Lattnerdf986172009-01-02 07:01:27 +00003181 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3182 return false;
3183}
3184
3185/// ParseLogical
3186/// ::= ArithmeticOps TypeAndValue ',' Value {
3187bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3188 unsigned Opc) {
3189 LocTy Loc; Value *LHS, *RHS;
3190 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3191 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3192 ParseValue(LHS->getType(), RHS, PFS))
3193 return true;
3194
3195 if (!LHS->getType()->isIntOrIntVector())
3196 return Error(Loc,"instruction requires integer or integer vector operands");
3197
3198 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3199 return false;
3200}
3201
3202
3203/// ParseCompare
3204/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3205/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003206bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3207 unsigned Opc) {
3208 // Parse the integer/fp comparison predicate.
3209 LocTy Loc;
3210 unsigned Pred;
3211 Value *LHS, *RHS;
3212 if (ParseCmpPredicate(Pred, Opc) ||
3213 ParseTypeAndValue(LHS, Loc, PFS) ||
3214 ParseToken(lltok::comma, "expected ',' after compare value") ||
3215 ParseValue(LHS->getType(), RHS, PFS))
3216 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003217
Chris Lattnerdf986172009-01-02 07:01:27 +00003218 if (Opc == Instruction::FCmp) {
3219 if (!LHS->getType()->isFPOrFPVector())
3220 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003221 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003222 } else {
3223 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00003224 if (!LHS->getType()->isIntOrIntVector() &&
3225 !isa<PointerType>(LHS->getType()))
3226 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003227 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003228 }
3229 return false;
3230}
3231
3232//===----------------------------------------------------------------------===//
3233// Other Instructions.
3234//===----------------------------------------------------------------------===//
3235
3236
3237/// ParseCast
3238/// ::= CastOpc TypeAndValue 'to' Type
3239bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3240 unsigned Opc) {
3241 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003242 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003243 if (ParseTypeAndValue(Op, Loc, PFS) ||
3244 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3245 ParseType(DestTy))
3246 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003247
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003248 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3249 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003250 return Error(Loc, "invalid cast opcode for cast from '" +
3251 Op->getType()->getDescription() + "' to '" +
3252 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003253 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003254 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3255 return false;
3256}
3257
3258/// ParseSelect
3259/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3260bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3261 LocTy Loc;
3262 Value *Op0, *Op1, *Op2;
3263 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3264 ParseToken(lltok::comma, "expected ',' after select condition") ||
3265 ParseTypeAndValue(Op1, PFS) ||
3266 ParseToken(lltok::comma, "expected ',' after select value") ||
3267 ParseTypeAndValue(Op2, PFS))
3268 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003269
Chris Lattnerdf986172009-01-02 07:01:27 +00003270 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3271 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003272
Chris Lattnerdf986172009-01-02 07:01:27 +00003273 Inst = SelectInst::Create(Op0, Op1, Op2);
3274 return false;
3275}
3276
Chris Lattner0088a5c2009-01-05 08:18:44 +00003277/// ParseVA_Arg
3278/// ::= 'va_arg' TypeAndValue ',' Type
3279bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003280 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003281 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003282 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003283 if (ParseTypeAndValue(Op, PFS) ||
3284 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003285 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003286 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003287
Chris Lattner0088a5c2009-01-05 08:18:44 +00003288 if (!EltTy->isFirstClassType())
3289 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003290
3291 Inst = new VAArgInst(Op, EltTy);
3292 return false;
3293}
3294
3295/// ParseExtractElement
3296/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3297bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3298 LocTy Loc;
3299 Value *Op0, *Op1;
3300 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3301 ParseToken(lltok::comma, "expected ',' after extract value") ||
3302 ParseTypeAndValue(Op1, PFS))
3303 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003304
Chris Lattnerdf986172009-01-02 07:01:27 +00003305 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3306 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003307
Eric Christophera3500da2009-07-25 02:28:41 +00003308 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003309 return false;
3310}
3311
3312/// ParseInsertElement
3313/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3314bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3315 LocTy Loc;
3316 Value *Op0, *Op1, *Op2;
3317 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3318 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3319 ParseTypeAndValue(Op1, PFS) ||
3320 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3321 ParseTypeAndValue(Op2, PFS))
3322 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003323
Chris Lattnerdf986172009-01-02 07:01:27 +00003324 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003325 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003326
Chris Lattnerdf986172009-01-02 07:01:27 +00003327 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3328 return false;
3329}
3330
3331/// ParseShuffleVector
3332/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3333bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3334 LocTy Loc;
3335 Value *Op0, *Op1, *Op2;
3336 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3337 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3338 ParseTypeAndValue(Op1, PFS) ||
3339 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3340 ParseTypeAndValue(Op2, PFS))
3341 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003342
Chris Lattnerdf986172009-01-02 07:01:27 +00003343 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3344 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003345
Chris Lattnerdf986172009-01-02 07:01:27 +00003346 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3347 return false;
3348}
3349
3350/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003351/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerdf986172009-01-02 07:01:27 +00003352bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003353 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003354 Value *Op0, *Op1;
3355 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003356
Chris Lattnerdf986172009-01-02 07:01:27 +00003357 if (ParseType(Ty) ||
3358 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3359 ParseValue(Ty, Op0, PFS) ||
3360 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003361 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003362 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3363 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003364
Chris Lattnerdf986172009-01-02 07:01:27 +00003365 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3366 while (1) {
3367 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003368
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003369 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003370 break;
3371
Devang Patela43d46f2009-10-16 18:45:49 +00003372 if (Lex.getKind() == lltok::NamedOrCustomMD)
3373 break;
3374
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003375 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003376 ParseValue(Ty, Op0, PFS) ||
3377 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003378 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003379 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3380 return true;
3381 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003382
Devang Patela43d46f2009-10-16 18:45:49 +00003383 if (Lex.getKind() == lltok::NamedOrCustomMD)
3384 if (ParseOptionalCustomMetadata()) return true;
3385
Chris Lattnerdf986172009-01-02 07:01:27 +00003386 if (!Ty->isFirstClassType())
3387 return Error(TypeLoc, "phi node must have first class type");
3388
3389 PHINode *PN = PHINode::Create(Ty);
3390 PN->reserveOperandSpace(PHIVals.size());
3391 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3392 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3393 Inst = PN;
3394 return false;
3395}
3396
3397/// ParseCall
3398/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3399/// ParameterList OptionalAttrs
3400bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3401 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003402 unsigned RetAttrs, FnAttrs;
3403 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003404 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003405 LocTy RetTypeLoc;
3406 ValID CalleeID;
3407 SmallVector<ParamInfo, 16> ArgList;
3408 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003409
Chris Lattnerdf986172009-01-02 07:01:27 +00003410 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3411 ParseOptionalCallingConv(CC) ||
3412 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003413 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003414 ParseValID(CalleeID) ||
3415 ParseParameterList(ArgList, PFS) ||
3416 ParseOptionalAttrs(FnAttrs, 2))
3417 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003418
Chris Lattnerdf986172009-01-02 07:01:27 +00003419 // If RetType is a non-function pointer type, then this is the short syntax
3420 // for the call, which means that RetType is just the return type. Infer the
3421 // rest of the function argument types from the arguments that are present.
3422 const PointerType *PFTy = 0;
3423 const FunctionType *Ty = 0;
3424 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3425 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3426 // Pull out the types of all of the arguments...
3427 std::vector<const Type*> ParamTypes;
3428 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3429 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003430
Chris Lattnerdf986172009-01-02 07:01:27 +00003431 if (!FunctionType::isValidReturnType(RetType))
3432 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003433
Owen Andersondebcb012009-07-29 22:17:13 +00003434 Ty = FunctionType::get(RetType, ParamTypes, false);
3435 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003436 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003437
Chris Lattnerdf986172009-01-02 07:01:27 +00003438 // Look up the callee.
3439 Value *Callee;
3440 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003441
Chris Lattnerdf986172009-01-02 07:01:27 +00003442 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3443 // function attributes.
3444 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3445 if (FnAttrs & ObsoleteFuncAttrs) {
3446 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3447 FnAttrs &= ~ObsoleteFuncAttrs;
3448 }
3449
3450 // Set up the Attributes for the function.
3451 SmallVector<AttributeWithIndex, 8> Attrs;
3452 if (RetAttrs != Attribute::None)
3453 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003454
Chris Lattnerdf986172009-01-02 07:01:27 +00003455 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003456
Chris Lattnerdf986172009-01-02 07:01:27 +00003457 // Loop through FunctionType's arguments and ensure they are specified
3458 // correctly. Also, gather any parameter attributes.
3459 FunctionType::param_iterator I = Ty->param_begin();
3460 FunctionType::param_iterator E = Ty->param_end();
3461 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3462 const Type *ExpectedTy = 0;
3463 if (I != E) {
3464 ExpectedTy = *I++;
3465 } else if (!Ty->isVarArg()) {
3466 return Error(ArgList[i].Loc, "too many arguments specified");
3467 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003468
Chris Lattnerdf986172009-01-02 07:01:27 +00003469 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3470 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3471 ExpectedTy->getDescription() + "'");
3472 Args.push_back(ArgList[i].V);
3473 if (ArgList[i].Attrs != Attribute::None)
3474 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3475 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003476
Chris Lattnerdf986172009-01-02 07:01:27 +00003477 if (I != E)
3478 return Error(CallLoc, "not enough parameters specified for call");
3479
3480 if (FnAttrs != Attribute::None)
3481 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3482
3483 // Finish off the Attributes and check them
3484 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003485
Chris Lattnerdf986172009-01-02 07:01:27 +00003486 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3487 CI->setTailCall(isTail);
3488 CI->setCallingConv(CC);
3489 CI->setAttributes(PAL);
3490 Inst = CI;
3491 return false;
3492}
3493
3494//===----------------------------------------------------------------------===//
3495// Memory Instructions.
3496//===----------------------------------------------------------------------===//
3497
3498/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003499/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3500/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003501bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003502 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003503 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003504 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003505 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003506 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003507 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003508
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003509 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003510 if (Lex.getKind() == lltok::kw_align
3511 || Lex.getKind() == lltok::NamedOrCustomMD) {
Devang Patelf633a062009-09-17 23:04:48 +00003512 if (ParseOptionalInfo(Alignment)) return true;
3513 } else {
3514 if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3515 if (EatIfPresent(lltok::comma))
Daniel Dunbara279bc32009-09-20 02:20:51 +00003516 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003517 }
3518 }
3519
Owen Anderson1d0be152009-08-13 21:58:54 +00003520 if (Size && Size->getType() != Type::getInt32Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003521 return Error(SizeLoc, "element count must be i32");
3522
Victor Hernandez68afa542009-10-21 19:11:40 +00003523 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003524 Inst = new AllocaInst(Ty, Size, Alignment);
Victor Hernandez68afa542009-10-21 19:11:40 +00003525 return false;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003526 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003527
3528 // Autoupgrade old malloc instruction to malloc call.
3529 // FIXME: Remove in LLVM 3.0.
3530 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez68afa542009-10-21 19:11:40 +00003531 if (!MallocF)
3532 // Prototype malloc as "void *(int32)".
3533 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003534 MallocF = cast<Function>(
3535 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez68afa542009-10-21 19:11:40 +00003536 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, Size, MallocF);
Chris Lattnerdf986172009-01-02 07:01:27 +00003537 return false;
3538}
3539
3540/// ParseFree
3541/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003542bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3543 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003544 Value *Val; LocTy Loc;
3545 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3546 if (!isa<PointerType>(Val->getType()))
3547 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003548 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003549 return false;
3550}
3551
3552/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003553/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003554bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3555 bool isVolatile) {
3556 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003557 unsigned Alignment = 0;
3558 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003559
Devang Patelf633a062009-09-17 23:04:48 +00003560 if (EatIfPresent(lltok::comma))
3561 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003562
3563 if (!isa<PointerType>(Val->getType()) ||
3564 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3565 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003566
Chris Lattnerdf986172009-01-02 07:01:27 +00003567 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3568 return false;
3569}
3570
3571/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003572/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003573bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3574 bool isVolatile) {
3575 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003576 unsigned Alignment = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003577 if (ParseTypeAndValue(Val, Loc, PFS) ||
3578 ParseToken(lltok::comma, "expected ',' after store operand") ||
Devang Patelf633a062009-09-17 23:04:48 +00003579 ParseTypeAndValue(Ptr, PtrLoc, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003580 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003581
3582 if (EatIfPresent(lltok::comma))
3583 if (ParseOptionalInfo(Alignment)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003584
Chris Lattnerdf986172009-01-02 07:01:27 +00003585 if (!isa<PointerType>(Ptr->getType()))
3586 return Error(PtrLoc, "store operand must be a pointer");
3587 if (!Val->getType()->isFirstClassType())
3588 return Error(Loc, "store operand must be a first class value");
3589 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3590 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003591
Chris Lattnerdf986172009-01-02 07:01:27 +00003592 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3593 return false;
3594}
3595
3596/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003597/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003598/// FIXME: Remove support for getresult in LLVM 3.0
3599bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3600 Value *Val; LocTy ValLoc, EltLoc;
3601 unsigned Element;
3602 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3603 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003604 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003605 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003606
Chris Lattnerdf986172009-01-02 07:01:27 +00003607 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3608 return Error(ValLoc, "getresult inst requires an aggregate operand");
3609 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3610 return Error(EltLoc, "invalid getresult index for value");
3611 Inst = ExtractValueInst::Create(Val, Element);
3612 return false;
3613}
3614
3615/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003616/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00003617bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3618 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003619
Dan Gohmandcb40a32009-07-29 15:58:36 +00003620 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003621
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003622 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003623
Chris Lattnerdf986172009-01-02 07:01:27 +00003624 if (!isa<PointerType>(Ptr->getType()))
3625 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003626
Chris Lattnerdf986172009-01-02 07:01:27 +00003627 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003628 while (EatIfPresent(lltok::comma)) {
Devang Patel6225d642009-10-13 18:49:55 +00003629 if (Lex.getKind() == lltok::NamedOrCustomMD)
3630 break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003631 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003632 if (!isa<IntegerType>(Val->getType()))
3633 return Error(EltLoc, "getelementptr index must be an integer");
3634 Indices.push_back(Val);
3635 }
Devang Patel6225d642009-10-13 18:49:55 +00003636 if (Lex.getKind() == lltok::NamedOrCustomMD)
3637 if (ParseOptionalCustomMetadata()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003638
Chris Lattnerdf986172009-01-02 07:01:27 +00003639 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3640 Indices.begin(), Indices.end()))
3641 return Error(Loc, "invalid getelementptr indices");
3642 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003643 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003644 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00003645 return false;
3646}
3647
3648/// ParseExtractValue
3649/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3650bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3651 Value *Val; LocTy Loc;
3652 SmallVector<unsigned, 4> Indices;
3653 if (ParseTypeAndValue(Val, Loc, PFS) ||
3654 ParseIndexList(Indices))
3655 return true;
3656
3657 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3658 return Error(Loc, "extractvalue operand must be array or struct");
3659
3660 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3661 Indices.end()))
3662 return Error(Loc, "invalid indices for extractvalue");
3663 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3664 return false;
3665}
3666
3667/// ParseInsertValue
3668/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3669bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3670 Value *Val0, *Val1; LocTy Loc0, Loc1;
3671 SmallVector<unsigned, 4> Indices;
3672 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3673 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3674 ParseTypeAndValue(Val1, Loc1, PFS) ||
3675 ParseIndexList(Indices))
3676 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003677
Chris Lattnerdf986172009-01-02 07:01:27 +00003678 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3679 return Error(Loc0, "extractvalue operand must be array or struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003680
Chris Lattnerdf986172009-01-02 07:01:27 +00003681 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3682 Indices.end()))
3683 return Error(Loc0, "invalid indices for insertvalue");
3684 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3685 return false;
3686}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003687
3688//===----------------------------------------------------------------------===//
3689// Embedded metadata.
3690//===----------------------------------------------------------------------===//
3691
3692/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003693/// ::= Element (',' Element)*
3694/// Element
3695/// ::= 'null' | TypeAndValue
3696bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003697 assert(Lex.getKind() == lltok::lbrace);
3698 Lex.Lex();
3699 do {
Devang Pateldb5e9002009-07-23 01:36:16 +00003700 Value *V = 0;
Nick Lewyckycb337992009-05-10 20:57:05 +00003701 if (Lex.getKind() == lltok::kw_null) {
3702 Lex.Lex();
3703 V = 0;
3704 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00003705 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patele54abc92009-07-22 17:43:22 +00003706 if (ParseType(Ty)) return true;
3707 if (Lex.getKind() == lltok::Metadata) {
3708 Lex.Lex();
Devang Patel104cf9e2009-07-23 01:07:34 +00003709 MetadataBase *Node = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003710 if (!ParseMDNode(Node))
3711 V = Node;
3712 else {
3713 MetadataBase *MDS = 0;
3714 if (ParseMDString(MDS)) return true;
3715 V = MDS;
3716 }
3717 } else {
3718 Constant *C;
3719 if (ParseGlobalValue(Ty, C)) return true;
3720 V = C;
3721 }
Nick Lewyckycb337992009-05-10 20:57:05 +00003722 }
3723 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003724 } while (EatIfPresent(lltok::comma));
3725
3726 return false;
3727}