blob: db2a5a92ab925fb8932d03966fbc1139431c846d [file] [log] [blame]
Chris Lattnerdf986172009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
15#include "llvm/AutoUpgrade.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/InlineAsm.h"
20#include "llvm/Instructions.h"
21#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000022#include "llvm/Operator.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000023#include "llvm/ValueSymbolTable.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/StringExtras.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000026#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000027#include "llvm/Support/raw_ostream.h"
28using namespace llvm;
29
Chris Lattner3ed88ef2009-01-02 08:05:26 +000030/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000031bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000032 // Prime the lexer.
33 Lex.Lex();
34
Chris Lattnerad7d1e22009-01-04 20:44:11 +000035 return ParseTopLevelEntities() ||
36 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000037}
38
39/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
40/// module.
41bool LLParser::ValidateEndOfModule() {
Victor Hernandez68afa542009-10-21 19:11:40 +000042 // Update auto-upgraded malloc calls to "malloc".
Chris Lattnercf4d2f12009-10-18 05:09:15 +000043 // FIXME: Remove in LLVM 3.0.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000044 if (MallocF) {
45 MallocF->setName("malloc");
46 // If setName() does not set the name to "malloc", then there is already a
47 // declaration of "malloc". In that case, iterate over all calls to MallocF
48 // and get them to call the declared "malloc" instead.
49 if (MallocF->getName() != "malloc") {
Chris Lattner09d9ef42009-10-28 03:39:23 +000050 Constant *RealMallocF = M->getFunction("malloc");
Victor Hernandez68afa542009-10-21 19:11:40 +000051 if (RealMallocF->getType() != MallocF->getType())
52 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
53 MallocF->replaceAllUsesWith(RealMallocF);
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000054 MallocF->eraseFromParent();
55 MallocF = NULL;
56 }
57 }
Chris Lattner09d9ef42009-10-28 03:39:23 +000058
59
60 // If there are entries in ForwardRefBlockAddresses at this point, they are
61 // references after the function was defined. Resolve those now.
62 while (!ForwardRefBlockAddresses.empty()) {
63 // Okay, we are referencing an already-parsed function, resolve them now.
64 Function *TheFn = 0;
65 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
66 if (Fn.Kind == ValID::t_GlobalName)
67 TheFn = M->getFunction(Fn.StrVal);
68 else if (Fn.UIntVal < NumberedVals.size())
69 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
70
71 if (TheFn == 0)
72 return Error(Fn.Loc, "unknown function referenced by blockaddress");
73
74 // Resolve all these references.
75 if (ResolveForwardRefBlockAddresses(TheFn,
76 ForwardRefBlockAddresses.begin()->second,
77 0))
78 return true;
79
80 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
81 }
82
83
Chris Lattnerdf986172009-01-02 07:01:27 +000084 if (!ForwardRefTypes.empty())
85 return Error(ForwardRefTypes.begin()->second.second,
86 "use of undefined type named '" +
87 ForwardRefTypes.begin()->first + "'");
88 if (!ForwardRefTypeIDs.empty())
89 return Error(ForwardRefTypeIDs.begin()->second.second,
90 "use of undefined type '%" +
91 utostr(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +000092
Chris Lattnerdf986172009-01-02 07:01:27 +000093 if (!ForwardRefVals.empty())
94 return Error(ForwardRefVals.begin()->second.second,
95 "use of undefined value '@" + ForwardRefVals.begin()->first +
96 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +000097
Chris Lattnerdf986172009-01-02 07:01:27 +000098 if (!ForwardRefValIDs.empty())
99 return Error(ForwardRefValIDs.begin()->second.second,
100 "use of undefined value '@" +
101 utostr(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000102
Devang Patel1c7eea62009-07-08 19:23:54 +0000103 if (!ForwardRefMDNodes.empty())
104 return Error(ForwardRefMDNodes.begin()->second.second,
105 "use of undefined metadata '!" +
106 utostr(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000107
Devang Patel1c7eea62009-07-08 19:23:54 +0000108
Chris Lattnerdf986172009-01-02 07:01:27 +0000109 // Look for intrinsic functions and CallInst that need to be upgraded
110 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
111 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000112
Devang Patele4b27562009-08-28 23:24:31 +0000113 // Check debug info intrinsics.
114 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000115 return false;
116}
117
Chris Lattner09d9ef42009-10-28 03:39:23 +0000118bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
119 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
120 PerFunctionState *PFS) {
121 // Loop over all the references, resolving them.
122 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
123 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000124 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000125 if (Refs[i].first.Kind == ValID::t_LocalName)
126 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000127 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000128 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
129 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
130 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000131 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000132 } else {
133 Res = dyn_cast_or_null<BasicBlock>(
134 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
135 }
136
Chris Lattnercdfc9402009-11-01 01:27:45 +0000137 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000138 return Error(Refs[i].first.Loc,
139 "referenced value is not a basic block");
140
141 // Get the BlockAddress for this and update references to use it.
142 BlockAddress *BA = BlockAddress::get(TheFn, Res);
143 Refs[i].second->replaceAllUsesWith(BA);
144 Refs[i].second->eraseFromParent();
145 }
146 return false;
147}
148
149
Chris Lattnerdf986172009-01-02 07:01:27 +0000150//===----------------------------------------------------------------------===//
151// Top-Level Entities
152//===----------------------------------------------------------------------===//
153
154bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000155 while (1) {
156 switch (Lex.getKind()) {
157 default: return TokError("expected top-level entity");
158 case lltok::Eof: return false;
159 //case lltok::kw_define:
160 case lltok::kw_declare: if (ParseDeclare()) return true; break;
161 case lltok::kw_define: if (ParseDefine()) return true; break;
162 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
163 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
164 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
165 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000166 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000167 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
168 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000169 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000170 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Devang Patel923078c2009-07-01 19:21:12 +0000171 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
Devang Patel0475c912009-09-29 00:01:14 +0000172 case lltok::NamedOrCustomMD: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000173
174 // The Global variable production with no name can have many different
175 // optional leading prefixes, the production is:
176 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
177 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000178 case lltok::kw_private : // OptionalLinkage
179 case lltok::kw_linker_private: // OptionalLinkage
180 case lltok::kw_internal: // OptionalLinkage
181 case lltok::kw_weak: // OptionalLinkage
182 case lltok::kw_weak_odr: // OptionalLinkage
183 case lltok::kw_linkonce: // OptionalLinkage
184 case lltok::kw_linkonce_odr: // OptionalLinkage
185 case lltok::kw_appending: // OptionalLinkage
186 case lltok::kw_dllexport: // OptionalLinkage
187 case lltok::kw_common: // OptionalLinkage
188 case lltok::kw_dllimport: // OptionalLinkage
189 case lltok::kw_extern_weak: // OptionalLinkage
190 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000191 unsigned Linkage, Visibility;
192 if (ParseOptionalLinkage(Linkage) ||
193 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000194 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000195 return true;
196 break;
197 }
198 case lltok::kw_default: // OptionalVisibility
199 case lltok::kw_hidden: // OptionalVisibility
200 case lltok::kw_protected: { // OptionalVisibility
201 unsigned Visibility;
202 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000203 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000204 return true;
205 break;
206 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000207
Chris Lattnerdf986172009-01-02 07:01:27 +0000208 case lltok::kw_thread_local: // OptionalThreadLocal
209 case lltok::kw_addrspace: // OptionalAddrSpace
210 case lltok::kw_constant: // GlobalType
211 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000212 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000213 break;
214 }
215 }
216}
217
218
219/// toplevelentity
220/// ::= 'module' 'asm' STRINGCONSTANT
221bool LLParser::ParseModuleAsm() {
222 assert(Lex.getKind() == lltok::kw_module);
223 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000224
225 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000226 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
227 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000228
Chris Lattnerdf986172009-01-02 07:01:27 +0000229 const std::string &AsmSoFar = M->getModuleInlineAsm();
230 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000231 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000232 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000233 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000234 return false;
235}
236
237/// toplevelentity
238/// ::= 'target' 'triple' '=' STRINGCONSTANT
239/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
240bool LLParser::ParseTargetDefinition() {
241 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000242 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000243 switch (Lex.Lex()) {
244 default: return TokError("unknown target property");
245 case lltok::kw_triple:
246 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000247 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
248 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000249 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000250 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000251 return false;
252 case lltok::kw_datalayout:
253 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000254 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
255 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000256 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000257 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000258 return false;
259 }
260}
261
262/// toplevelentity
263/// ::= 'deplibs' '=' '[' ']'
264/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
265bool LLParser::ParseDepLibs() {
266 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000267 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000268 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
269 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
270 return true;
271
272 if (EatIfPresent(lltok::rsquare))
273 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000274
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000275 std::string Str;
276 if (ParseStringConstant(Str)) return true;
277 M->addLibrary(Str);
278
279 while (EatIfPresent(lltok::comma)) {
280 if (ParseStringConstant(Str)) return true;
281 M->addLibrary(Str);
282 }
283
284 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000285}
286
Dan Gohman3845e502009-08-12 23:32:33 +0000287/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000288/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000289/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000290bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000291 unsigned TypeID = NumberedTypes.size();
292
293 // Handle the LocalVarID form.
294 if (Lex.getKind() == lltok::LocalVarID) {
295 if (Lex.getUIntVal() != TypeID)
296 return Error(Lex.getLoc(), "type expected to be numbered '%" +
297 utostr(TypeID) + "'");
298 Lex.Lex(); // eat LocalVarID;
299
300 if (ParseToken(lltok::equal, "expected '=' after name"))
301 return true;
302 }
303
Chris Lattnerdf986172009-01-02 07:01:27 +0000304 assert(Lex.getKind() == lltok::kw_type);
305 LocTy TypeLoc = Lex.getLoc();
306 Lex.Lex(); // eat kw_type
307
Owen Anderson1d0be152009-08-13 21:58:54 +0000308 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000309 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000310
Chris Lattnerdf986172009-01-02 07:01:27 +0000311 // See if this type was previously referenced.
312 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
313 FI = ForwardRefTypeIDs.find(TypeID);
314 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000315 if (FI->second.first.get() == Ty)
316 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000317
Chris Lattnerdf986172009-01-02 07:01:27 +0000318 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
319 Ty = FI->second.first.get();
320 ForwardRefTypeIDs.erase(FI);
321 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000322
Chris Lattnerdf986172009-01-02 07:01:27 +0000323 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000324
Chris Lattnerdf986172009-01-02 07:01:27 +0000325 return false;
326}
327
328/// toplevelentity
329/// ::= LocalVar '=' 'type' type
330bool LLParser::ParseNamedType() {
331 std::string Name = Lex.getStrVal();
332 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000333 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000334
Owen Anderson1d0be152009-08-13 21:58:54 +0000335 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000336
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000337 if (ParseToken(lltok::equal, "expected '=' after name") ||
338 ParseToken(lltok::kw_type, "expected 'type' after name") ||
339 ParseType(Ty))
340 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000341
Chris Lattnerdf986172009-01-02 07:01:27 +0000342 // Set the type name, checking for conflicts as we do so.
343 bool AlreadyExists = M->addTypeName(Name, Ty);
344 if (!AlreadyExists) return false;
345
346 // See if this type is a forward reference. We need to eagerly resolve
347 // types to allow recursive type redefinitions below.
348 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
349 FI = ForwardRefTypes.find(Name);
350 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000351 if (FI->second.first.get() == Ty)
352 return Error(NameLoc, "self referential type is invalid");
353
Chris Lattnerdf986172009-01-02 07:01:27 +0000354 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
355 Ty = FI->second.first.get();
356 ForwardRefTypes.erase(FI);
357 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000358
Chris Lattnerdf986172009-01-02 07:01:27 +0000359 // Inserting a name that is already defined, get the existing name.
360 const Type *Existing = M->getTypeByName(Name);
361 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000362
Chris Lattnerdf986172009-01-02 07:01:27 +0000363 // Otherwise, this is an attempt to redefine a type. That's okay if
364 // the redefinition is identical to the original.
365 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
366 if (Existing == Ty) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000367
Chris Lattnerdf986172009-01-02 07:01:27 +0000368 // Any other kind of (non-equivalent) redefinition is an error.
369 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
370 Ty->getDescription() + "'");
371}
372
373
374/// toplevelentity
375/// ::= 'declare' FunctionHeader
376bool LLParser::ParseDeclare() {
377 assert(Lex.getKind() == lltok::kw_declare);
378 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000379
Chris Lattnerdf986172009-01-02 07:01:27 +0000380 Function *F;
381 return ParseFunctionHeader(F, false);
382}
383
384/// toplevelentity
385/// ::= 'define' FunctionHeader '{' ...
386bool LLParser::ParseDefine() {
387 assert(Lex.getKind() == lltok::kw_define);
388 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000389
Chris Lattnerdf986172009-01-02 07:01:27 +0000390 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000391 return ParseFunctionHeader(F, true) ||
392 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000393}
394
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000395/// ParseGlobalType
396/// ::= 'constant'
397/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000398bool LLParser::ParseGlobalType(bool &IsConstant) {
399 if (Lex.getKind() == lltok::kw_constant)
400 IsConstant = true;
401 else if (Lex.getKind() == lltok::kw_global)
402 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000403 else {
404 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000405 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000406 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000407 Lex.Lex();
408 return false;
409}
410
Dan Gohman3845e502009-08-12 23:32:33 +0000411/// ParseUnnamedGlobal:
412/// OptionalVisibility ALIAS ...
413/// OptionalLinkage OptionalVisibility ... -> global variable
414/// GlobalID '=' OptionalVisibility ALIAS ...
415/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
416bool LLParser::ParseUnnamedGlobal() {
417 unsigned VarID = NumberedVals.size();
418 std::string Name;
419 LocTy NameLoc = Lex.getLoc();
420
421 // Handle the GlobalID form.
422 if (Lex.getKind() == lltok::GlobalID) {
423 if (Lex.getUIntVal() != VarID)
424 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
425 utostr(VarID) + "'");
426 Lex.Lex(); // eat GlobalID;
427
428 if (ParseToken(lltok::equal, "expected '=' after name"))
429 return true;
430 }
431
432 bool HasLinkage;
433 unsigned Linkage, Visibility;
434 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
435 ParseOptionalVisibility(Visibility))
436 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000437
Dan Gohman3845e502009-08-12 23:32:33 +0000438 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
439 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
440 return ParseAlias(Name, NameLoc, Visibility);
441}
442
Chris Lattnerdf986172009-01-02 07:01:27 +0000443/// ParseNamedGlobal:
444/// GlobalVar '=' OptionalVisibility ALIAS ...
445/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
446bool LLParser::ParseNamedGlobal() {
447 assert(Lex.getKind() == lltok::GlobalVar);
448 LocTy NameLoc = Lex.getLoc();
449 std::string Name = Lex.getStrVal();
450 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000451
Chris Lattnerdf986172009-01-02 07:01:27 +0000452 bool HasLinkage;
453 unsigned Linkage, Visibility;
454 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
455 ParseOptionalLinkage(Linkage, HasLinkage) ||
456 ParseOptionalVisibility(Visibility))
457 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000458
Chris Lattnerdf986172009-01-02 07:01:27 +0000459 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
460 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
461 return ParseAlias(Name, NameLoc, Visibility);
462}
463
Devang Patel256be962009-07-20 19:00:08 +0000464// MDString:
465// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000466bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000467 std::string Str;
468 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000469 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000470 return false;
471}
472
473// MDNode:
474// ::= '!' MDNodeNumber
Chris Lattner442ffa12009-12-29 21:53:55 +0000475bool LLParser::ParseMDNode(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000476 // !{ ..., !42, ... }
477 unsigned MID = 0;
Chris Lattnere80250e2009-12-29 21:43:58 +0000478 if (ParseUInt32(MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000479
Devang Patel256be962009-07-20 19:00:08 +0000480 // Check existing MDNode.
Chris Lattnere80250e2009-12-29 21:43:58 +0000481 std::map<unsigned, TrackingVH<MDNode> >::iterator I = MetadataCache.find(MID);
Devang Patel256be962009-07-20 19:00:08 +0000482 if (I != MetadataCache.end()) {
Chris Lattner442ffa12009-12-29 21:53:55 +0000483 Result = I->second;
Devang Patel256be962009-07-20 19:00:08 +0000484 return false;
485 }
486
487 // Check known forward references.
Chris Lattnere80250e2009-12-29 21:43:58 +0000488 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel256be962009-07-20 19:00:08 +0000489 FI = ForwardRefMDNodes.find(MID);
490 if (FI != ForwardRefMDNodes.end()) {
Chris Lattner442ffa12009-12-29 21:53:55 +0000491 Result = FI->second.first;
Devang Patel256be962009-07-20 19:00:08 +0000492 return false;
493 }
494
Chris Lattner42991ee2009-12-29 22:01:50 +0000495 // Create MDNode forward reference.
496
497 // FIXME: This is not unique enough!
Devang Patel256be962009-07-20 19:00:08 +0000498 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Benjamin Kramerc17300f2009-12-29 22:17:06 +0000499 Value *V = MDString::get(Context, FwdRefName);
Chris Lattner42991ee2009-12-29 22:01:50 +0000500 MDNode *FwdNode = MDNode::get(Context, &V, 1);
Devang Patel256be962009-07-20 19:00:08 +0000501 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner442ffa12009-12-29 21:53:55 +0000502 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000503 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000504}
Devang Patel256be962009-07-20 19:00:08 +0000505
Chris Lattner84d03b12009-12-29 22:35:39 +0000506/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000507/// !foo = !{ !1, !2 }
508bool LLParser::ParseNamedMetadata() {
Devang Patel0475c912009-09-29 00:01:14 +0000509 assert(Lex.getKind() == lltok::NamedOrCustomMD);
Devang Pateleff2ab62009-07-29 00:34:02 +0000510 Lex.Lex();
511 std::string Name = Lex.getStrVal();
512
Chris Lattner84d03b12009-12-29 22:35:39 +0000513 if (ParseToken(lltok::equal, "expected '=' here") ||
514 ParseToken(lltok::Metadata, "Expected '!' here") ||
515 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000516 return true;
517
Devang Pateleff2ab62009-07-29 00:34:02 +0000518 SmallVector<MetadataBase *, 8> Elts;
519 do {
Chris Lattner42991ee2009-12-29 22:01:50 +0000520 if (ParseToken(lltok::Metadata, "Expected '!' here"))
521 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000522
Chris Lattner42991ee2009-12-29 22:01:50 +0000523 // FIXME: This rejects MDStrings. Are they legal in an named MDNode or not?
Chris Lattner442ffa12009-12-29 21:53:55 +0000524 MDNode *N = 0;
Devang Pateleff2ab62009-07-29 00:34:02 +0000525 if (ParseMDNode(N)) return true;
526 Elts.push_back(N);
527 } while (EatIfPresent(lltok::comma));
528
529 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
530 return true;
531
Owen Anderson1d0be152009-08-13 21:58:54 +0000532 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
Devang Pateleff2ab62009-07-29 00:34:02 +0000533 return false;
534}
535
Devang Patel923078c2009-07-01 19:21:12 +0000536/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000537/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000538bool LLParser::ParseStandaloneMetadata() {
539 assert(Lex.getKind() == lltok::Metadata);
540 Lex.Lex();
541 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000542
543 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000544 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000545 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000546 // FIXME: This doesn't make sense here. Pull braced MD stuff parsing out!
547 if (ParseUInt32(MetadataID) ||
548 ParseToken(lltok::equal, "expected '=' here") ||
549 ParseType(Ty, TyLoc) ||
550 ParseToken(lltok::Metadata, "Expected metadata here") ||
551 ParseToken(lltok::lbrace, "Expected '{' here") ||
552 ParseMDNodeVector(Elts) ||
553 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000554 return true;
555
Chris Lattner3f5132a2009-12-29 22:40:21 +0000556 if (MetadataCache.count(MetadataID))
557 return TokError("Metadata id is already used");
558
Owen Anderson647e3012009-07-31 21:35:40 +0000559 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel923078c2009-07-01 19:21:12 +0000560 MetadataCache[MetadataID] = Init;
Chris Lattnere80250e2009-12-29 21:43:58 +0000561 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000562 FI = ForwardRefMDNodes.find(MetadataID);
563 if (FI != ForwardRefMDNodes.end()) {
Chris Lattnere80250e2009-12-29 21:43:58 +0000564 FI->second.first->replaceAllUsesWith(Init);
Devang Patel1c7eea62009-07-08 19:23:54 +0000565 ForwardRefMDNodes.erase(FI);
566 }
567
Devang Patel923078c2009-07-01 19:21:12 +0000568 return false;
569}
570
Chris Lattnerdf986172009-01-02 07:01:27 +0000571/// ParseAlias:
572/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
573/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000574/// ::= TypeAndValue
575/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000576/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000577///
578/// Everything through visibility has already been parsed.
579///
580bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
581 unsigned Visibility) {
582 assert(Lex.getKind() == lltok::kw_alias);
583 Lex.Lex();
584 unsigned Linkage;
585 LocTy LinkageLoc = Lex.getLoc();
586 if (ParseOptionalLinkage(Linkage))
587 return true;
588
589 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000590 Linkage != GlobalValue::WeakAnyLinkage &&
591 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000592 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000593 Linkage != GlobalValue::PrivateLinkage &&
594 Linkage != GlobalValue::LinkerPrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000595 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000596
Chris Lattnerdf986172009-01-02 07:01:27 +0000597 Constant *Aliasee;
598 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000599 if (Lex.getKind() != lltok::kw_bitcast &&
600 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000601 if (ParseGlobalTypeAndValue(Aliasee)) return true;
602 } else {
603 // The bitcast dest type is not present, it is implied by the dest type.
604 ValID ID;
605 if (ParseValID(ID)) return true;
606 if (ID.Kind != ValID::t_Constant)
607 return Error(AliaseeLoc, "invalid aliasee");
608 Aliasee = ID.ConstantVal;
609 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000610
Chris Lattnerdf986172009-01-02 07:01:27 +0000611 if (!isa<PointerType>(Aliasee->getType()))
612 return Error(AliaseeLoc, "alias must have pointer type");
613
614 // Okay, create the alias but do not insert it into the module yet.
615 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
616 (GlobalValue::LinkageTypes)Linkage, Name,
617 Aliasee);
618 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000619
Chris Lattnerdf986172009-01-02 07:01:27 +0000620 // See if this value already exists in the symbol table. If so, it is either
621 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000622 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000623 // See if this was a redefinition. If so, there is no entry in
624 // ForwardRefVals.
625 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
626 I = ForwardRefVals.find(Name);
627 if (I == ForwardRefVals.end())
628 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
629
630 // Otherwise, this was a definition of forward ref. Verify that types
631 // agree.
632 if (Val->getType() != GA->getType())
633 return Error(NameLoc,
634 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000635
Chris Lattnerdf986172009-01-02 07:01:27 +0000636 // If they agree, just RAUW the old value with the alias and remove the
637 // forward ref info.
638 Val->replaceAllUsesWith(GA);
639 Val->eraseFromParent();
640 ForwardRefVals.erase(I);
641 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000642
Chris Lattnerdf986172009-01-02 07:01:27 +0000643 // Insert into the module, we know its name won't collide now.
644 M->getAliasList().push_back(GA);
645 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000646
Chris Lattnerdf986172009-01-02 07:01:27 +0000647 return false;
648}
649
650/// ParseGlobal
651/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
652/// OptionalAddrSpace GlobalType Type Const
653/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
654/// OptionalAddrSpace GlobalType Type Const
655///
656/// Everything through visibility has been parsed already.
657///
658bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
659 unsigned Linkage, bool HasLinkage,
660 unsigned Visibility) {
661 unsigned AddrSpace;
662 bool ThreadLocal, IsConstant;
663 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000664
Owen Anderson1d0be152009-08-13 21:58:54 +0000665 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000666 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
667 ParseOptionalAddrSpace(AddrSpace) ||
668 ParseGlobalType(IsConstant) ||
669 ParseType(Ty, TyLoc))
670 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000671
Chris Lattnerdf986172009-01-02 07:01:27 +0000672 // If the linkage is specified and is external, then no initializer is
673 // present.
674 Constant *Init = 0;
675 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000676 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000677 Linkage != GlobalValue::ExternalLinkage)) {
678 if (ParseGlobalValue(Ty, Init))
679 return true;
680 }
681
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000682 if (isa<FunctionType>(Ty) || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000683 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000684
Chris Lattnerdf986172009-01-02 07:01:27 +0000685 GlobalVariable *GV = 0;
686
687 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000688 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000689 if (GlobalValue *GVal = M->getNamedValue(Name)) {
690 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
691 return Error(NameLoc, "redefinition of global '@" + Name + "'");
692 GV = cast<GlobalVariable>(GVal);
693 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000694 } else {
695 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
696 I = ForwardRefValIDs.find(NumberedVals.size());
697 if (I != ForwardRefValIDs.end()) {
698 GV = cast<GlobalVariable>(I->second.first);
699 ForwardRefValIDs.erase(I);
700 }
701 }
702
703 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000704 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000705 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000706 } else {
707 if (GV->getType()->getElementType() != Ty)
708 return Error(TyLoc,
709 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000710
Chris Lattnerdf986172009-01-02 07:01:27 +0000711 // Move the forward-reference to the correct spot in the module.
712 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
713 }
714
715 if (Name.empty())
716 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000717
Chris Lattnerdf986172009-01-02 07:01:27 +0000718 // Set the parsed properties on the global.
719 if (Init)
720 GV->setInitializer(Init);
721 GV->setConstant(IsConstant);
722 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
723 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
724 GV->setThreadLocal(ThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000725
Chris Lattnerdf986172009-01-02 07:01:27 +0000726 // Parse attributes on the global.
727 while (Lex.getKind() == lltok::comma) {
728 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000729
Chris Lattnerdf986172009-01-02 07:01:27 +0000730 if (Lex.getKind() == lltok::kw_section) {
731 Lex.Lex();
732 GV->setSection(Lex.getStrVal());
733 if (ParseToken(lltok::StringConstant, "expected global section string"))
734 return true;
735 } else if (Lex.getKind() == lltok::kw_align) {
736 unsigned Alignment;
737 if (ParseOptionalAlignment(Alignment)) return true;
738 GV->setAlignment(Alignment);
739 } else {
740 TokError("unknown global variable property!");
741 }
742 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000743
Chris Lattnerdf986172009-01-02 07:01:27 +0000744 return false;
745}
746
747
748//===----------------------------------------------------------------------===//
749// GlobalValue Reference/Resolution Routines.
750//===----------------------------------------------------------------------===//
751
752/// GetGlobalVal - Get a value with the specified name or ID, creating a
753/// forward reference record if needed. This can return null if the value
754/// exists but does not have the right type.
755GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
756 LocTy Loc) {
757 const PointerType *PTy = dyn_cast<PointerType>(Ty);
758 if (PTy == 0) {
759 Error(Loc, "global variable reference must have pointer type");
760 return 0;
761 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000762
Chris Lattnerdf986172009-01-02 07:01:27 +0000763 // Look this name up in the normal function symbol table.
764 GlobalValue *Val =
765 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000766
Chris Lattnerdf986172009-01-02 07:01:27 +0000767 // If this is a forward reference for the value, see if we already created a
768 // forward ref record.
769 if (Val == 0) {
770 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
771 I = ForwardRefVals.find(Name);
772 if (I != ForwardRefVals.end())
773 Val = I->second.first;
774 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000775
Chris Lattnerdf986172009-01-02 07:01:27 +0000776 // If we have the value in the symbol table or fwd-ref table, return it.
777 if (Val) {
778 if (Val->getType() == Ty) return Val;
779 Error(Loc, "'@" + Name + "' defined with type '" +
780 Val->getType()->getDescription() + "'");
781 return 0;
782 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000783
Chris Lattnerdf986172009-01-02 07:01:27 +0000784 // Otherwise, create a new forward reference for this value and remember it.
785 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000786 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
787 // Function types can return opaque but functions can't.
788 if (isa<OpaqueType>(FT->getReturnType())) {
789 Error(Loc, "function may not return opaque type");
790 return 0;
791 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000792
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000793 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000794 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000795 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
796 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000797 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000798
Chris Lattnerdf986172009-01-02 07:01:27 +0000799 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
800 return FwdVal;
801}
802
803GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
804 const PointerType *PTy = dyn_cast<PointerType>(Ty);
805 if (PTy == 0) {
806 Error(Loc, "global variable reference must have pointer type");
807 return 0;
808 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000809
Chris Lattnerdf986172009-01-02 07:01:27 +0000810 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000811
Chris Lattnerdf986172009-01-02 07:01:27 +0000812 // If this is a forward reference for the value, see if we already created a
813 // forward ref record.
814 if (Val == 0) {
815 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
816 I = ForwardRefValIDs.find(ID);
817 if (I != ForwardRefValIDs.end())
818 Val = I->second.first;
819 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000820
Chris Lattnerdf986172009-01-02 07:01:27 +0000821 // If we have the value in the symbol table or fwd-ref table, return it.
822 if (Val) {
823 if (Val->getType() == Ty) return Val;
824 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
825 Val->getType()->getDescription() + "'");
826 return 0;
827 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000828
Chris Lattnerdf986172009-01-02 07:01:27 +0000829 // Otherwise, create a new forward reference for this value and remember it.
830 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000831 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
832 // Function types can return opaque but functions can't.
833 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000834 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000835 return 0;
836 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000837 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000838 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000839 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
840 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000841 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000842
Chris Lattnerdf986172009-01-02 07:01:27 +0000843 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
844 return FwdVal;
845}
846
847
848//===----------------------------------------------------------------------===//
849// Helper Routines.
850//===----------------------------------------------------------------------===//
851
852/// ParseToken - If the current token has the specified kind, eat it and return
853/// success. Otherwise, emit the specified error and return failure.
854bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
855 if (Lex.getKind() != T)
856 return TokError(ErrMsg);
857 Lex.Lex();
858 return false;
859}
860
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000861/// ParseStringConstant
862/// ::= StringConstant
863bool LLParser::ParseStringConstant(std::string &Result) {
864 if (Lex.getKind() != lltok::StringConstant)
865 return TokError("expected string constant");
866 Result = Lex.getStrVal();
867 Lex.Lex();
868 return false;
869}
870
871/// ParseUInt32
872/// ::= uint32
873bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000874 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
875 return TokError("expected integer");
876 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
877 if (Val64 != unsigned(Val64))
878 return TokError("expected 32-bit integer (too large)");
879 Val = Val64;
880 Lex.Lex();
881 return false;
882}
883
884
885/// ParseOptionalAddrSpace
886/// := /*empty*/
887/// := 'addrspace' '(' uint32 ')'
888bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
889 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000890 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000891 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000892 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000893 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000894 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000895}
Chris Lattnerdf986172009-01-02 07:01:27 +0000896
897/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
898/// indicates what kind of attribute list this is: 0: function arg, 1: result,
899/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000900/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000901bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
902 Attrs = Attribute::None;
903 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000904
Chris Lattnerdf986172009-01-02 07:01:27 +0000905 while (1) {
906 switch (Lex.getKind()) {
907 case lltok::kw_sext:
908 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000909 // Treat these as signext/zeroext if they occur in the argument list after
910 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
911 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
912 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000913 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000914 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000915 if (Lex.getKind() == lltok::kw_sext)
916 Attrs |= Attribute::SExt;
917 else
918 Attrs |= Attribute::ZExt;
919 break;
920 }
921 // FALL THROUGH.
922 default: // End of attributes.
923 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
924 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000925
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000926 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000927 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000928
Chris Lattnerdf986172009-01-02 07:01:27 +0000929 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000930 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
931 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
932 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
933 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
934 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
935 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
936 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
937 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000938
Devang Patel578efa92009-06-05 21:57:13 +0000939 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
940 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
941 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
942 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
943 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Dale Johannesende86d472009-08-26 01:08:21 +0000944 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000945 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
946 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
947 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
948 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
949 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
950 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000951 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000952
Chris Lattnerdf986172009-01-02 07:01:27 +0000953 case lltok::kw_align: {
954 unsigned Alignment;
955 if (ParseOptionalAlignment(Alignment))
956 return true;
957 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
958 continue;
959 }
960 }
961 Lex.Lex();
962 }
963}
964
965/// ParseOptionalLinkage
966/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000967/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000968/// ::= 'linker_private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000969/// ::= 'internal'
970/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000971/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000972/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000973/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000974/// ::= 'appending'
975/// ::= 'dllexport'
976/// ::= 'common'
977/// ::= 'dllimport'
978/// ::= 'extern_weak'
979/// ::= 'external'
980bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
981 HasLinkage = false;
982 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000983 default: Res=GlobalValue::ExternalLinkage; return false;
984 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
985 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
986 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
987 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
988 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
989 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
990 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000991 case lltok::kw_available_externally:
992 Res = GlobalValue::AvailableExternallyLinkage;
993 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000994 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
995 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
996 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
997 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
998 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
999 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001000 }
1001 Lex.Lex();
1002 HasLinkage = true;
1003 return false;
1004}
1005
1006/// ParseOptionalVisibility
1007/// ::= /*empty*/
1008/// ::= 'default'
1009/// ::= 'hidden'
1010/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001011///
Chris Lattnerdf986172009-01-02 07:01:27 +00001012bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1013 switch (Lex.getKind()) {
1014 default: Res = GlobalValue::DefaultVisibility; return false;
1015 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1016 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1017 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1018 }
1019 Lex.Lex();
1020 return false;
1021}
1022
1023/// ParseOptionalCallingConv
1024/// ::= /*empty*/
1025/// ::= 'ccc'
1026/// ::= 'fastcc'
1027/// ::= 'coldcc'
1028/// ::= 'x86_stdcallcc'
1029/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001030/// ::= 'arm_apcscc'
1031/// ::= 'arm_aapcscc'
1032/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001033/// ::= 'msp430_intrcc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001034/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001035///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001036bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001037 switch (Lex.getKind()) {
1038 default: CC = CallingConv::C; return false;
1039 case lltok::kw_ccc: CC = CallingConv::C; break;
1040 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1041 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1042 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1043 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001044 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1045 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1046 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001047 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001048 case lltok::kw_cc: {
1049 unsigned ArbitraryCC;
1050 Lex.Lex();
1051 if (ParseUInt32(ArbitraryCC)) {
1052 return true;
1053 } else
1054 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1055 return false;
1056 }
1057 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001058 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001059
Chris Lattnerdf986172009-01-02 07:01:27 +00001060 Lex.Lex();
1061 return false;
1062}
1063
Devang Patel0475c912009-09-29 00:01:14 +00001064/// ParseOptionalCustomMetadata
Devang Patelf633a062009-09-17 23:04:48 +00001065/// ::= /* empty */
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001066/// ::= !dbg !42 (',' !dbg !57)*
Devang Patel0475c912009-09-29 00:01:14 +00001067bool LLParser::ParseOptionalCustomMetadata() {
Chris Lattner52e20312009-10-19 05:31:10 +00001068 if (Lex.getKind() != lltok::NamedOrCustomMD)
Devang Patelf633a062009-09-17 23:04:48 +00001069 return false;
Devang Patel0475c912009-09-29 00:01:14 +00001070
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001071 while (1) {
1072 std::string Name = Lex.getStrVal();
1073 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001074
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001075 if (Lex.getKind() != lltok::Metadata)
1076 return TokError("expected '!' here");
1077 Lex.Lex();
Devang Patel0475c912009-09-29 00:01:14 +00001078
Chris Lattner442ffa12009-12-29 21:53:55 +00001079 MDNode *Node;
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001080 if (ParseMDNode(Node)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001081
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001082 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner442ffa12009-12-29 21:53:55 +00001083 MDsOnInst.push_back(std::make_pair(MDK, Node));
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001084
1085 // If this is the end of the list, we're done.
1086 if (!EatIfPresent(lltok::comma))
1087 return false;
1088
1089 // The next value must be a custom metadata id.
1090 if (Lex.getKind() != lltok::NamedOrCustomMD)
1091 return TokError("expected more custom metadata ids");
1092 }
Devang Patelf633a062009-09-17 23:04:48 +00001093}
1094
Chris Lattnerdf986172009-01-02 07:01:27 +00001095/// ParseOptionalAlignment
1096/// ::= /* empty */
1097/// ::= 'align' 4
1098bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1099 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001100 if (!EatIfPresent(lltok::kw_align))
1101 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001102 LocTy AlignLoc = Lex.getLoc();
1103 if (ParseUInt32(Alignment)) return true;
1104 if (!isPowerOf2_32(Alignment))
1105 return Error(AlignLoc, "alignment is not a power of two");
1106 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001107}
1108
Devang Patelf633a062009-09-17 23:04:48 +00001109/// ParseOptionalInfo
1110/// ::= OptionalInfo (',' OptionalInfo)+
1111bool LLParser::ParseOptionalInfo(unsigned &Alignment) {
1112
1113 // FIXME: Handle customized metadata info attached with an instruction.
1114 do {
Devang Patel0475c912009-09-29 00:01:14 +00001115 if (Lex.getKind() == lltok::NamedOrCustomMD) {
1116 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00001117 } else if (Lex.getKind() == lltok::kw_align) {
1118 if (ParseOptionalAlignment(Alignment)) return true;
1119 } else
1120 return true;
1121 } while (EatIfPresent(lltok::comma));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001122
Devang Patelf633a062009-09-17 23:04:48 +00001123 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001124}
1125
Devang Patelf633a062009-09-17 23:04:48 +00001126
Chris Lattnerdf986172009-01-02 07:01:27 +00001127/// ParseIndexList
1128/// ::= (',' uint32)+
1129bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1130 if (Lex.getKind() != lltok::comma)
1131 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001132
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001133 while (EatIfPresent(lltok::comma)) {
Devang Patele8bc45a2009-11-03 19:06:07 +00001134 if (Lex.getKind() == lltok::NamedOrCustomMD)
1135 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001136 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001137 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001138 Indices.push_back(Idx);
1139 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001140
Chris Lattnerdf986172009-01-02 07:01:27 +00001141 return false;
1142}
1143
1144//===----------------------------------------------------------------------===//
1145// Type Parsing.
1146//===----------------------------------------------------------------------===//
1147
1148/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001149bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1150 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001151 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001152
Chris Lattnerdf986172009-01-02 07:01:27 +00001153 // Verify no unresolved uprefs.
1154 if (!UpRefs.empty())
1155 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001156
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001157 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001158 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001159
Chris Lattnerdf986172009-01-02 07:01:27 +00001160 return false;
1161}
1162
1163/// HandleUpRefs - Every time we finish a new layer of types, this function is
1164/// called. It loops through the UpRefs vector, which is a list of the
1165/// currently active types. For each type, if the up-reference is contained in
1166/// the newly completed type, we decrement the level count. When the level
1167/// count reaches zero, the up-referenced type is the type that is passed in:
1168/// thus we can complete the cycle.
1169///
1170PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1171 // If Ty isn't abstract, or if there are no up-references in it, then there is
1172 // nothing to resolve here.
1173 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001174
Chris Lattnerdf986172009-01-02 07:01:27 +00001175 PATypeHolder Ty(ty);
1176#if 0
David Greene0e28d762009-12-23 23:38:28 +00001177 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001178 << "' newly formed. Resolving upreferences.\n"
1179 << UpRefs.size() << " upreferences active!\n";
1180#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001181
Chris Lattnerdf986172009-01-02 07:01:27 +00001182 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1183 // to zero), we resolve them all together before we resolve them to Ty. At
1184 // the end of the loop, if there is anything to resolve to Ty, it will be in
1185 // this variable.
1186 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001187
Chris Lattnerdf986172009-01-02 07:01:27 +00001188 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1189 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1190 bool ContainsType =
1191 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1192 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001193
Chris Lattnerdf986172009-01-02 07:01:27 +00001194#if 0
David Greene0e28d762009-12-23 23:38:28 +00001195 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001196 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1197 << (ContainsType ? "true" : "false")
1198 << " level=" << UpRefs[i].NestingLevel << "\n";
1199#endif
1200 if (!ContainsType)
1201 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001202
Chris Lattnerdf986172009-01-02 07:01:27 +00001203 // Decrement level of upreference
1204 unsigned Level = --UpRefs[i].NestingLevel;
1205 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001206
Chris Lattnerdf986172009-01-02 07:01:27 +00001207 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1208 if (Level != 0)
1209 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001210
Chris Lattnerdf986172009-01-02 07:01:27 +00001211#if 0
David Greene0e28d762009-12-23 23:38:28 +00001212 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001213#endif
1214 if (!TypeToResolve)
1215 TypeToResolve = UpRefs[i].UpRefTy;
1216 else
1217 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1218 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1219 --i; // Do not skip the next element.
1220 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001221
Chris Lattnerdf986172009-01-02 07:01:27 +00001222 if (TypeToResolve)
1223 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001224
Chris Lattnerdf986172009-01-02 07:01:27 +00001225 return Ty;
1226}
1227
1228
1229/// ParseTypeRec - The recursive function used to process the internal
1230/// implementation details of types.
1231bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1232 switch (Lex.getKind()) {
1233 default:
1234 return TokError("expected type");
1235 case lltok::Type:
1236 // TypeRec ::= 'float' | 'void' (etc)
1237 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001238 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001239 break;
1240 case lltok::kw_opaque:
1241 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001242 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001243 Lex.Lex();
1244 break;
1245 case lltok::lbrace:
1246 // TypeRec ::= '{' ... '}'
1247 if (ParseStructType(Result, false))
1248 return true;
1249 break;
1250 case lltok::lsquare:
1251 // TypeRec ::= '[' ... ']'
1252 Lex.Lex(); // eat the lsquare.
1253 if (ParseArrayVectorType(Result, false))
1254 return true;
1255 break;
1256 case lltok::less: // Either vector or packed struct.
1257 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001258 Lex.Lex();
1259 if (Lex.getKind() == lltok::lbrace) {
1260 if (ParseStructType(Result, true) ||
1261 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001262 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001263 } else if (ParseArrayVectorType(Result, true))
1264 return true;
1265 break;
1266 case lltok::LocalVar:
1267 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1268 // TypeRec ::= %foo
1269 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1270 Result = T;
1271 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001272 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001273 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1274 std::make_pair(Result,
1275 Lex.getLoc())));
1276 M->addTypeName(Lex.getStrVal(), Result.get());
1277 }
1278 Lex.Lex();
1279 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001280
Chris Lattnerdf986172009-01-02 07:01:27 +00001281 case lltok::LocalVarID:
1282 // TypeRec ::= %4
1283 if (Lex.getUIntVal() < NumberedTypes.size())
1284 Result = NumberedTypes[Lex.getUIntVal()];
1285 else {
1286 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1287 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1288 if (I != ForwardRefTypeIDs.end())
1289 Result = I->second.first;
1290 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001291 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001292 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1293 std::make_pair(Result,
1294 Lex.getLoc())));
1295 }
1296 }
1297 Lex.Lex();
1298 break;
1299 case lltok::backslash: {
1300 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001301 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001302 unsigned Val;
1303 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001304 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001305 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1306 Result = OT;
1307 break;
1308 }
1309 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001310
1311 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001312 while (1) {
1313 switch (Lex.getKind()) {
1314 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001315 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001316
1317 // TypeRec ::= TypeRec '*'
1318 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001319 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001320 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001321 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001322 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001323 if (!PointerType::isValidElementType(Result.get()))
1324 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001325 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001326 Lex.Lex();
1327 break;
1328
1329 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1330 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001331 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001332 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001333 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001334 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001335 if (!PointerType::isValidElementType(Result.get()))
1336 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001337 unsigned AddrSpace;
1338 if (ParseOptionalAddrSpace(AddrSpace) ||
1339 ParseToken(lltok::star, "expected '*' in address space"))
1340 return true;
1341
Owen Andersondebcb012009-07-29 22:17:13 +00001342 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001343 break;
1344 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001345
Chris Lattnerdf986172009-01-02 07:01:27 +00001346 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1347 case lltok::lparen:
1348 if (ParseFunctionType(Result))
1349 return true;
1350 break;
1351 }
1352 }
1353}
1354
1355/// ParseParameterList
1356/// ::= '(' ')'
1357/// ::= '(' Arg (',' Arg)* ')'
1358/// Arg
1359/// ::= Type OptionalAttributes Value OptionalAttributes
1360bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1361 PerFunctionState &PFS) {
1362 if (ParseToken(lltok::lparen, "expected '(' in call"))
1363 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001364
Chris Lattnerdf986172009-01-02 07:01:27 +00001365 while (Lex.getKind() != lltok::rparen) {
1366 // If this isn't the first argument, we need a comma.
1367 if (!ArgList.empty() &&
1368 ParseToken(lltok::comma, "expected ',' in argument list"))
1369 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001370
Chris Lattnerdf986172009-01-02 07:01:27 +00001371 // Parse the argument.
1372 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001373 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001374 unsigned ArgAttrs1 = Attribute::None;
1375 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001376 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001377 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001378 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001379
Chris Lattner287881d2009-12-30 02:11:14 +00001380 // Otherwise, handle normal operands.
1381 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1382 ParseValue(ArgTy, V, PFS) ||
1383 // FIXME: Should not allow attributes after the argument, remove this
1384 // in LLVM 3.0.
1385 ParseOptionalAttrs(ArgAttrs2, 3))
1386 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001387 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1388 }
1389
1390 Lex.Lex(); // Lex the ')'.
1391 return false;
1392}
1393
1394
1395
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001396/// ParseArgumentList - Parse the argument list for a function type or function
1397/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001398/// ::= '(' ArgTypeListI ')'
1399/// ArgTypeListI
1400/// ::= /*empty*/
1401/// ::= '...'
1402/// ::= ArgTypeList ',' '...'
1403/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001404///
Chris Lattnerdf986172009-01-02 07:01:27 +00001405bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001406 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001407 isVarArg = false;
1408 assert(Lex.getKind() == lltok::lparen);
1409 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001410
Chris Lattnerdf986172009-01-02 07:01:27 +00001411 if (Lex.getKind() == lltok::rparen) {
1412 // empty
1413 } else if (Lex.getKind() == lltok::dotdotdot) {
1414 isVarArg = true;
1415 Lex.Lex();
1416 } else {
1417 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001418 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001419 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001420 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001421
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001422 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1423 // types (such as a function returning a pointer to itself). If parsing a
1424 // function prototype, we require fully resolved types.
1425 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001426 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001427
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001428 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001429 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001430
Chris Lattnerdf986172009-01-02 07:01:27 +00001431 if (Lex.getKind() == lltok::LocalVar ||
1432 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1433 Name = Lex.getStrVal();
1434 Lex.Lex();
1435 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001436
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001437 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001438 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001439
Chris Lattnerdf986172009-01-02 07:01:27 +00001440 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001441
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001442 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001443 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001444 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001445 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001446 break;
1447 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001448
Chris Lattnerdf986172009-01-02 07:01:27 +00001449 // Otherwise must be an argument type.
1450 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001451 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001452 ParseOptionalAttrs(Attrs, 0)) return true;
1453
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001454 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001455 return Error(TypeLoc, "argument can not have void type");
1456
Chris Lattnerdf986172009-01-02 07:01:27 +00001457 if (Lex.getKind() == lltok::LocalVar ||
1458 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1459 Name = Lex.getStrVal();
1460 Lex.Lex();
1461 } else {
1462 Name = "";
1463 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001464
1465 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1466 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001467
Chris Lattnerdf986172009-01-02 07:01:27 +00001468 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1469 }
1470 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001471
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001472 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001473}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001474
Chris Lattnerdf986172009-01-02 07:01:27 +00001475/// ParseFunctionType
1476/// ::= Type ArgumentList OptionalAttrs
1477bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1478 assert(Lex.getKind() == lltok::lparen);
1479
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001480 if (!FunctionType::isValidReturnType(Result))
1481 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001482
Chris Lattnerdf986172009-01-02 07:01:27 +00001483 std::vector<ArgInfo> ArgList;
1484 bool isVarArg;
1485 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001486 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001487 // FIXME: Allow, but ignore attributes on function types!
1488 // FIXME: Remove in LLVM 3.0
1489 ParseOptionalAttrs(Attrs, 2))
1490 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001491
Chris Lattnerdf986172009-01-02 07:01:27 +00001492 // Reject names on the arguments lists.
1493 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1494 if (!ArgList[i].Name.empty())
1495 return Error(ArgList[i].Loc, "argument name invalid in function type");
1496 if (!ArgList[i].Attrs != 0) {
1497 // Allow but ignore attributes on function types; this permits
1498 // auto-upgrade.
1499 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1500 }
1501 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001502
Chris Lattnerdf986172009-01-02 07:01:27 +00001503 std::vector<const Type*> ArgListTy;
1504 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1505 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001506
Owen Andersondebcb012009-07-29 22:17:13 +00001507 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001508 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001509 return false;
1510}
1511
1512/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1513/// TypeRec
1514/// ::= '{' '}'
1515/// ::= '{' TypeRec (',' TypeRec)* '}'
1516/// ::= '<' '{' '}' '>'
1517/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1518bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1519 assert(Lex.getKind() == lltok::lbrace);
1520 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001521
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001522 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001523 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001524 return false;
1525 }
1526
1527 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001528 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001529 if (ParseTypeRec(Result)) return true;
1530 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001531
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001532 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001533 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001534 if (!StructType::isValidElementType(Result))
1535 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001536
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001537 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001538 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001539 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001540
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001541 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001542 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001543 if (!StructType::isValidElementType(Result))
1544 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001545
Chris Lattnerdf986172009-01-02 07:01:27 +00001546 ParamsList.push_back(Result);
1547 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001548
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001549 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1550 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001551
Chris Lattnerdf986172009-01-02 07:01:27 +00001552 std::vector<const Type*> ParamsListTy;
1553 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1554 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001555 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001556 return false;
1557}
1558
1559/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1560/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001561/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001562/// ::= '[' APSINTVAL 'x' Types ']'
1563/// ::= '<' APSINTVAL 'x' Types '>'
1564bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1565 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1566 Lex.getAPSIntVal().getBitWidth() > 64)
1567 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001568
Chris Lattnerdf986172009-01-02 07:01:27 +00001569 LocTy SizeLoc = Lex.getLoc();
1570 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001571 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001572
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001573 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1574 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001575
1576 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001577 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001578 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001579
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001580 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001581 return Error(TypeLoc, "array and vector element type cannot be void");
1582
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001583 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1584 "expected end of sequential type"))
1585 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001586
Chris Lattnerdf986172009-01-02 07:01:27 +00001587 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001588 if (Size == 0)
1589 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001590 if ((unsigned)Size != Size)
1591 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001592 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001593 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001594 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001595 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001596 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001597 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001598 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001599 }
1600 return false;
1601}
1602
1603//===----------------------------------------------------------------------===//
1604// Function Semantic Analysis.
1605//===----------------------------------------------------------------------===//
1606
Chris Lattner09d9ef42009-10-28 03:39:23 +00001607LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1608 int functionNumber)
1609 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001610
1611 // Insert unnamed arguments into the NumberedVals list.
1612 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1613 AI != E; ++AI)
1614 if (!AI->hasName())
1615 NumberedVals.push_back(AI);
1616}
1617
1618LLParser::PerFunctionState::~PerFunctionState() {
1619 // If there were any forward referenced non-basicblock values, delete them.
1620 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1621 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1622 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001623 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001624 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001625 delete I->second.first;
1626 I->second.first = 0;
1627 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001628
Chris Lattnerdf986172009-01-02 07:01:27 +00001629 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1630 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1631 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001632 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001633 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001634 delete I->second.first;
1635 I->second.first = 0;
1636 }
1637}
1638
Chris Lattner09d9ef42009-10-28 03:39:23 +00001639bool LLParser::PerFunctionState::FinishFunction() {
1640 // Check to see if someone took the address of labels in this block.
1641 if (!P.ForwardRefBlockAddresses.empty()) {
1642 ValID FunctionID;
1643 if (!F.getName().empty()) {
1644 FunctionID.Kind = ValID::t_GlobalName;
1645 FunctionID.StrVal = F.getName();
1646 } else {
1647 FunctionID.Kind = ValID::t_GlobalID;
1648 FunctionID.UIntVal = FunctionNumber;
1649 }
1650
1651 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1652 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1653 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1654 // Resolve all these references.
1655 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1656 return true;
1657
1658 P.ForwardRefBlockAddresses.erase(FRBAI);
1659 }
1660 }
1661
Chris Lattnerdf986172009-01-02 07:01:27 +00001662 if (!ForwardRefVals.empty())
1663 return P.Error(ForwardRefVals.begin()->second.second,
1664 "use of undefined value '%" + ForwardRefVals.begin()->first +
1665 "'");
1666 if (!ForwardRefValIDs.empty())
1667 return P.Error(ForwardRefValIDs.begin()->second.second,
1668 "use of undefined value '%" +
1669 utostr(ForwardRefValIDs.begin()->first) + "'");
1670 return false;
1671}
1672
1673
1674/// GetVal - Get a value with the specified name or ID, creating a
1675/// forward reference record if needed. This can return null if the value
1676/// exists but does not have the right type.
1677Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1678 const Type *Ty, LocTy Loc) {
1679 // Look this name up in the normal function symbol table.
1680 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001681
Chris Lattnerdf986172009-01-02 07:01:27 +00001682 // If this is a forward reference for the value, see if we already created a
1683 // forward ref record.
1684 if (Val == 0) {
1685 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1686 I = ForwardRefVals.find(Name);
1687 if (I != ForwardRefVals.end())
1688 Val = I->second.first;
1689 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001690
Chris Lattnerdf986172009-01-02 07:01:27 +00001691 // If we have the value in the symbol table or fwd-ref table, return it.
1692 if (Val) {
1693 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001694 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001695 P.Error(Loc, "'%" + Name + "' is not a basic block");
1696 else
1697 P.Error(Loc, "'%" + Name + "' defined with type '" +
1698 Val->getType()->getDescription() + "'");
1699 return 0;
1700 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001701
Chris Lattnerdf986172009-01-02 07:01:27 +00001702 // Don't make placeholders with invalid type.
Owen Anderson1d0be152009-08-13 21:58:54 +00001703 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1704 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001705 P.Error(Loc, "invalid use of a non-first-class type");
1706 return 0;
1707 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001708
Chris Lattnerdf986172009-01-02 07:01:27 +00001709 // Otherwise, create a new forward reference for this value and remember it.
1710 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001711 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001712 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001713 else
1714 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001715
Chris Lattnerdf986172009-01-02 07:01:27 +00001716 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1717 return FwdVal;
1718}
1719
1720Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1721 LocTy Loc) {
1722 // Look this name up in the normal function symbol table.
1723 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001724
Chris Lattnerdf986172009-01-02 07:01:27 +00001725 // If this is a forward reference for the value, see if we already created a
1726 // forward ref record.
1727 if (Val == 0) {
1728 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1729 I = ForwardRefValIDs.find(ID);
1730 if (I != ForwardRefValIDs.end())
1731 Val = I->second.first;
1732 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001733
Chris Lattnerdf986172009-01-02 07:01:27 +00001734 // If we have the value in the symbol table or fwd-ref table, return it.
1735 if (Val) {
1736 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001737 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001738 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1739 else
1740 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1741 Val->getType()->getDescription() + "'");
1742 return 0;
1743 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001744
Owen Anderson1d0be152009-08-13 21:58:54 +00001745 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1746 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001747 P.Error(Loc, "invalid use of a non-first-class type");
1748 return 0;
1749 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001750
Chris Lattnerdf986172009-01-02 07:01:27 +00001751 // Otherwise, create a new forward reference for this value and remember it.
1752 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001753 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001754 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001755 else
1756 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001757
Chris Lattnerdf986172009-01-02 07:01:27 +00001758 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1759 return FwdVal;
1760}
1761
1762/// SetInstName - After an instruction is parsed and inserted into its
1763/// basic block, this installs its name.
1764bool LLParser::PerFunctionState::SetInstName(int NameID,
1765 const std::string &NameStr,
1766 LocTy NameLoc, Instruction *Inst) {
1767 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001768 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001769 if (NameID != -1 || !NameStr.empty())
1770 return P.Error(NameLoc, "instructions returning void cannot have a name");
1771 return false;
1772 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001773
Chris Lattnerdf986172009-01-02 07:01:27 +00001774 // If this was a numbered instruction, verify that the instruction is the
1775 // expected value and resolve any forward references.
1776 if (NameStr.empty()) {
1777 // If neither a name nor an ID was specified, just use the next ID.
1778 if (NameID == -1)
1779 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001780
Chris Lattnerdf986172009-01-02 07:01:27 +00001781 if (unsigned(NameID) != NumberedVals.size())
1782 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1783 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001784
Chris Lattnerdf986172009-01-02 07:01:27 +00001785 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1786 ForwardRefValIDs.find(NameID);
1787 if (FI != ForwardRefValIDs.end()) {
1788 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001789 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001790 FI->second.first->getType()->getDescription() + "'");
1791 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001792 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001793 ForwardRefValIDs.erase(FI);
1794 }
1795
1796 NumberedVals.push_back(Inst);
1797 return false;
1798 }
1799
1800 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1801 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1802 FI = ForwardRefVals.find(NameStr);
1803 if (FI != ForwardRefVals.end()) {
1804 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001805 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001806 FI->second.first->getType()->getDescription() + "'");
1807 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001808 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001809 ForwardRefVals.erase(FI);
1810 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001811
Chris Lattnerdf986172009-01-02 07:01:27 +00001812 // Set the name on the instruction.
1813 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001814
Chris Lattnerdf986172009-01-02 07:01:27 +00001815 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001816 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001817 NameStr + "'");
1818 return false;
1819}
1820
1821/// GetBB - Get a basic block with the specified name or ID, creating a
1822/// forward reference record if needed.
1823BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1824 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001825 return cast_or_null<BasicBlock>(GetVal(Name,
1826 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001827}
1828
1829BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001830 return cast_or_null<BasicBlock>(GetVal(ID,
1831 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001832}
1833
1834/// DefineBB - Define the specified basic block, which is either named or
1835/// unnamed. If there is an error, this returns null otherwise it returns
1836/// the block being defined.
1837BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1838 LocTy Loc) {
1839 BasicBlock *BB;
1840 if (Name.empty())
1841 BB = GetBB(NumberedVals.size(), Loc);
1842 else
1843 BB = GetBB(Name, Loc);
1844 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001845
Chris Lattnerdf986172009-01-02 07:01:27 +00001846 // Move the block to the end of the function. Forward ref'd blocks are
1847 // inserted wherever they happen to be referenced.
1848 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001849
Chris Lattnerdf986172009-01-02 07:01:27 +00001850 // Remove the block from forward ref sets.
1851 if (Name.empty()) {
1852 ForwardRefValIDs.erase(NumberedVals.size());
1853 NumberedVals.push_back(BB);
1854 } else {
1855 // BB forward references are already in the function symbol table.
1856 ForwardRefVals.erase(Name);
1857 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001858
Chris Lattnerdf986172009-01-02 07:01:27 +00001859 return BB;
1860}
1861
1862//===----------------------------------------------------------------------===//
1863// Constants.
1864//===----------------------------------------------------------------------===//
1865
1866/// ParseValID - Parse an abstract value that doesn't necessarily have a
1867/// type implied. For example, if we parse "4" we don't know what integer type
1868/// it has. The value will later be combined with its type and checked for
1869/// sanity.
1870bool LLParser::ParseValID(ValID &ID) {
1871 ID.Loc = Lex.getLoc();
1872 switch (Lex.getKind()) {
1873 default: return TokError("expected value token");
1874 case lltok::GlobalID: // @42
1875 ID.UIntVal = Lex.getUIntVal();
1876 ID.Kind = ValID::t_GlobalID;
1877 break;
1878 case lltok::GlobalVar: // @foo
1879 ID.StrVal = Lex.getStrVal();
1880 ID.Kind = ValID::t_GlobalName;
1881 break;
1882 case lltok::LocalVarID: // %42
1883 ID.UIntVal = Lex.getUIntVal();
1884 ID.Kind = ValID::t_LocalID;
1885 break;
1886 case lltok::LocalVar: // %foo
1887 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1888 ID.StrVal = Lex.getStrVal();
1889 ID.Kind = ValID::t_LocalName;
1890 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001891 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
Nick Lewycky21cc4462009-04-04 07:22:01 +00001892 Lex.Lex();
Chris Lattner442ffa12009-12-29 21:53:55 +00001893
1894 // FIXME: This doesn't belong here.
Chris Lattner3f5132a2009-12-29 22:40:21 +00001895 if (EatIfPresent(lltok::lbrace)) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001896 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001897 if (ParseMDNodeVector(Elts) ||
1898 ParseToken(lltok::rbrace, "expected end of metadata node"))
1899 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001900
Chris Lattner287881d2009-12-30 02:11:14 +00001901 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
1902 ID.Kind = ValID::t_MDNode;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001903 return false;
1904 }
1905
Devang Patel923078c2009-07-01 19:21:12 +00001906 // Standalone metadata reference
1907 // !{ ..., !42, ... }
Chris Lattner442ffa12009-12-29 21:53:55 +00001908 // FIXME: Split MetadataVal into one for MDNode and one for MDString.
Chris Lattner287881d2009-12-30 02:11:14 +00001909 if (!ParseMDNode(ID.MDNodeVal)) {
1910 ID.Kind = ValID::t_MDNode;
Devang Patel923078c2009-07-01 19:21:12 +00001911 return false;
Chris Lattner287881d2009-12-30 02:11:14 +00001912 }
1913
1914 // FIXME: This can't work.
Devang Patel256be962009-07-20 19:00:08 +00001915
Nick Lewycky21cc4462009-04-04 07:22:01 +00001916 // MDString:
1917 // ::= '!' STRINGCONSTANT
Chris Lattner287881d2009-12-30 02:11:14 +00001918 if (ParseMDString(ID.MDStringVal)) return true;
1919 ID.Kind = ValID::t_MDString;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001920 return false;
1921 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001922 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001923 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001924 ID.Kind = ValID::t_APSInt;
1925 break;
1926 case lltok::APFloat:
1927 ID.APFloatVal = Lex.getAPFloatVal();
1928 ID.Kind = ValID::t_APFloat;
1929 break;
1930 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001931 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001932 ID.Kind = ValID::t_Constant;
1933 break;
1934 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001935 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001936 ID.Kind = ValID::t_Constant;
1937 break;
1938 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1939 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1940 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001941
Chris Lattnerdf986172009-01-02 07:01:27 +00001942 case lltok::lbrace: {
1943 // ValID ::= '{' ConstVector '}'
1944 Lex.Lex();
1945 SmallVector<Constant*, 16> Elts;
1946 if (ParseGlobalValueVector(Elts) ||
1947 ParseToken(lltok::rbrace, "expected end of struct constant"))
1948 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001949
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001950 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1951 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001952 ID.Kind = ValID::t_Constant;
1953 return false;
1954 }
1955 case lltok::less: {
1956 // ValID ::= '<' ConstVector '>' --> Vector.
1957 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1958 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001959 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001960
Chris Lattnerdf986172009-01-02 07:01:27 +00001961 SmallVector<Constant*, 16> Elts;
1962 LocTy FirstEltLoc = Lex.getLoc();
1963 if (ParseGlobalValueVector(Elts) ||
1964 (isPackedStruct &&
1965 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1966 ParseToken(lltok::greater, "expected end of constant"))
1967 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001968
Chris Lattnerdf986172009-01-02 07:01:27 +00001969 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001970 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001971 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001972 ID.Kind = ValID::t_Constant;
1973 return false;
1974 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001975
Chris Lattnerdf986172009-01-02 07:01:27 +00001976 if (Elts.empty())
1977 return Error(ID.Loc, "constant vector must not be empty");
1978
1979 if (!Elts[0]->getType()->isInteger() &&
1980 !Elts[0]->getType()->isFloatingPoint())
1981 return Error(FirstEltLoc,
1982 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001983
Chris Lattnerdf986172009-01-02 07:01:27 +00001984 // Verify that all the vector elements have the same type.
1985 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1986 if (Elts[i]->getType() != Elts[0]->getType())
1987 return Error(FirstEltLoc,
1988 "vector element #" + utostr(i) +
1989 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001990
Owen Andersonaf7ec972009-07-28 21:19:26 +00001991 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001992 ID.Kind = ValID::t_Constant;
1993 return false;
1994 }
1995 case lltok::lsquare: { // Array Constant
1996 Lex.Lex();
1997 SmallVector<Constant*, 16> Elts;
1998 LocTy FirstEltLoc = Lex.getLoc();
1999 if (ParseGlobalValueVector(Elts) ||
2000 ParseToken(lltok::rsquare, "expected end of array constant"))
2001 return true;
2002
2003 // Handle empty element.
2004 if (Elts.empty()) {
2005 // Use undef instead of an array because it's inconvenient to determine
2006 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002007 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002008 return false;
2009 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002010
Chris Lattnerdf986172009-01-02 07:01:27 +00002011 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002012 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002013 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002014
Owen Andersondebcb012009-07-29 22:17:13 +00002015 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002016
Chris Lattnerdf986172009-01-02 07:01:27 +00002017 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002018 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002019 if (Elts[i]->getType() != Elts[0]->getType())
2020 return Error(FirstEltLoc,
2021 "array element #" + utostr(i) +
2022 " is not of type '" +Elts[0]->getType()->getDescription());
2023 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002024
Owen Anderson1fd70962009-07-28 18:32:17 +00002025 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002026 ID.Kind = ValID::t_Constant;
2027 return false;
2028 }
2029 case lltok::kw_c: // c "foo"
2030 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002031 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002032 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2033 ID.Kind = ValID::t_Constant;
2034 return false;
2035
2036 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002037 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2038 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002039 Lex.Lex();
2040 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002041 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002042 ParseStringConstant(ID.StrVal) ||
2043 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002044 ParseToken(lltok::StringConstant, "expected constraint string"))
2045 return true;
2046 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002047 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002048 ID.Kind = ValID::t_InlineAsm;
2049 return false;
2050 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002051
Chris Lattner09d9ef42009-10-28 03:39:23 +00002052 case lltok::kw_blockaddress: {
2053 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2054 Lex.Lex();
2055
2056 ValID Fn, Label;
2057 LocTy FnLoc, LabelLoc;
2058
2059 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2060 ParseValID(Fn) ||
2061 ParseToken(lltok::comma, "expected comma in block address expression")||
2062 ParseValID(Label) ||
2063 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2064 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002065
Chris Lattner09d9ef42009-10-28 03:39:23 +00002066 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2067 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002068 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002069 return Error(Label.Loc, "expected basic block name in blockaddress");
2070
2071 // Make a global variable as a placeholder for this reference.
2072 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2073 false, GlobalValue::InternalLinkage,
2074 0, "");
2075 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2076 ID.ConstantVal = FwdRef;
2077 ID.Kind = ValID::t_Constant;
2078 return false;
2079 }
2080
Chris Lattnerdf986172009-01-02 07:01:27 +00002081 case lltok::kw_trunc:
2082 case lltok::kw_zext:
2083 case lltok::kw_sext:
2084 case lltok::kw_fptrunc:
2085 case lltok::kw_fpext:
2086 case lltok::kw_bitcast:
2087 case lltok::kw_uitofp:
2088 case lltok::kw_sitofp:
2089 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002090 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002091 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002092 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002093 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002094 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002095 Constant *SrcVal;
2096 Lex.Lex();
2097 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2098 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002099 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002100 ParseType(DestTy) ||
2101 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2102 return true;
2103 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2104 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2105 SrcVal->getType()->getDescription() + "' to '" +
2106 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002107 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002108 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002109 ID.Kind = ValID::t_Constant;
2110 return false;
2111 }
2112 case lltok::kw_extractvalue: {
2113 Lex.Lex();
2114 Constant *Val;
2115 SmallVector<unsigned, 4> Indices;
2116 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2117 ParseGlobalTypeAndValue(Val) ||
2118 ParseIndexList(Indices) ||
2119 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2120 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002121 if (Lex.getKind() == lltok::NamedOrCustomMD)
2122 if (ParseOptionalCustomMetadata()) return true;
2123
Chris Lattnerdf986172009-01-02 07:01:27 +00002124 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
2125 return Error(ID.Loc, "extractvalue operand must be array or struct");
2126 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2127 Indices.end()))
2128 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002129 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002130 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002131 ID.Kind = ValID::t_Constant;
2132 return false;
2133 }
2134 case lltok::kw_insertvalue: {
2135 Lex.Lex();
2136 Constant *Val0, *Val1;
2137 SmallVector<unsigned, 4> Indices;
2138 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2139 ParseGlobalTypeAndValue(Val0) ||
2140 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2141 ParseGlobalTypeAndValue(Val1) ||
2142 ParseIndexList(Indices) ||
2143 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2144 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002145 if (Lex.getKind() == lltok::NamedOrCustomMD)
2146 if (ParseOptionalCustomMetadata()) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002147 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2148 return Error(ID.Loc, "extractvalue operand must be array or struct");
2149 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2150 Indices.end()))
2151 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002152 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002153 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002154 ID.Kind = ValID::t_Constant;
2155 return false;
2156 }
2157 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002158 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002159 unsigned PredVal, Opc = Lex.getUIntVal();
2160 Constant *Val0, *Val1;
2161 Lex.Lex();
2162 if (ParseCmpPredicate(PredVal, Opc) ||
2163 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2164 ParseGlobalTypeAndValue(Val0) ||
2165 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2166 ParseGlobalTypeAndValue(Val1) ||
2167 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2168 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002169
Chris Lattnerdf986172009-01-02 07:01:27 +00002170 if (Val0->getType() != Val1->getType())
2171 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002172
Chris Lattnerdf986172009-01-02 07:01:27 +00002173 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002174
Chris Lattnerdf986172009-01-02 07:01:27 +00002175 if (Opc == Instruction::FCmp) {
2176 if (!Val0->getType()->isFPOrFPVector())
2177 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002178 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002179 } else {
2180 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002181 if (!Val0->getType()->isIntOrIntVector() &&
2182 !isa<PointerType>(Val0->getType()))
2183 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002184 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002185 }
2186 ID.Kind = ValID::t_Constant;
2187 return false;
2188 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002189
Chris Lattnerdf986172009-01-02 07:01:27 +00002190 // Binary Operators.
2191 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002192 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002193 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002194 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002195 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002196 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002197 case lltok::kw_udiv:
2198 case lltok::kw_sdiv:
2199 case lltok::kw_fdiv:
2200 case lltok::kw_urem:
2201 case lltok::kw_srem:
2202 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002203 bool NUW = false;
2204 bool NSW = false;
2205 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002206 unsigned Opc = Lex.getUIntVal();
2207 Constant *Val0, *Val1;
2208 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002209 LocTy ModifierLoc = Lex.getLoc();
2210 if (Opc == Instruction::Add ||
2211 Opc == Instruction::Sub ||
2212 Opc == Instruction::Mul) {
2213 if (EatIfPresent(lltok::kw_nuw))
2214 NUW = true;
2215 if (EatIfPresent(lltok::kw_nsw)) {
2216 NSW = true;
2217 if (EatIfPresent(lltok::kw_nuw))
2218 NUW = true;
2219 }
2220 } else if (Opc == Instruction::SDiv) {
2221 if (EatIfPresent(lltok::kw_exact))
2222 Exact = true;
2223 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002224 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2225 ParseGlobalTypeAndValue(Val0) ||
2226 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2227 ParseGlobalTypeAndValue(Val1) ||
2228 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2229 return true;
2230 if (Val0->getType() != Val1->getType())
2231 return Error(ID.Loc, "operands of constexpr must have same type");
Dan Gohman59858cf2009-07-27 16:11:46 +00002232 if (!Val0->getType()->isIntOrIntVector()) {
2233 if (NUW)
2234 return Error(ModifierLoc, "nuw only applies to integer operations");
2235 if (NSW)
2236 return Error(ModifierLoc, "nsw only applies to integer operations");
2237 }
2238 // API compatibility: Accept either integer or floating-point types with
2239 // add, sub, and mul.
Chris Lattnerdf986172009-01-02 07:01:27 +00002240 if (!Val0->getType()->isIntOrIntVector() &&
2241 !Val0->getType()->isFPOrFPVector())
2242 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002243 unsigned Flags = 0;
2244 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2245 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2246 if (Exact) Flags |= SDivOperator::IsExact;
2247 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002248 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002249 ID.Kind = ValID::t_Constant;
2250 return false;
2251 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002252
Chris Lattnerdf986172009-01-02 07:01:27 +00002253 // Logical Operations
2254 case lltok::kw_shl:
2255 case lltok::kw_lshr:
2256 case lltok::kw_ashr:
2257 case lltok::kw_and:
2258 case lltok::kw_or:
2259 case lltok::kw_xor: {
2260 unsigned Opc = Lex.getUIntVal();
2261 Constant *Val0, *Val1;
2262 Lex.Lex();
2263 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2264 ParseGlobalTypeAndValue(Val0) ||
2265 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2266 ParseGlobalTypeAndValue(Val1) ||
2267 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2268 return true;
2269 if (Val0->getType() != Val1->getType())
2270 return Error(ID.Loc, "operands of constexpr must have same type");
2271 if (!Val0->getType()->isIntOrIntVector())
2272 return Error(ID.Loc,
2273 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002274 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002275 ID.Kind = ValID::t_Constant;
2276 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002277 }
2278
Chris Lattnerdf986172009-01-02 07:01:27 +00002279 case lltok::kw_getelementptr:
2280 case lltok::kw_shufflevector:
2281 case lltok::kw_insertelement:
2282 case lltok::kw_extractelement:
2283 case lltok::kw_select: {
2284 unsigned Opc = Lex.getUIntVal();
2285 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002286 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002287 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002288 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002289 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002290 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2291 ParseGlobalValueVector(Elts) ||
2292 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2293 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002294
Chris Lattnerdf986172009-01-02 07:01:27 +00002295 if (Opc == Instruction::GetElementPtr) {
2296 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2297 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002298
Chris Lattnerdf986172009-01-02 07:01:27 +00002299 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002300 (Value**)(Elts.data() + 1),
2301 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002302 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002303 ID.ConstantVal = InBounds ?
2304 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2305 Elts.data() + 1,
2306 Elts.size() - 1) :
2307 ConstantExpr::getGetElementPtr(Elts[0],
2308 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002309 } else if (Opc == Instruction::Select) {
2310 if (Elts.size() != 3)
2311 return Error(ID.Loc, "expected three operands to select");
2312 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2313 Elts[2]))
2314 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002315 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002316 } else if (Opc == Instruction::ShuffleVector) {
2317 if (Elts.size() != 3)
2318 return Error(ID.Loc, "expected three operands to shufflevector");
2319 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2320 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002321 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002322 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002323 } else if (Opc == Instruction::ExtractElement) {
2324 if (Elts.size() != 2)
2325 return Error(ID.Loc, "expected two operands to extractelement");
2326 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2327 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002328 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002329 } else {
2330 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2331 if (Elts.size() != 3)
2332 return Error(ID.Loc, "expected three operands to insertelement");
2333 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2334 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002335 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002336 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002337 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002338
Chris Lattnerdf986172009-01-02 07:01:27 +00002339 ID.Kind = ValID::t_Constant;
2340 return false;
2341 }
2342 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002343
Chris Lattnerdf986172009-01-02 07:01:27 +00002344 Lex.Lex();
2345 return false;
2346}
2347
2348/// ParseGlobalValue - Parse a global value with the specified type.
2349bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2350 V = 0;
2351 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002352 return ParseValID(ID) ||
2353 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002354}
2355
2356/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2357/// constant.
2358bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2359 Constant *&V) {
2360 if (isa<FunctionType>(Ty))
2361 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002362
Chris Lattnerdf986172009-01-02 07:01:27 +00002363 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002364 default: llvm_unreachable("Unknown ValID!");
Chris Lattner287881d2009-12-30 02:11:14 +00002365 case ValID::t_MDNode:
2366 case ValID::t_MDString:
Devang Patele54abc92009-07-22 17:43:22 +00002367 return Error(ID.Loc, "invalid use of metadata");
Chris Lattnerdf986172009-01-02 07:01:27 +00002368 case ValID::t_LocalID:
2369 case ValID::t_LocalName:
2370 return Error(ID.Loc, "invalid use of function-local name");
2371 case ValID::t_InlineAsm:
2372 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2373 case ValID::t_GlobalName:
2374 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2375 return V == 0;
2376 case ValID::t_GlobalID:
2377 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2378 return V == 0;
2379 case ValID::t_APSInt:
2380 if (!isa<IntegerType>(Ty))
2381 return Error(ID.Loc, "integer constant must have integer type");
2382 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002383 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002384 return false;
2385 case ValID::t_APFloat:
2386 if (!Ty->isFloatingPoint() ||
2387 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2388 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002389
Chris Lattnerdf986172009-01-02 07:01:27 +00002390 // The lexer has no type info, so builds all float and double FP constants
2391 // as double. Fix this here. Long double does not need this.
2392 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002393 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002394 bool Ignored;
2395 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2396 &Ignored);
2397 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002398 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002399
Chris Lattner959873d2009-01-05 18:24:23 +00002400 if (V->getType() != Ty)
2401 return Error(ID.Loc, "floating point constant does not have type '" +
2402 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002403
Chris Lattnerdf986172009-01-02 07:01:27 +00002404 return false;
2405 case ValID::t_Null:
2406 if (!isa<PointerType>(Ty))
2407 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002408 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002409 return false;
2410 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002411 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002412 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Chris Lattner0b616352009-01-05 18:12:21 +00002413 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002414 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002415 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002416 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002417 case ValID::t_EmptyArray:
2418 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2419 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002420 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002421 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002422 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002423 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002424 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002425 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002426 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002427 return false;
2428 case ValID::t_Constant:
2429 if (ID.ConstantVal->getType() != Ty)
2430 return Error(ID.Loc, "constant expression type mismatch");
2431 V = ID.ConstantVal;
2432 return false;
2433 }
2434}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002435
Chris Lattnerdf986172009-01-02 07:01:27 +00002436bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002437 PATypeHolder Type(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002438 return ParseType(Type) ||
2439 ParseGlobalValue(Type, V);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002440}
Chris Lattnerdf986172009-01-02 07:01:27 +00002441
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002442/// ParseGlobalValueVector
2443/// ::= /*empty*/
2444/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002445bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2446 // Empty list.
2447 if (Lex.getKind() == lltok::rbrace ||
2448 Lex.getKind() == lltok::rsquare ||
2449 Lex.getKind() == lltok::greater ||
2450 Lex.getKind() == lltok::rparen)
2451 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002452
Chris Lattnerdf986172009-01-02 07:01:27 +00002453 Constant *C;
2454 if (ParseGlobalTypeAndValue(C)) return true;
2455 Elts.push_back(C);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002456
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002457 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002458 if (ParseGlobalTypeAndValue(C)) return true;
2459 Elts.push_back(C);
2460 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002461
Chris Lattnerdf986172009-01-02 07:01:27 +00002462 return false;
2463}
2464
2465
2466//===----------------------------------------------------------------------===//
2467// Function Parsing.
2468//===----------------------------------------------------------------------===//
2469
2470bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2471 PerFunctionState &PFS) {
Chris Lattner287881d2009-12-30 02:11:14 +00002472 switch (ID.Kind) {
2473 case ValID::t_LocalID: V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc); break;
2474 case ValID::t_LocalName: V = PFS.GetVal(ID.StrVal, Ty, ID.Loc); break;
2475 case ValID::t_MDNode: V = ID.MDNodeVal; break;
2476 case ValID::t_MDString: V = ID.MDStringVal;
2477 case ValID::t_InlineAsm: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002478 const PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerc49363b2009-12-30 02:20:07 +00002479 const FunctionType *FTy =
2480 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002481 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2482 return Error(ID.Loc, "invalid type for inline asm constraint string");
Dale Johannesen43602982009-10-13 20:46:56 +00002483 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002484 return false;
Chris Lattner287881d2009-12-30 02:11:14 +00002485 }
2486 default: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002487 Constant *C;
2488 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2489 V = C;
2490 return false;
2491 }
Chris Lattner287881d2009-12-30 02:11:14 +00002492 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002493
2494 return V == 0;
2495}
2496
2497bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2498 V = 0;
2499 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002500 return ParseValID(ID) ||
2501 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002502}
2503
2504bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002505 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002506 return ParseType(T) ||
2507 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002508}
2509
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002510bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2511 PerFunctionState &PFS) {
2512 Value *V;
2513 Loc = Lex.getLoc();
2514 if (ParseTypeAndValue(V, PFS)) return true;
2515 if (!isa<BasicBlock>(V))
2516 return Error(Loc, "expected a basic block");
2517 BB = cast<BasicBlock>(V);
2518 return false;
2519}
2520
2521
Chris Lattnerdf986172009-01-02 07:01:27 +00002522/// FunctionHeader
2523/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2524/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2525/// OptionalAlign OptGC
2526bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2527 // Parse the linkage.
2528 LocTy LinkageLoc = Lex.getLoc();
2529 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002530
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002531 unsigned Visibility, RetAttrs;
2532 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002533 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002534 LocTy RetTypeLoc = Lex.getLoc();
2535 if (ParseOptionalLinkage(Linkage) ||
2536 ParseOptionalVisibility(Visibility) ||
2537 ParseOptionalCallingConv(CC) ||
2538 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002539 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002540 return true;
2541
2542 // Verify that the linkage is ok.
2543 switch ((GlobalValue::LinkageTypes)Linkage) {
2544 case GlobalValue::ExternalLinkage:
2545 break; // always ok.
2546 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002547 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002548 if (isDefine)
2549 return Error(LinkageLoc, "invalid linkage for function definition");
2550 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002551 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002552 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002553 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002554 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002555 case GlobalValue::LinkOnceAnyLinkage:
2556 case GlobalValue::LinkOnceODRLinkage:
2557 case GlobalValue::WeakAnyLinkage:
2558 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002559 case GlobalValue::DLLExportLinkage:
2560 if (!isDefine)
2561 return Error(LinkageLoc, "invalid linkage for function declaration");
2562 break;
2563 case GlobalValue::AppendingLinkage:
2564 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002565 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002566 return Error(LinkageLoc, "invalid function linkage type");
2567 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002568
Chris Lattner99bb3152009-01-05 08:00:30 +00002569 if (!FunctionType::isValidReturnType(RetType) ||
2570 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002571 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002572
Chris Lattnerdf986172009-01-02 07:01:27 +00002573 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002574
2575 std::string FunctionName;
2576 if (Lex.getKind() == lltok::GlobalVar) {
2577 FunctionName = Lex.getStrVal();
2578 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2579 unsigned NameID = Lex.getUIntVal();
2580
2581 if (NameID != NumberedVals.size())
2582 return TokError("function expected to be numbered '%" +
2583 utostr(NumberedVals.size()) + "'");
2584 } else {
2585 return TokError("expected function name");
2586 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002587
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002588 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002589
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002590 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002591 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002592
Chris Lattnerdf986172009-01-02 07:01:27 +00002593 std::vector<ArgInfo> ArgList;
2594 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002595 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002596 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002597 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002598 std::string GC;
2599
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002600 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002601 ParseOptionalAttrs(FuncAttrs, 2) ||
2602 (EatIfPresent(lltok::kw_section) &&
2603 ParseStringConstant(Section)) ||
2604 ParseOptionalAlignment(Alignment) ||
2605 (EatIfPresent(lltok::kw_gc) &&
2606 ParseStringConstant(GC)))
2607 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002608
2609 // If the alignment was parsed as an attribute, move to the alignment field.
2610 if (FuncAttrs & Attribute::Alignment) {
2611 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2612 FuncAttrs &= ~Attribute::Alignment;
2613 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002614
Chris Lattnerdf986172009-01-02 07:01:27 +00002615 // Okay, if we got here, the function is syntactically valid. Convert types
2616 // and do semantic checks.
2617 std::vector<const Type*> ParamTypeList;
2618 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002619 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002620 // attributes.
2621 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2622 if (FuncAttrs & ObsoleteFuncAttrs) {
2623 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2624 FuncAttrs &= ~ObsoleteFuncAttrs;
2625 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002626
Chris Lattnerdf986172009-01-02 07:01:27 +00002627 if (RetAttrs != Attribute::None)
2628 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002629
Chris Lattnerdf986172009-01-02 07:01:27 +00002630 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2631 ParamTypeList.push_back(ArgList[i].Type);
2632 if (ArgList[i].Attrs != Attribute::None)
2633 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2634 }
2635
2636 if (FuncAttrs != Attribute::None)
2637 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2638
2639 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002640
Chris Lattnera9a9e072009-03-09 04:49:14 +00002641 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002642 RetType != Type::getVoidTy(Context))
Daniel Dunbara279bc32009-09-20 02:20:51 +00002643 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2644
Owen Andersonfba933c2009-07-01 23:57:11 +00002645 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002646 FunctionType::get(RetType, ParamTypeList, isVarArg);
2647 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002648
2649 Fn = 0;
2650 if (!FunctionName.empty()) {
2651 // If this was a definition of a forward reference, remove the definition
2652 // from the forward reference table and fill in the forward ref.
2653 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2654 ForwardRefVals.find(FunctionName);
2655 if (FRVI != ForwardRefVals.end()) {
2656 Fn = M->getFunction(FunctionName);
2657 ForwardRefVals.erase(FRVI);
2658 } else if ((Fn = M->getFunction(FunctionName))) {
2659 // If this function already exists in the symbol table, then it is
2660 // multiply defined. We accept a few cases for old backwards compat.
2661 // FIXME: Remove this stuff for LLVM 3.0.
2662 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2663 (!Fn->isDeclaration() && isDefine)) {
2664 // If the redefinition has different type or different attributes,
2665 // reject it. If both have bodies, reject it.
2666 return Error(NameLoc, "invalid redefinition of function '" +
2667 FunctionName + "'");
2668 } else if (Fn->isDeclaration()) {
2669 // Make sure to strip off any argument names so we can't get conflicts.
2670 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2671 AI != AE; ++AI)
2672 AI->setName("");
2673 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002674 } else if (M->getNamedValue(FunctionName)) {
2675 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002676 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002677
Dan Gohman41905542009-08-29 23:37:49 +00002678 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002679 // If this is a definition of a forward referenced function, make sure the
2680 // types agree.
2681 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2682 = ForwardRefValIDs.find(NumberedVals.size());
2683 if (I != ForwardRefValIDs.end()) {
2684 Fn = cast<Function>(I->second.first);
2685 if (Fn->getType() != PFT)
2686 return Error(NameLoc, "type of definition and forward reference of '@" +
2687 utostr(NumberedVals.size()) +"' disagree");
2688 ForwardRefValIDs.erase(I);
2689 }
2690 }
2691
2692 if (Fn == 0)
2693 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2694 else // Move the forward-reference to the correct spot in the module.
2695 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2696
2697 if (FunctionName.empty())
2698 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002699
Chris Lattnerdf986172009-01-02 07:01:27 +00002700 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2701 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2702 Fn->setCallingConv(CC);
2703 Fn->setAttributes(PAL);
2704 Fn->setAlignment(Alignment);
2705 Fn->setSection(Section);
2706 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002707
Chris Lattnerdf986172009-01-02 07:01:27 +00002708 // Add all of the arguments we parsed to the function.
2709 Function::arg_iterator ArgIt = Fn->arg_begin();
2710 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002711 // If we run out of arguments in the Function prototype, exit early.
2712 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2713 if (ArgIt == Fn->arg_end()) break;
2714
Chris Lattnerdf986172009-01-02 07:01:27 +00002715 // If the argument has a name, insert it into the argument symbol table.
2716 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002717
Chris Lattnerdf986172009-01-02 07:01:27 +00002718 // Set the name, if it conflicted, it will be auto-renamed.
2719 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002720
Chris Lattnerdf986172009-01-02 07:01:27 +00002721 if (ArgIt->getNameStr() != ArgList[i].Name)
2722 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2723 ArgList[i].Name + "'");
2724 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002725
Chris Lattnerdf986172009-01-02 07:01:27 +00002726 return false;
2727}
2728
2729
2730/// ParseFunctionBody
2731/// ::= '{' BasicBlock+ '}'
2732/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2733///
2734bool LLParser::ParseFunctionBody(Function &Fn) {
2735 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2736 return TokError("expected '{' in function body");
2737 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002738
Chris Lattner09d9ef42009-10-28 03:39:23 +00002739 int FunctionNumber = -1;
2740 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2741
2742 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002743
Chris Lattnerdf986172009-01-02 07:01:27 +00002744 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2745 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002746
Chris Lattnerdf986172009-01-02 07:01:27 +00002747 // Eat the }.
2748 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002749
Chris Lattnerdf986172009-01-02 07:01:27 +00002750 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002751 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002752}
2753
2754/// ParseBasicBlock
2755/// ::= LabelStr? Instruction*
2756bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2757 // If this basic block starts out with a name, remember it.
2758 std::string Name;
2759 LocTy NameLoc = Lex.getLoc();
2760 if (Lex.getKind() == lltok::LabelStr) {
2761 Name = Lex.getStrVal();
2762 Lex.Lex();
2763 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002764
Chris Lattnerdf986172009-01-02 07:01:27 +00002765 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2766 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002767
Chris Lattnerdf986172009-01-02 07:01:27 +00002768 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002769
Chris Lattnerdf986172009-01-02 07:01:27 +00002770 // Parse the instructions in this block until we get a terminator.
2771 Instruction *Inst;
2772 do {
2773 // This instruction may have three possibilities for a name: a) none
2774 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2775 LocTy NameLoc = Lex.getLoc();
2776 int NameID = -1;
2777 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002778
Chris Lattnerdf986172009-01-02 07:01:27 +00002779 if (Lex.getKind() == lltok::LocalVarID) {
2780 NameID = Lex.getUIntVal();
2781 Lex.Lex();
2782 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2783 return true;
2784 } else if (Lex.getKind() == lltok::LocalVar ||
2785 // FIXME: REMOVE IN LLVM 3.0
2786 Lex.getKind() == lltok::StringConstant) {
2787 NameStr = Lex.getStrVal();
2788 Lex.Lex();
2789 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2790 return true;
2791 }
Devang Patelf633a062009-09-17 23:04:48 +00002792
Chris Lattnerdf986172009-01-02 07:01:27 +00002793 if (ParseInstruction(Inst, BB, PFS)) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002794 if (EatIfPresent(lltok::comma))
Devang Patel0475c912009-09-29 00:01:14 +00002795 ParseOptionalCustomMetadata();
Devang Patelf633a062009-09-17 23:04:48 +00002796
2797 // Set metadata attached with this instruction.
Devang Patela2148402009-09-28 21:14:55 +00002798 for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
Daniel Dunbara279bc32009-09-20 02:20:51 +00002799 MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
Chris Lattner3990b122009-12-28 23:41:32 +00002800 Inst->setMetadata(MDI->first, MDI->second);
Devang Patelf633a062009-09-17 23:04:48 +00002801 MDsOnInst.clear();
2802
Chris Lattnerdf986172009-01-02 07:01:27 +00002803 BB->getInstList().push_back(Inst);
2804
2805 // Set the name on the instruction.
2806 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2807 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002808
Chris Lattnerdf986172009-01-02 07:01:27 +00002809 return false;
2810}
2811
2812//===----------------------------------------------------------------------===//
2813// Instruction Parsing.
2814//===----------------------------------------------------------------------===//
2815
2816/// ParseInstruction - Parse one of the many different instructions.
2817///
2818bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2819 PerFunctionState &PFS) {
2820 lltok::Kind Token = Lex.getKind();
2821 if (Token == lltok::Eof)
2822 return TokError("found end of file when expecting more instructions");
2823 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002824 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002825 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002826
Chris Lattnerdf986172009-01-02 07:01:27 +00002827 switch (Token) {
2828 default: return Error(Loc, "expected instruction opcode");
2829 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002830 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2831 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002832 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2833 case lltok::kw_br: return ParseBr(Inst, PFS);
2834 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002835 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002836 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2837 // Binary Operators.
2838 case lltok::kw_add:
2839 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002840 case lltok::kw_mul: {
2841 bool NUW = false;
2842 bool NSW = false;
2843 LocTy ModifierLoc = Lex.getLoc();
2844 if (EatIfPresent(lltok::kw_nuw))
2845 NUW = true;
2846 if (EatIfPresent(lltok::kw_nsw)) {
2847 NSW = true;
2848 if (EatIfPresent(lltok::kw_nuw))
2849 NUW = true;
2850 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002851 // API compatibility: Accept either integer or floating-point types.
Dan Gohman59858cf2009-07-27 16:11:46 +00002852 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2853 if (!Result) {
2854 if (!Inst->getType()->isIntOrIntVector()) {
2855 if (NUW)
2856 return Error(ModifierLoc, "nuw only applies to integer operations");
2857 if (NSW)
2858 return Error(ModifierLoc, "nsw only applies to integer operations");
2859 }
2860 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002861 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002862 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002863 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002864 }
2865 return Result;
2866 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002867 case lltok::kw_fadd:
2868 case lltok::kw_fsub:
2869 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2870
Dan Gohman59858cf2009-07-27 16:11:46 +00002871 case lltok::kw_sdiv: {
2872 bool Exact = false;
2873 if (EatIfPresent(lltok::kw_exact))
2874 Exact = true;
2875 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2876 if (!Result)
2877 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002878 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002879 return Result;
2880 }
2881
Chris Lattnerdf986172009-01-02 07:01:27 +00002882 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002883 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002884 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002885 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002886 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002887 case lltok::kw_shl:
2888 case lltok::kw_lshr:
2889 case lltok::kw_ashr:
2890 case lltok::kw_and:
2891 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002892 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002893 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002894 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002895 // Casts.
2896 case lltok::kw_trunc:
2897 case lltok::kw_zext:
2898 case lltok::kw_sext:
2899 case lltok::kw_fptrunc:
2900 case lltok::kw_fpext:
2901 case lltok::kw_bitcast:
2902 case lltok::kw_uitofp:
2903 case lltok::kw_sitofp:
2904 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002905 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002906 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002907 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002908 // Other.
2909 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002910 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002911 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2912 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2913 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2914 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2915 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2916 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2917 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002918 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2919 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00002920 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00002921 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2922 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2923 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002924 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002925 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002926 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002927 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002928 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002929 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002930 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2931 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2932 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2933 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2934 }
2935}
2936
2937/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2938bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002939 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002940 switch (Lex.getKind()) {
2941 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2942 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2943 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2944 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2945 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2946 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2947 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2948 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2949 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2950 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2951 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2952 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2953 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2954 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2955 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2956 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2957 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2958 }
2959 } else {
2960 switch (Lex.getKind()) {
2961 default: TokError("expected icmp predicate (e.g. 'eq')");
2962 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2963 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2964 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2965 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2966 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2967 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2968 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2969 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2970 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2971 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2972 }
2973 }
2974 Lex.Lex();
2975 return false;
2976}
2977
2978//===----------------------------------------------------------------------===//
2979// Terminator Instructions.
2980//===----------------------------------------------------------------------===//
2981
2982/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00002983/// ::= 'ret' void (',' !dbg, !1)*
2984/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
2985/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00002986/// [[obsolete: LLVM 3.0]]
Chris Lattnerdf986172009-01-02 07:01:27 +00002987bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2988 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002989 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00002990 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002991
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002992 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002993 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002994 return false;
2995 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002996
Chris Lattnerdf986172009-01-02 07:01:27 +00002997 Value *RV;
2998 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002999
Devang Patelf633a062009-09-17 23:04:48 +00003000 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003001 // Parse optional custom metadata, e.g. !dbg
3002 if (Lex.getKind() == lltok::NamedOrCustomMD) {
3003 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00003004 } else {
3005 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003006 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3007 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003008 SmallVector<Value*, 8> RVs;
3009 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003010
Devang Patelf633a062009-09-17 23:04:48 +00003011 do {
Devang Patel0475c912009-09-29 00:01:14 +00003012 // If optional custom metadata, e.g. !dbg is seen then this is the
3013 // end of MRV.
3014 if (Lex.getKind() == lltok::NamedOrCustomMD)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003015 break;
3016 if (ParseTypeAndValue(RV, PFS)) return true;
3017 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003018 } while (EatIfPresent(lltok::comma));
3019
3020 RV = UndefValue::get(PFS.getFunction().getReturnType());
3021 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003022 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3023 BB->getInstList().push_back(I);
3024 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003025 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003026 }
3027 }
Devang Patelf633a062009-09-17 23:04:48 +00003028
Owen Anderson1d0be152009-08-13 21:58:54 +00003029 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerdf986172009-01-02 07:01:27 +00003030 return false;
3031}
3032
3033
3034/// ParseBr
3035/// ::= 'br' TypeAndValue
3036/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3037bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3038 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003039 Value *Op0;
3040 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003041 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003042
Chris Lattnerdf986172009-01-02 07:01:27 +00003043 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3044 Inst = BranchInst::Create(BB);
3045 return false;
3046 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003047
Owen Anderson1d0be152009-08-13 21:58:54 +00003048 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003049 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003050
Chris Lattnerdf986172009-01-02 07:01:27 +00003051 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003052 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003053 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003054 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003055 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003056
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003057 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003058 return false;
3059}
3060
3061/// ParseSwitch
3062/// Instruction
3063/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3064/// JumpTable
3065/// ::= (TypeAndValue ',' TypeAndValue)*
3066bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3067 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003068 Value *Cond;
3069 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003070 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3071 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003072 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003073 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3074 return true;
3075
3076 if (!isa<IntegerType>(Cond->getType()))
3077 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003078
Chris Lattnerdf986172009-01-02 07:01:27 +00003079 // Parse the jump table pairs.
3080 SmallPtrSet<Value*, 32> SeenCases;
3081 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3082 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003083 Value *Constant;
3084 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003085
Chris Lattnerdf986172009-01-02 07:01:27 +00003086 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3087 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003088 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003089 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003090
Chris Lattnerdf986172009-01-02 07:01:27 +00003091 if (!SeenCases.insert(Constant))
3092 return Error(CondLoc, "duplicate case value in switch");
3093 if (!isa<ConstantInt>(Constant))
3094 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003095
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003096 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003097 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003098
Chris Lattnerdf986172009-01-02 07:01:27 +00003099 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003100
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003101 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003102 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3103 SI->addCase(Table[i].first, Table[i].second);
3104 Inst = SI;
3105 return false;
3106}
3107
Chris Lattnerab21db72009-10-28 00:19:10 +00003108/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003109/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003110/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3111bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003112 LocTy AddrLoc;
3113 Value *Address;
3114 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003115 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3116 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003117 return true;
3118
3119 if (!isa<PointerType>(Address->getType()))
Chris Lattnerab21db72009-10-28 00:19:10 +00003120 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003121
3122 // Parse the destination list.
3123 SmallVector<BasicBlock*, 16> DestList;
3124
3125 if (Lex.getKind() != lltok::rsquare) {
3126 BasicBlock *DestBB;
3127 if (ParseTypeAndBasicBlock(DestBB, PFS))
3128 return true;
3129 DestList.push_back(DestBB);
3130
3131 while (EatIfPresent(lltok::comma)) {
3132 if (ParseTypeAndBasicBlock(DestBB, PFS))
3133 return true;
3134 DestList.push_back(DestBB);
3135 }
3136 }
3137
3138 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3139 return true;
3140
Chris Lattnerab21db72009-10-28 00:19:10 +00003141 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003142 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3143 IBI->addDestination(DestList[i]);
3144 Inst = IBI;
3145 return false;
3146}
3147
3148
Chris Lattnerdf986172009-01-02 07:01:27 +00003149/// ParseInvoke
3150/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3151/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3152bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3153 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003154 unsigned RetAttrs, FnAttrs;
3155 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003156 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003157 LocTy RetTypeLoc;
3158 ValID CalleeID;
3159 SmallVector<ParamInfo, 16> ArgList;
3160
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003161 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003162 if (ParseOptionalCallingConv(CC) ||
3163 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003164 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003165 ParseValID(CalleeID) ||
3166 ParseParameterList(ArgList, PFS) ||
3167 ParseOptionalAttrs(FnAttrs, 2) ||
3168 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003169 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003170 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003171 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003172 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003173
Chris Lattnerdf986172009-01-02 07:01:27 +00003174 // If RetType is a non-function pointer type, then this is the short syntax
3175 // for the call, which means that RetType is just the return type. Infer the
3176 // rest of the function argument types from the arguments that are present.
3177 const PointerType *PFTy = 0;
3178 const FunctionType *Ty = 0;
3179 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3180 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3181 // Pull out the types of all of the arguments...
3182 std::vector<const Type*> ParamTypes;
3183 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3184 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003185
Chris Lattnerdf986172009-01-02 07:01:27 +00003186 if (!FunctionType::isValidReturnType(RetType))
3187 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003188
Owen Andersondebcb012009-07-29 22:17:13 +00003189 Ty = FunctionType::get(RetType, ParamTypes, false);
3190 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003191 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003192
Chris Lattnerdf986172009-01-02 07:01:27 +00003193 // Look up the callee.
3194 Value *Callee;
3195 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003196
Chris Lattnerdf986172009-01-02 07:01:27 +00003197 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3198 // function attributes.
3199 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3200 if (FnAttrs & ObsoleteFuncAttrs) {
3201 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3202 FnAttrs &= ~ObsoleteFuncAttrs;
3203 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003204
Chris Lattnerdf986172009-01-02 07:01:27 +00003205 // Set up the Attributes for the function.
3206 SmallVector<AttributeWithIndex, 8> Attrs;
3207 if (RetAttrs != Attribute::None)
3208 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003209
Chris Lattnerdf986172009-01-02 07:01:27 +00003210 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003211
Chris Lattnerdf986172009-01-02 07:01:27 +00003212 // Loop through FunctionType's arguments and ensure they are specified
3213 // correctly. Also, gather any parameter attributes.
3214 FunctionType::param_iterator I = Ty->param_begin();
3215 FunctionType::param_iterator E = Ty->param_end();
3216 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3217 const Type *ExpectedTy = 0;
3218 if (I != E) {
3219 ExpectedTy = *I++;
3220 } else if (!Ty->isVarArg()) {
3221 return Error(ArgList[i].Loc, "too many arguments specified");
3222 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003223
Chris Lattnerdf986172009-01-02 07:01:27 +00003224 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3225 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3226 ExpectedTy->getDescription() + "'");
3227 Args.push_back(ArgList[i].V);
3228 if (ArgList[i].Attrs != Attribute::None)
3229 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3230 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003231
Chris Lattnerdf986172009-01-02 07:01:27 +00003232 if (I != E)
3233 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003234
Chris Lattnerdf986172009-01-02 07:01:27 +00003235 if (FnAttrs != Attribute::None)
3236 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003237
Chris Lattnerdf986172009-01-02 07:01:27 +00003238 // Finish off the Attributes and check them
3239 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003240
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003241 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003242 Args.begin(), Args.end());
3243 II->setCallingConv(CC);
3244 II->setAttributes(PAL);
3245 Inst = II;
3246 return false;
3247}
3248
3249
3250
3251//===----------------------------------------------------------------------===//
3252// Binary Operators.
3253//===----------------------------------------------------------------------===//
3254
3255/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003256/// ::= ArithmeticOps TypeAndValue ',' Value
3257///
3258/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3259/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003260bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003261 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003262 LocTy Loc; Value *LHS, *RHS;
3263 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3264 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3265 ParseValue(LHS->getType(), RHS, PFS))
3266 return true;
3267
Chris Lattnere914b592009-01-05 08:24:46 +00003268 bool Valid;
3269 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003270 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003271 case 0: // int or FP.
3272 Valid = LHS->getType()->isIntOrIntVector() ||
3273 LHS->getType()->isFPOrFPVector();
3274 break;
3275 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3276 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3277 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003278
Chris Lattnere914b592009-01-05 08:24:46 +00003279 if (!Valid)
3280 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003281
Chris Lattnerdf986172009-01-02 07:01:27 +00003282 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3283 return false;
3284}
3285
3286/// ParseLogical
3287/// ::= ArithmeticOps TypeAndValue ',' Value {
3288bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3289 unsigned Opc) {
3290 LocTy Loc; Value *LHS, *RHS;
3291 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3292 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3293 ParseValue(LHS->getType(), RHS, PFS))
3294 return true;
3295
3296 if (!LHS->getType()->isIntOrIntVector())
3297 return Error(Loc,"instruction requires integer or integer vector operands");
3298
3299 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3300 return false;
3301}
3302
3303
3304/// ParseCompare
3305/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3306/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003307bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3308 unsigned Opc) {
3309 // Parse the integer/fp comparison predicate.
3310 LocTy Loc;
3311 unsigned Pred;
3312 Value *LHS, *RHS;
3313 if (ParseCmpPredicate(Pred, Opc) ||
3314 ParseTypeAndValue(LHS, Loc, PFS) ||
3315 ParseToken(lltok::comma, "expected ',' after compare value") ||
3316 ParseValue(LHS->getType(), RHS, PFS))
3317 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003318
Chris Lattnerdf986172009-01-02 07:01:27 +00003319 if (Opc == Instruction::FCmp) {
3320 if (!LHS->getType()->isFPOrFPVector())
3321 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003322 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003323 } else {
3324 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00003325 if (!LHS->getType()->isIntOrIntVector() &&
3326 !isa<PointerType>(LHS->getType()))
3327 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003328 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003329 }
3330 return false;
3331}
3332
3333//===----------------------------------------------------------------------===//
3334// Other Instructions.
3335//===----------------------------------------------------------------------===//
3336
3337
3338/// ParseCast
3339/// ::= CastOpc TypeAndValue 'to' Type
3340bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3341 unsigned Opc) {
3342 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003343 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003344 if (ParseTypeAndValue(Op, Loc, PFS) ||
3345 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3346 ParseType(DestTy))
3347 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003348
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003349 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3350 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003351 return Error(Loc, "invalid cast opcode for cast from '" +
3352 Op->getType()->getDescription() + "' to '" +
3353 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003354 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003355 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3356 return false;
3357}
3358
3359/// ParseSelect
3360/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3361bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3362 LocTy Loc;
3363 Value *Op0, *Op1, *Op2;
3364 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3365 ParseToken(lltok::comma, "expected ',' after select condition") ||
3366 ParseTypeAndValue(Op1, PFS) ||
3367 ParseToken(lltok::comma, "expected ',' after select value") ||
3368 ParseTypeAndValue(Op2, PFS))
3369 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003370
Chris Lattnerdf986172009-01-02 07:01:27 +00003371 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3372 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003373
Chris Lattnerdf986172009-01-02 07:01:27 +00003374 Inst = SelectInst::Create(Op0, Op1, Op2);
3375 return false;
3376}
3377
Chris Lattner0088a5c2009-01-05 08:18:44 +00003378/// ParseVA_Arg
3379/// ::= 'va_arg' TypeAndValue ',' Type
3380bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003381 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003382 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003383 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003384 if (ParseTypeAndValue(Op, PFS) ||
3385 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003386 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003387 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003388
Chris Lattner0088a5c2009-01-05 08:18:44 +00003389 if (!EltTy->isFirstClassType())
3390 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003391
3392 Inst = new VAArgInst(Op, EltTy);
3393 return false;
3394}
3395
3396/// ParseExtractElement
3397/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3398bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3399 LocTy Loc;
3400 Value *Op0, *Op1;
3401 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3402 ParseToken(lltok::comma, "expected ',' after extract value") ||
3403 ParseTypeAndValue(Op1, PFS))
3404 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003405
Chris Lattnerdf986172009-01-02 07:01:27 +00003406 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3407 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003408
Eric Christophera3500da2009-07-25 02:28:41 +00003409 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003410 return false;
3411}
3412
3413/// ParseInsertElement
3414/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3415bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3416 LocTy Loc;
3417 Value *Op0, *Op1, *Op2;
3418 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3419 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3420 ParseTypeAndValue(Op1, PFS) ||
3421 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3422 ParseTypeAndValue(Op2, PFS))
3423 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003424
Chris Lattnerdf986172009-01-02 07:01:27 +00003425 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003426 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003427
Chris Lattnerdf986172009-01-02 07:01:27 +00003428 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3429 return false;
3430}
3431
3432/// ParseShuffleVector
3433/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3434bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3435 LocTy Loc;
3436 Value *Op0, *Op1, *Op2;
3437 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3438 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3439 ParseTypeAndValue(Op1, PFS) ||
3440 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3441 ParseTypeAndValue(Op2, PFS))
3442 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003443
Chris Lattnerdf986172009-01-02 07:01:27 +00003444 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3445 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003446
Chris Lattnerdf986172009-01-02 07:01:27 +00003447 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3448 return false;
3449}
3450
3451/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003452/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerdf986172009-01-02 07:01:27 +00003453bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003454 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003455 Value *Op0, *Op1;
3456 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003457
Chris Lattnerdf986172009-01-02 07:01:27 +00003458 if (ParseType(Ty) ||
3459 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3460 ParseValue(Ty, Op0, PFS) ||
3461 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003462 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003463 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3464 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003465
Chris Lattnerdf986172009-01-02 07:01:27 +00003466 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3467 while (1) {
3468 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003469
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003470 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003471 break;
3472
Devang Patela43d46f2009-10-16 18:45:49 +00003473 if (Lex.getKind() == lltok::NamedOrCustomMD)
3474 break;
3475
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003476 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003477 ParseValue(Ty, Op0, PFS) ||
3478 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003479 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003480 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3481 return true;
3482 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003483
Devang Patela43d46f2009-10-16 18:45:49 +00003484 if (Lex.getKind() == lltok::NamedOrCustomMD)
3485 if (ParseOptionalCustomMetadata()) return true;
3486
Chris Lattnerdf986172009-01-02 07:01:27 +00003487 if (!Ty->isFirstClassType())
3488 return Error(TypeLoc, "phi node must have first class type");
3489
3490 PHINode *PN = PHINode::Create(Ty);
3491 PN->reserveOperandSpace(PHIVals.size());
3492 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3493 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3494 Inst = PN;
3495 return false;
3496}
3497
3498/// ParseCall
3499/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3500/// ParameterList OptionalAttrs
3501bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3502 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003503 unsigned RetAttrs, FnAttrs;
3504 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003505 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003506 LocTy RetTypeLoc;
3507 ValID CalleeID;
3508 SmallVector<ParamInfo, 16> ArgList;
3509 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003510
Chris Lattnerdf986172009-01-02 07:01:27 +00003511 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3512 ParseOptionalCallingConv(CC) ||
3513 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003514 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003515 ParseValID(CalleeID) ||
3516 ParseParameterList(ArgList, PFS) ||
3517 ParseOptionalAttrs(FnAttrs, 2))
3518 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003519
Chris Lattnerdf986172009-01-02 07:01:27 +00003520 // If RetType is a non-function pointer type, then this is the short syntax
3521 // for the call, which means that RetType is just the return type. Infer the
3522 // rest of the function argument types from the arguments that are present.
3523 const PointerType *PFTy = 0;
3524 const FunctionType *Ty = 0;
3525 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3526 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3527 // Pull out the types of all of the arguments...
3528 std::vector<const Type*> ParamTypes;
3529 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3530 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003531
Chris Lattnerdf986172009-01-02 07:01:27 +00003532 if (!FunctionType::isValidReturnType(RetType))
3533 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003534
Owen Andersondebcb012009-07-29 22:17:13 +00003535 Ty = FunctionType::get(RetType, ParamTypes, false);
3536 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003537 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003538
Chris Lattnerdf986172009-01-02 07:01:27 +00003539 // Look up the callee.
3540 Value *Callee;
3541 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003542
Chris Lattnerdf986172009-01-02 07:01:27 +00003543 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3544 // function attributes.
3545 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3546 if (FnAttrs & ObsoleteFuncAttrs) {
3547 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3548 FnAttrs &= ~ObsoleteFuncAttrs;
3549 }
3550
3551 // Set up the Attributes for the function.
3552 SmallVector<AttributeWithIndex, 8> Attrs;
3553 if (RetAttrs != Attribute::None)
3554 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003555
Chris Lattnerdf986172009-01-02 07:01:27 +00003556 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003557
Chris Lattnerdf986172009-01-02 07:01:27 +00003558 // Loop through FunctionType's arguments and ensure they are specified
3559 // correctly. Also, gather any parameter attributes.
3560 FunctionType::param_iterator I = Ty->param_begin();
3561 FunctionType::param_iterator E = Ty->param_end();
3562 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3563 const Type *ExpectedTy = 0;
3564 if (I != E) {
3565 ExpectedTy = *I++;
3566 } else if (!Ty->isVarArg()) {
3567 return Error(ArgList[i].Loc, "too many arguments specified");
3568 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003569
Chris Lattnerdf986172009-01-02 07:01:27 +00003570 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3571 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3572 ExpectedTy->getDescription() + "'");
3573 Args.push_back(ArgList[i].V);
3574 if (ArgList[i].Attrs != Attribute::None)
3575 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3576 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003577
Chris Lattnerdf986172009-01-02 07:01:27 +00003578 if (I != E)
3579 return Error(CallLoc, "not enough parameters specified for call");
3580
3581 if (FnAttrs != Attribute::None)
3582 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3583
3584 // Finish off the Attributes and check them
3585 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003586
Chris Lattnerdf986172009-01-02 07:01:27 +00003587 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3588 CI->setTailCall(isTail);
3589 CI->setCallingConv(CC);
3590 CI->setAttributes(PAL);
3591 Inst = CI;
3592 return false;
3593}
3594
3595//===----------------------------------------------------------------------===//
3596// Memory Instructions.
3597//===----------------------------------------------------------------------===//
3598
3599/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003600/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3601/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003602bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003603 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003604 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003605 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003606 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003607 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003608 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003609
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003610 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003611 if (Lex.getKind() == lltok::kw_align
3612 || Lex.getKind() == lltok::NamedOrCustomMD) {
Devang Patelf633a062009-09-17 23:04:48 +00003613 if (ParseOptionalInfo(Alignment)) return true;
3614 } else {
3615 if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3616 if (EatIfPresent(lltok::comma))
Daniel Dunbara279bc32009-09-20 02:20:51 +00003617 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003618 }
3619 }
3620
Owen Anderson1d0be152009-08-13 21:58:54 +00003621 if (Size && Size->getType() != Type::getInt32Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003622 return Error(SizeLoc, "element count must be i32");
3623
Victor Hernandez68afa542009-10-21 19:11:40 +00003624 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003625 Inst = new AllocaInst(Ty, Size, Alignment);
Victor Hernandez68afa542009-10-21 19:11:40 +00003626 return false;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003627 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003628
3629 // Autoupgrade old malloc instruction to malloc call.
3630 // FIXME: Remove in LLVM 3.0.
3631 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003632 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3633 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
Victor Hernandez68afa542009-10-21 19:11:40 +00003634 if (!MallocF)
3635 // Prototype malloc as "void *(int32)".
3636 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003637 MallocF = cast<Function>(
3638 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003639 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
Chris Lattnerdf986172009-01-02 07:01:27 +00003640 return false;
3641}
3642
3643/// ParseFree
3644/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003645bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3646 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003647 Value *Val; LocTy Loc;
3648 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3649 if (!isa<PointerType>(Val->getType()))
3650 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003651 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003652 return false;
3653}
3654
3655/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003656/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003657bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3658 bool isVolatile) {
3659 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003660 unsigned Alignment = 0;
3661 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003662
Devang Patelf633a062009-09-17 23:04:48 +00003663 if (EatIfPresent(lltok::comma))
3664 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003665
3666 if (!isa<PointerType>(Val->getType()) ||
3667 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3668 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003669
Chris Lattnerdf986172009-01-02 07:01:27 +00003670 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3671 return false;
3672}
3673
3674/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003675/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003676bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3677 bool isVolatile) {
3678 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003679 unsigned Alignment = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003680 if (ParseTypeAndValue(Val, Loc, PFS) ||
3681 ParseToken(lltok::comma, "expected ',' after store operand") ||
Devang Patelf633a062009-09-17 23:04:48 +00003682 ParseTypeAndValue(Ptr, PtrLoc, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003683 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003684
3685 if (EatIfPresent(lltok::comma))
3686 if (ParseOptionalInfo(Alignment)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003687
Chris Lattnerdf986172009-01-02 07:01:27 +00003688 if (!isa<PointerType>(Ptr->getType()))
3689 return Error(PtrLoc, "store operand must be a pointer");
3690 if (!Val->getType()->isFirstClassType())
3691 return Error(Loc, "store operand must be a first class value");
3692 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3693 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003694
Chris Lattnerdf986172009-01-02 07:01:27 +00003695 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3696 return false;
3697}
3698
3699/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003700/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003701/// FIXME: Remove support for getresult in LLVM 3.0
3702bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3703 Value *Val; LocTy ValLoc, EltLoc;
3704 unsigned Element;
3705 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3706 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003707 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003708 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003709
Chris Lattnerdf986172009-01-02 07:01:27 +00003710 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3711 return Error(ValLoc, "getresult inst requires an aggregate operand");
3712 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3713 return Error(EltLoc, "invalid getresult index for value");
3714 Inst = ExtractValueInst::Create(Val, Element);
3715 return false;
3716}
3717
3718/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003719/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00003720bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3721 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003722
Dan Gohmandcb40a32009-07-29 15:58:36 +00003723 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003724
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003725 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003726
Chris Lattnerdf986172009-01-02 07:01:27 +00003727 if (!isa<PointerType>(Ptr->getType()))
3728 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003729
Chris Lattnerdf986172009-01-02 07:01:27 +00003730 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003731 while (EatIfPresent(lltok::comma)) {
Devang Patel6225d642009-10-13 18:49:55 +00003732 if (Lex.getKind() == lltok::NamedOrCustomMD)
3733 break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003734 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003735 if (!isa<IntegerType>(Val->getType()))
3736 return Error(EltLoc, "getelementptr index must be an integer");
3737 Indices.push_back(Val);
3738 }
Devang Patel6225d642009-10-13 18:49:55 +00003739 if (Lex.getKind() == lltok::NamedOrCustomMD)
3740 if (ParseOptionalCustomMetadata()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003741
Chris Lattnerdf986172009-01-02 07:01:27 +00003742 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3743 Indices.begin(), Indices.end()))
3744 return Error(Loc, "invalid getelementptr indices");
3745 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003746 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003747 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00003748 return false;
3749}
3750
3751/// ParseExtractValue
3752/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3753bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3754 Value *Val; LocTy Loc;
3755 SmallVector<unsigned, 4> Indices;
3756 if (ParseTypeAndValue(Val, Loc, PFS) ||
3757 ParseIndexList(Indices))
3758 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00003759 if (Lex.getKind() == lltok::NamedOrCustomMD)
3760 if (ParseOptionalCustomMetadata()) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003761
3762 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3763 return Error(Loc, "extractvalue operand must be array or struct");
3764
3765 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3766 Indices.end()))
3767 return Error(Loc, "invalid indices for extractvalue");
3768 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3769 return false;
3770}
3771
3772/// ParseInsertValue
3773/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3774bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3775 Value *Val0, *Val1; LocTy Loc0, Loc1;
3776 SmallVector<unsigned, 4> Indices;
3777 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3778 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3779 ParseTypeAndValue(Val1, Loc1, PFS) ||
3780 ParseIndexList(Indices))
3781 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00003782 if (Lex.getKind() == lltok::NamedOrCustomMD)
3783 if (ParseOptionalCustomMetadata()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003784
Chris Lattnerdf986172009-01-02 07:01:27 +00003785 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3786 return Error(Loc0, "extractvalue operand must be array or struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003787
Chris Lattnerdf986172009-01-02 07:01:27 +00003788 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3789 Indices.end()))
3790 return Error(Loc0, "invalid indices for insertvalue");
3791 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3792 return false;
3793}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003794
3795//===----------------------------------------------------------------------===//
3796// Embedded metadata.
3797//===----------------------------------------------------------------------===//
3798
3799/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003800/// ::= Element (',' Element)*
3801/// Element
3802/// ::= 'null' | TypeAndValue
3803bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003804 do {
Devang Pateldb5e9002009-07-23 01:36:16 +00003805 Value *V = 0;
Chris Lattner442ffa12009-12-29 21:53:55 +00003806 // FIXME: REWRITE.
Nick Lewyckycb337992009-05-10 20:57:05 +00003807 if (Lex.getKind() == lltok::kw_null) {
3808 Lex.Lex();
3809 V = 0;
3810 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00003811 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patele54abc92009-07-22 17:43:22 +00003812 if (ParseType(Ty)) return true;
3813 if (Lex.getKind() == lltok::Metadata) {
3814 Lex.Lex();
Chris Lattner442ffa12009-12-29 21:53:55 +00003815 MDNode *Node = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003816 if (!ParseMDNode(Node))
3817 V = Node;
3818 else {
Chris Lattner442ffa12009-12-29 21:53:55 +00003819 MDString *MDS = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003820 if (ParseMDString(MDS)) return true;
3821 V = MDS;
3822 }
3823 } else {
3824 Constant *C;
3825 if (ParseGlobalValue(Ty, C)) return true;
3826 V = C;
3827 }
Nick Lewyckycb337992009-05-10 20:57:05 +00003828 }
3829 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003830 } while (EatIfPresent(lltok::comma));
3831
3832 return false;
3833}