blob: cdad0770a38af9bebe71b204cdea728d42a62d73 [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() {
Chris Lattner449c3102010-04-01 05:14:45 +000042 // Handle any instruction metadata forward references.
43 if (!ForwardRefInstMetadata.empty()) {
44 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
45 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
46 I != E; ++I) {
47 Instruction *Inst = I->first;
48 const std::vector<MDRef> &MDList = I->second;
49
50 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
51 unsigned SlotNo = MDList[i].MDSlot;
52
53 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
54 return Error(MDList[i].Loc, "use of undefined metadata '!" +
55 utostr(SlotNo) + "'");
56 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
57 }
58 }
59 ForwardRefInstMetadata.clear();
60 }
61
62
Victor Hernandez68afa542009-10-21 19:11:40 +000063 // Update auto-upgraded malloc calls to "malloc".
Chris Lattnercf4d2f12009-10-18 05:09:15 +000064 // FIXME: Remove in LLVM 3.0.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000065 if (MallocF) {
66 MallocF->setName("malloc");
67 // If setName() does not set the name to "malloc", then there is already a
68 // declaration of "malloc". In that case, iterate over all calls to MallocF
69 // and get them to call the declared "malloc" instead.
70 if (MallocF->getName() != "malloc") {
Chris Lattner09d9ef42009-10-28 03:39:23 +000071 Constant *RealMallocF = M->getFunction("malloc");
Victor Hernandez68afa542009-10-21 19:11:40 +000072 if (RealMallocF->getType() != MallocF->getType())
73 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
74 MallocF->replaceAllUsesWith(RealMallocF);
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000075 MallocF->eraseFromParent();
76 MallocF = NULL;
77 }
78 }
Chris Lattner09d9ef42009-10-28 03:39:23 +000079
80
81 // If there are entries in ForwardRefBlockAddresses at this point, they are
82 // references after the function was defined. Resolve those now.
83 while (!ForwardRefBlockAddresses.empty()) {
84 // Okay, we are referencing an already-parsed function, resolve them now.
85 Function *TheFn = 0;
86 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
87 if (Fn.Kind == ValID::t_GlobalName)
88 TheFn = M->getFunction(Fn.StrVal);
89 else if (Fn.UIntVal < NumberedVals.size())
90 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
91
92 if (TheFn == 0)
93 return Error(Fn.Loc, "unknown function referenced by blockaddress");
94
95 // Resolve all these references.
96 if (ResolveForwardRefBlockAddresses(TheFn,
97 ForwardRefBlockAddresses.begin()->second,
98 0))
99 return true;
100
101 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
102 }
103
104
Chris Lattnerdf986172009-01-02 07:01:27 +0000105 if (!ForwardRefTypes.empty())
106 return Error(ForwardRefTypes.begin()->second.second,
107 "use of undefined type named '" +
108 ForwardRefTypes.begin()->first + "'");
109 if (!ForwardRefTypeIDs.empty())
110 return Error(ForwardRefTypeIDs.begin()->second.second,
111 "use of undefined type '%" +
112 utostr(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000113
Chris Lattnerdf986172009-01-02 07:01:27 +0000114 if (!ForwardRefVals.empty())
115 return Error(ForwardRefVals.begin()->second.second,
116 "use of undefined value '@" + ForwardRefVals.begin()->first +
117 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000118
Chris Lattnerdf986172009-01-02 07:01:27 +0000119 if (!ForwardRefValIDs.empty())
120 return Error(ForwardRefValIDs.begin()->second.second,
121 "use of undefined value '@" +
122 utostr(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000123
Devang Patel1c7eea62009-07-08 19:23:54 +0000124 if (!ForwardRefMDNodes.empty())
125 return Error(ForwardRefMDNodes.begin()->second.second,
126 "use of undefined metadata '!" +
127 utostr(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000128
Devang Patel1c7eea62009-07-08 19:23:54 +0000129
Chris Lattnerdf986172009-01-02 07:01:27 +0000130 // Look for intrinsic functions and CallInst that need to be upgraded
131 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
132 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000133
Devang Patele4b27562009-08-28 23:24:31 +0000134 // Check debug info intrinsics.
135 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000136 return false;
137}
138
Chris Lattner09d9ef42009-10-28 03:39:23 +0000139bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
140 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
141 PerFunctionState *PFS) {
142 // Loop over all the references, resolving them.
143 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
144 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000145 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000146 if (Refs[i].first.Kind == ValID::t_LocalName)
147 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000148 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000149 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
150 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
151 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000152 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000153 } else {
154 Res = dyn_cast_or_null<BasicBlock>(
155 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
156 }
157
Chris Lattnercdfc9402009-11-01 01:27:45 +0000158 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000159 return Error(Refs[i].first.Loc,
160 "referenced value is not a basic block");
161
162 // Get the BlockAddress for this and update references to use it.
163 BlockAddress *BA = BlockAddress::get(TheFn, Res);
164 Refs[i].second->replaceAllUsesWith(BA);
165 Refs[i].second->eraseFromParent();
166 }
167 return false;
168}
169
170
Chris Lattnerdf986172009-01-02 07:01:27 +0000171//===----------------------------------------------------------------------===//
172// Top-Level Entities
173//===----------------------------------------------------------------------===//
174
175bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000176 while (1) {
177 switch (Lex.getKind()) {
178 default: return TokError("expected top-level entity");
179 case lltok::Eof: return false;
180 //case lltok::kw_define:
181 case lltok::kw_declare: if (ParseDeclare()) return true; break;
182 case lltok::kw_define: if (ParseDefine()) return true; break;
183 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
184 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
185 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
186 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000187 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000188 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
189 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000190 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000191 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000192 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000193 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000194
195 // The Global variable production with no name can have many different
196 // optional leading prefixes, the production is:
197 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
198 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000199 case lltok::kw_private : // OptionalLinkage
200 case lltok::kw_linker_private: // OptionalLinkage
201 case lltok::kw_internal: // OptionalLinkage
202 case lltok::kw_weak: // OptionalLinkage
203 case lltok::kw_weak_odr: // OptionalLinkage
204 case lltok::kw_linkonce: // OptionalLinkage
205 case lltok::kw_linkonce_odr: // OptionalLinkage
206 case lltok::kw_appending: // OptionalLinkage
207 case lltok::kw_dllexport: // OptionalLinkage
208 case lltok::kw_common: // OptionalLinkage
209 case lltok::kw_dllimport: // OptionalLinkage
210 case lltok::kw_extern_weak: // OptionalLinkage
211 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000212 unsigned Linkage, Visibility;
213 if (ParseOptionalLinkage(Linkage) ||
214 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000215 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000216 return true;
217 break;
218 }
219 case lltok::kw_default: // OptionalVisibility
220 case lltok::kw_hidden: // OptionalVisibility
221 case lltok::kw_protected: { // OptionalVisibility
222 unsigned Visibility;
223 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000224 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000225 return true;
226 break;
227 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000228
Chris Lattnerdf986172009-01-02 07:01:27 +0000229 case lltok::kw_thread_local: // OptionalThreadLocal
230 case lltok::kw_addrspace: // OptionalAddrSpace
231 case lltok::kw_constant: // GlobalType
232 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000233 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000234 break;
235 }
236 }
237}
238
239
240/// toplevelentity
241/// ::= 'module' 'asm' STRINGCONSTANT
242bool LLParser::ParseModuleAsm() {
243 assert(Lex.getKind() == lltok::kw_module);
244 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000245
246 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000247 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
248 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000249
Chris Lattnerdf986172009-01-02 07:01:27 +0000250 const std::string &AsmSoFar = M->getModuleInlineAsm();
251 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000252 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000253 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000254 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000255 return false;
256}
257
258/// toplevelentity
259/// ::= 'target' 'triple' '=' STRINGCONSTANT
260/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
261bool LLParser::ParseTargetDefinition() {
262 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000263 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000264 switch (Lex.Lex()) {
265 default: return TokError("unknown target property");
266 case lltok::kw_triple:
267 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000268 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
269 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000270 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000271 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000272 return false;
273 case lltok::kw_datalayout:
274 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000275 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
276 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000277 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000278 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000279 return false;
280 }
281}
282
283/// toplevelentity
284/// ::= 'deplibs' '=' '[' ']'
285/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
286bool LLParser::ParseDepLibs() {
287 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000288 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000289 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
290 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
291 return true;
292
293 if (EatIfPresent(lltok::rsquare))
294 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000295
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000296 std::string Str;
297 if (ParseStringConstant(Str)) return true;
298 M->addLibrary(Str);
299
300 while (EatIfPresent(lltok::comma)) {
301 if (ParseStringConstant(Str)) return true;
302 M->addLibrary(Str);
303 }
304
305 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000306}
307
Dan Gohman3845e502009-08-12 23:32:33 +0000308/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000309/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000310/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000311bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000312 unsigned TypeID = NumberedTypes.size();
313
314 // Handle the LocalVarID form.
315 if (Lex.getKind() == lltok::LocalVarID) {
316 if (Lex.getUIntVal() != TypeID)
317 return Error(Lex.getLoc(), "type expected to be numbered '%" +
318 utostr(TypeID) + "'");
319 Lex.Lex(); // eat LocalVarID;
320
321 if (ParseToken(lltok::equal, "expected '=' after name"))
322 return true;
323 }
324
Chris Lattnerdf986172009-01-02 07:01:27 +0000325 assert(Lex.getKind() == lltok::kw_type);
326 LocTy TypeLoc = Lex.getLoc();
327 Lex.Lex(); // eat kw_type
328
Owen Anderson1d0be152009-08-13 21:58:54 +0000329 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000330 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000331
Chris Lattnerdf986172009-01-02 07:01:27 +0000332 // See if this type was previously referenced.
333 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
334 FI = ForwardRefTypeIDs.find(TypeID);
335 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000336 if (FI->second.first.get() == Ty)
337 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000338
Chris Lattnerdf986172009-01-02 07:01:27 +0000339 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
340 Ty = FI->second.first.get();
341 ForwardRefTypeIDs.erase(FI);
342 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000343
Chris Lattnerdf986172009-01-02 07:01:27 +0000344 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000345
Chris Lattnerdf986172009-01-02 07:01:27 +0000346 return false;
347}
348
349/// toplevelentity
350/// ::= LocalVar '=' 'type' type
351bool LLParser::ParseNamedType() {
352 std::string Name = Lex.getStrVal();
353 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000354 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000355
Owen Anderson1d0be152009-08-13 21:58:54 +0000356 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000357
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000358 if (ParseToken(lltok::equal, "expected '=' after name") ||
359 ParseToken(lltok::kw_type, "expected 'type' after name") ||
360 ParseType(Ty))
361 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000362
Chris Lattnerdf986172009-01-02 07:01:27 +0000363 // Set the type name, checking for conflicts as we do so.
364 bool AlreadyExists = M->addTypeName(Name, Ty);
365 if (!AlreadyExists) return false;
366
367 // See if this type is a forward reference. We need to eagerly resolve
368 // types to allow recursive type redefinitions below.
369 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
370 FI = ForwardRefTypes.find(Name);
371 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000372 if (FI->second.first.get() == Ty)
373 return Error(NameLoc, "self referential type is invalid");
374
Chris Lattnerdf986172009-01-02 07:01:27 +0000375 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
376 Ty = FI->second.first.get();
377 ForwardRefTypes.erase(FI);
378 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000379
Chris Lattnerdf986172009-01-02 07:01:27 +0000380 // Inserting a name that is already defined, get the existing name.
381 const Type *Existing = M->getTypeByName(Name);
382 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000383
Chris Lattnerdf986172009-01-02 07:01:27 +0000384 // Otherwise, this is an attempt to redefine a type. That's okay if
385 // the redefinition is identical to the original.
386 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
387 if (Existing == Ty) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000388
Chris Lattnerdf986172009-01-02 07:01:27 +0000389 // Any other kind of (non-equivalent) redefinition is an error.
390 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
391 Ty->getDescription() + "'");
392}
393
394
395/// toplevelentity
396/// ::= 'declare' FunctionHeader
397bool LLParser::ParseDeclare() {
398 assert(Lex.getKind() == lltok::kw_declare);
399 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000400
Chris Lattnerdf986172009-01-02 07:01:27 +0000401 Function *F;
402 return ParseFunctionHeader(F, false);
403}
404
405/// toplevelentity
406/// ::= 'define' FunctionHeader '{' ...
407bool LLParser::ParseDefine() {
408 assert(Lex.getKind() == lltok::kw_define);
409 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000410
Chris Lattnerdf986172009-01-02 07:01:27 +0000411 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000412 return ParseFunctionHeader(F, true) ||
413 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000414}
415
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000416/// ParseGlobalType
417/// ::= 'constant'
418/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000419bool LLParser::ParseGlobalType(bool &IsConstant) {
420 if (Lex.getKind() == lltok::kw_constant)
421 IsConstant = true;
422 else if (Lex.getKind() == lltok::kw_global)
423 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000424 else {
425 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000426 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000427 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000428 Lex.Lex();
429 return false;
430}
431
Dan Gohman3845e502009-08-12 23:32:33 +0000432/// ParseUnnamedGlobal:
433/// OptionalVisibility ALIAS ...
434/// OptionalLinkage OptionalVisibility ... -> global variable
435/// GlobalID '=' OptionalVisibility ALIAS ...
436/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
437bool LLParser::ParseUnnamedGlobal() {
438 unsigned VarID = NumberedVals.size();
439 std::string Name;
440 LocTy NameLoc = Lex.getLoc();
441
442 // Handle the GlobalID form.
443 if (Lex.getKind() == lltok::GlobalID) {
444 if (Lex.getUIntVal() != VarID)
445 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
446 utostr(VarID) + "'");
447 Lex.Lex(); // eat GlobalID;
448
449 if (ParseToken(lltok::equal, "expected '=' after name"))
450 return true;
451 }
452
453 bool HasLinkage;
454 unsigned Linkage, Visibility;
455 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
456 ParseOptionalVisibility(Visibility))
457 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000458
Dan Gohman3845e502009-08-12 23:32:33 +0000459 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
460 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
461 return ParseAlias(Name, NameLoc, Visibility);
462}
463
Chris Lattnerdf986172009-01-02 07:01:27 +0000464/// ParseNamedGlobal:
465/// GlobalVar '=' OptionalVisibility ALIAS ...
466/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
467bool LLParser::ParseNamedGlobal() {
468 assert(Lex.getKind() == lltok::GlobalVar);
469 LocTy NameLoc = Lex.getLoc();
470 std::string Name = Lex.getStrVal();
471 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000472
Chris Lattnerdf986172009-01-02 07:01:27 +0000473 bool HasLinkage;
474 unsigned Linkage, Visibility;
475 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
476 ParseOptionalLinkage(Linkage, HasLinkage) ||
477 ParseOptionalVisibility(Visibility))
478 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000479
Chris Lattnerdf986172009-01-02 07:01:27 +0000480 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
481 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
482 return ParseAlias(Name, NameLoc, Visibility);
483}
484
Devang Patel256be962009-07-20 19:00:08 +0000485// MDString:
486// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000487bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000488 std::string Str;
489 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000490 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000491 return false;
492}
493
494// MDNode:
495// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000496//
497/// This version of ParseMDNodeID returns the slot number and null in the case
498/// of a forward reference.
499bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
500 // !{ ..., !42, ... }
501 if (ParseUInt32(SlotNo)) return true;
502
503 // Check existing MDNode.
504 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
505 Result = NumberedMetadata[SlotNo];
506 else
507 Result = 0;
508 return false;
509}
510
Chris Lattner4a72efc2009-12-30 04:15:23 +0000511bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000512 // !{ ..., !42, ... }
513 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000514 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000515
Chris Lattner449c3102010-04-01 05:14:45 +0000516 // If not a forward reference, just return it now.
517 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000518
Chris Lattner449c3102010-04-01 05:14:45 +0000519 // Otherwise, create MDNode forward reference.
Chris Lattner42991ee2009-12-29 22:01:50 +0000520
521 // FIXME: This is not unique enough!
Devang Patel256be962009-07-20 19:00:08 +0000522 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Benjamin Kramerc17300f2009-12-29 22:17:06 +0000523 Value *V = MDString::get(Context, FwdRefName);
Chris Lattner42991ee2009-12-29 22:01:50 +0000524 MDNode *FwdNode = MDNode::get(Context, &V, 1);
Devang Patel256be962009-07-20 19:00:08 +0000525 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000526
527 if (NumberedMetadata.size() <= MID)
528 NumberedMetadata.resize(MID+1);
529 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000530 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000531 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000532}
Devang Patel256be962009-07-20 19:00:08 +0000533
Chris Lattner84d03b12009-12-29 22:35:39 +0000534/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000535/// !foo = !{ !1, !2 }
536bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000537 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000538 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000539 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000540
Chris Lattner84d03b12009-12-29 22:35:39 +0000541 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000542 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000543 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000544 return true;
545
Devang Patel3e30c2a2010-01-05 20:41:31 +0000546 SmallVector<MDNode *, 8> Elts;
Devang Pateleff2ab62009-07-29 00:34:02 +0000547 do {
Devang Patel69d02e02010-01-05 21:47:32 +0000548 // Null is a special case since it is typeless.
549 if (EatIfPresent(lltok::kw_null)) {
550 Elts.push_back(0);
551 continue;
552 }
553
Chris Lattnere434d272009-12-30 04:56:59 +0000554 if (ParseToken(lltok::exclaim, "Expected '!' here"))
Chris Lattner42991ee2009-12-29 22:01:50 +0000555 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000556
Chris Lattner442ffa12009-12-29 21:53:55 +0000557 MDNode *N = 0;
Chris Lattner4a72efc2009-12-30 04:15:23 +0000558 if (ParseMDNodeID(N)) return true;
Devang Pateleff2ab62009-07-29 00:34:02 +0000559 Elts.push_back(N);
560 } while (EatIfPresent(lltok::comma));
561
562 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
563 return true;
564
Owen Anderson1d0be152009-08-13 21:58:54 +0000565 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
Devang Pateleff2ab62009-07-29 00:34:02 +0000566 return false;
567}
568
Devang Patel923078c2009-07-01 19:21:12 +0000569/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000570/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000571bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000572 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000573 Lex.Lex();
574 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000575
576 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000577 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000578 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000579 if (ParseUInt32(MetadataID) ||
580 ParseToken(lltok::equal, "expected '=' here") ||
581 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000582 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000583 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000584 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000585 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000586 return true;
587
Owen Anderson647e3012009-07-31 21:35:40 +0000588 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000589
590 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000591 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000592 FI = ForwardRefMDNodes.find(MetadataID);
593 if (FI != ForwardRefMDNodes.end()) {
Chris Lattnere80250e2009-12-29 21:43:58 +0000594 FI->second.first->replaceAllUsesWith(Init);
Devang Patel1c7eea62009-07-08 19:23:54 +0000595 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000596
597 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
598 } else {
599 if (MetadataID >= NumberedMetadata.size())
600 NumberedMetadata.resize(MetadataID+1);
601
602 if (NumberedMetadata[MetadataID] != 0)
603 return TokError("Metadata id is already used");
604 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000605 }
606
Devang Patel923078c2009-07-01 19:21:12 +0000607 return false;
608}
609
Chris Lattnerdf986172009-01-02 07:01:27 +0000610/// ParseAlias:
611/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
612/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000613/// ::= TypeAndValue
614/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000615/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000616///
617/// Everything through visibility has already been parsed.
618///
619bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
620 unsigned Visibility) {
621 assert(Lex.getKind() == lltok::kw_alias);
622 Lex.Lex();
623 unsigned Linkage;
624 LocTy LinkageLoc = Lex.getLoc();
625 if (ParseOptionalLinkage(Linkage))
626 return true;
627
628 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000629 Linkage != GlobalValue::WeakAnyLinkage &&
630 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000631 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000632 Linkage != GlobalValue::PrivateLinkage &&
633 Linkage != GlobalValue::LinkerPrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000634 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000635
Chris Lattnerdf986172009-01-02 07:01:27 +0000636 Constant *Aliasee;
637 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000638 if (Lex.getKind() != lltok::kw_bitcast &&
639 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000640 if (ParseGlobalTypeAndValue(Aliasee)) return true;
641 } else {
642 // The bitcast dest type is not present, it is implied by the dest type.
643 ValID ID;
644 if (ParseValID(ID)) return true;
645 if (ID.Kind != ValID::t_Constant)
646 return Error(AliaseeLoc, "invalid aliasee");
647 Aliasee = ID.ConstantVal;
648 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000649
Duncan Sands1df98592010-02-16 11:11:14 +0000650 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000651 return Error(AliaseeLoc, "alias must have pointer type");
652
653 // Okay, create the alias but do not insert it into the module yet.
654 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
655 (GlobalValue::LinkageTypes)Linkage, Name,
656 Aliasee);
657 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000658
Chris Lattnerdf986172009-01-02 07:01:27 +0000659 // See if this value already exists in the symbol table. If so, it is either
660 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000661 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000662 // See if this was a redefinition. If so, there is no entry in
663 // ForwardRefVals.
664 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
665 I = ForwardRefVals.find(Name);
666 if (I == ForwardRefVals.end())
667 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
668
669 // Otherwise, this was a definition of forward ref. Verify that types
670 // agree.
671 if (Val->getType() != GA->getType())
672 return Error(NameLoc,
673 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000674
Chris Lattnerdf986172009-01-02 07:01:27 +0000675 // If they agree, just RAUW the old value with the alias and remove the
676 // forward ref info.
677 Val->replaceAllUsesWith(GA);
678 Val->eraseFromParent();
679 ForwardRefVals.erase(I);
680 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000681
Chris Lattnerdf986172009-01-02 07:01:27 +0000682 // Insert into the module, we know its name won't collide now.
683 M->getAliasList().push_back(GA);
684 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000685
Chris Lattnerdf986172009-01-02 07:01:27 +0000686 return false;
687}
688
689/// ParseGlobal
690/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
691/// OptionalAddrSpace GlobalType Type Const
692/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
693/// OptionalAddrSpace GlobalType Type Const
694///
695/// Everything through visibility has been parsed already.
696///
697bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
698 unsigned Linkage, bool HasLinkage,
699 unsigned Visibility) {
700 unsigned AddrSpace;
701 bool ThreadLocal, IsConstant;
702 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000703
Owen Anderson1d0be152009-08-13 21:58:54 +0000704 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000705 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
706 ParseOptionalAddrSpace(AddrSpace) ||
707 ParseGlobalType(IsConstant) ||
708 ParseType(Ty, TyLoc))
709 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000710
Chris Lattnerdf986172009-01-02 07:01:27 +0000711 // If the linkage is specified and is external, then no initializer is
712 // present.
713 Constant *Init = 0;
714 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000715 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000716 Linkage != GlobalValue::ExternalLinkage)) {
717 if (ParseGlobalValue(Ty, Init))
718 return true;
719 }
720
Duncan Sands1df98592010-02-16 11:11:14 +0000721 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000722 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000723
Chris Lattnerdf986172009-01-02 07:01:27 +0000724 GlobalVariable *GV = 0;
725
726 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000727 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000728 if (GlobalValue *GVal = M->getNamedValue(Name)) {
729 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
730 return Error(NameLoc, "redefinition of global '@" + Name + "'");
731 GV = cast<GlobalVariable>(GVal);
732 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000733 } else {
734 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
735 I = ForwardRefValIDs.find(NumberedVals.size());
736 if (I != ForwardRefValIDs.end()) {
737 GV = cast<GlobalVariable>(I->second.first);
738 ForwardRefValIDs.erase(I);
739 }
740 }
741
742 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000743 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000744 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000745 } else {
746 if (GV->getType()->getElementType() != Ty)
747 return Error(TyLoc,
748 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000749
Chris Lattnerdf986172009-01-02 07:01:27 +0000750 // Move the forward-reference to the correct spot in the module.
751 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
752 }
753
754 if (Name.empty())
755 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000756
Chris Lattnerdf986172009-01-02 07:01:27 +0000757 // Set the parsed properties on the global.
758 if (Init)
759 GV->setInitializer(Init);
760 GV->setConstant(IsConstant);
761 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
762 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
763 GV->setThreadLocal(ThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000764
Chris Lattnerdf986172009-01-02 07:01:27 +0000765 // Parse attributes on the global.
766 while (Lex.getKind() == lltok::comma) {
767 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000768
Chris Lattnerdf986172009-01-02 07:01:27 +0000769 if (Lex.getKind() == lltok::kw_section) {
770 Lex.Lex();
771 GV->setSection(Lex.getStrVal());
772 if (ParseToken(lltok::StringConstant, "expected global section string"))
773 return true;
774 } else if (Lex.getKind() == lltok::kw_align) {
775 unsigned Alignment;
776 if (ParseOptionalAlignment(Alignment)) return true;
777 GV->setAlignment(Alignment);
778 } else {
779 TokError("unknown global variable property!");
780 }
781 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000782
Chris Lattnerdf986172009-01-02 07:01:27 +0000783 return false;
784}
785
786
787//===----------------------------------------------------------------------===//
788// GlobalValue Reference/Resolution Routines.
789//===----------------------------------------------------------------------===//
790
791/// GetGlobalVal - Get a value with the specified name or ID, creating a
792/// forward reference record if needed. This can return null if the value
793/// exists but does not have the right type.
794GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
795 LocTy Loc) {
796 const PointerType *PTy = dyn_cast<PointerType>(Ty);
797 if (PTy == 0) {
798 Error(Loc, "global variable reference must have pointer type");
799 return 0;
800 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000801
Chris Lattnerdf986172009-01-02 07:01:27 +0000802 // Look this name up in the normal function symbol table.
803 GlobalValue *Val =
804 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000805
Chris Lattnerdf986172009-01-02 07:01:27 +0000806 // If this is a forward reference for the value, see if we already created a
807 // forward ref record.
808 if (Val == 0) {
809 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
810 I = ForwardRefVals.find(Name);
811 if (I != ForwardRefVals.end())
812 Val = I->second.first;
813 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000814
Chris Lattnerdf986172009-01-02 07:01:27 +0000815 // If we have the value in the symbol table or fwd-ref table, return it.
816 if (Val) {
817 if (Val->getType() == Ty) return Val;
818 Error(Loc, "'@" + Name + "' defined with type '" +
819 Val->getType()->getDescription() + "'");
820 return 0;
821 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000822
Chris Lattnerdf986172009-01-02 07:01:27 +0000823 // Otherwise, create a new forward reference for this value and remember it.
824 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000825 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
826 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000827 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner1e407c32009-01-08 19:05:36 +0000828 Error(Loc, "function may not return opaque type");
829 return 0;
830 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000831
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000832 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000833 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000834 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
835 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000836 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000837
Chris Lattnerdf986172009-01-02 07:01:27 +0000838 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
839 return FwdVal;
840}
841
842GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
843 const PointerType *PTy = dyn_cast<PointerType>(Ty);
844 if (PTy == 0) {
845 Error(Loc, "global variable reference must have pointer type");
846 return 0;
847 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000848
Chris Lattnerdf986172009-01-02 07:01:27 +0000849 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000850
Chris Lattnerdf986172009-01-02 07:01:27 +0000851 // If this is a forward reference for the value, see if we already created a
852 // forward ref record.
853 if (Val == 0) {
854 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
855 I = ForwardRefValIDs.find(ID);
856 if (I != ForwardRefValIDs.end())
857 Val = I->second.first;
858 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000859
Chris Lattnerdf986172009-01-02 07:01:27 +0000860 // If we have the value in the symbol table or fwd-ref table, return it.
861 if (Val) {
862 if (Val->getType() == Ty) return Val;
863 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
864 Val->getType()->getDescription() + "'");
865 return 0;
866 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000867
Chris Lattnerdf986172009-01-02 07:01:27 +0000868 // Otherwise, create a new forward reference for this value and remember it.
869 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000870 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
871 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000872 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000873 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000874 return 0;
875 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000876 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000877 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000878 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
879 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000880 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000881
Chris Lattnerdf986172009-01-02 07:01:27 +0000882 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
883 return FwdVal;
884}
885
886
887//===----------------------------------------------------------------------===//
888// Helper Routines.
889//===----------------------------------------------------------------------===//
890
891/// ParseToken - If the current token has the specified kind, eat it and return
892/// success. Otherwise, emit the specified error and return failure.
893bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
894 if (Lex.getKind() != T)
895 return TokError(ErrMsg);
896 Lex.Lex();
897 return false;
898}
899
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000900/// ParseStringConstant
901/// ::= StringConstant
902bool LLParser::ParseStringConstant(std::string &Result) {
903 if (Lex.getKind() != lltok::StringConstant)
904 return TokError("expected string constant");
905 Result = Lex.getStrVal();
906 Lex.Lex();
907 return false;
908}
909
910/// ParseUInt32
911/// ::= uint32
912bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000913 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
914 return TokError("expected integer");
915 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
916 if (Val64 != unsigned(Val64))
917 return TokError("expected 32-bit integer (too large)");
918 Val = Val64;
919 Lex.Lex();
920 return false;
921}
922
923
924/// ParseOptionalAddrSpace
925/// := /*empty*/
926/// := 'addrspace' '(' uint32 ')'
927bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
928 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000929 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000930 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000931 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000932 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000933 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000934}
Chris Lattnerdf986172009-01-02 07:01:27 +0000935
936/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
937/// indicates what kind of attribute list this is: 0: function arg, 1: result,
938/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000939/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000940bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
941 Attrs = Attribute::None;
942 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000943
Chris Lattnerdf986172009-01-02 07:01:27 +0000944 while (1) {
945 switch (Lex.getKind()) {
946 case lltok::kw_sext:
947 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000948 // Treat these as signext/zeroext if they occur in the argument list after
949 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
950 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
951 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000952 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000953 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000954 if (Lex.getKind() == lltok::kw_sext)
955 Attrs |= Attribute::SExt;
956 else
957 Attrs |= Attribute::ZExt;
958 break;
959 }
960 // FALL THROUGH.
961 default: // End of attributes.
962 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
963 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000964
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000965 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000966 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000967
Chris Lattnerdf986172009-01-02 07:01:27 +0000968 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000969 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
970 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
971 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
972 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
973 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
974 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
975 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
976 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000977
Devang Patel578efa92009-06-05 21:57:13 +0000978 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
979 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
980 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
981 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
982 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000983 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000984 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
985 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
986 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
987 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
988 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
989 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000990 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000991
Charles Davis1e063d12010-02-12 00:31:15 +0000992 case lltok::kw_alignstack: {
993 unsigned Alignment;
994 if (ParseOptionalStackAlignment(Alignment))
995 return true;
996 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
997 continue;
998 }
999
Chris Lattnerdf986172009-01-02 07:01:27 +00001000 case lltok::kw_align: {
1001 unsigned Alignment;
1002 if (ParseOptionalAlignment(Alignment))
1003 return true;
1004 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
1005 continue;
1006 }
Charles Davis1e063d12010-02-12 00:31:15 +00001007
Chris Lattnerdf986172009-01-02 07:01:27 +00001008 }
1009 Lex.Lex();
1010 }
1011}
1012
1013/// ParseOptionalLinkage
1014/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001015/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001016/// ::= 'linker_private'
Chris Lattnerdf986172009-01-02 07:01:27 +00001017/// ::= 'internal'
1018/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001019/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001020/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001021/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001022/// ::= 'appending'
1023/// ::= 'dllexport'
1024/// ::= 'common'
1025/// ::= 'dllimport'
1026/// ::= 'extern_weak'
1027/// ::= 'external'
1028bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1029 HasLinkage = false;
1030 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001031 default: Res=GlobalValue::ExternalLinkage; return false;
1032 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1033 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1034 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1035 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1036 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1037 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1038 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001039 case lltok::kw_available_externally:
1040 Res = GlobalValue::AvailableExternallyLinkage;
1041 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001042 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1043 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1044 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1045 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1046 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1047 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001048 }
1049 Lex.Lex();
1050 HasLinkage = true;
1051 return false;
1052}
1053
1054/// ParseOptionalVisibility
1055/// ::= /*empty*/
1056/// ::= 'default'
1057/// ::= 'hidden'
1058/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001059///
Chris Lattnerdf986172009-01-02 07:01:27 +00001060bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1061 switch (Lex.getKind()) {
1062 default: Res = GlobalValue::DefaultVisibility; return false;
1063 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1064 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1065 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1066 }
1067 Lex.Lex();
1068 return false;
1069}
1070
1071/// ParseOptionalCallingConv
1072/// ::= /*empty*/
1073/// ::= 'ccc'
1074/// ::= 'fastcc'
1075/// ::= 'coldcc'
1076/// ::= 'x86_stdcallcc'
1077/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001078/// ::= 'arm_apcscc'
1079/// ::= 'arm_aapcscc'
1080/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001081/// ::= 'msp430_intrcc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001082/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001083///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001084bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001085 switch (Lex.getKind()) {
1086 default: CC = CallingConv::C; return false;
1087 case lltok::kw_ccc: CC = CallingConv::C; break;
1088 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1089 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1090 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1091 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001092 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1093 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1094 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001095 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001096 case lltok::kw_cc: {
1097 unsigned ArbitraryCC;
1098 Lex.Lex();
1099 if (ParseUInt32(ArbitraryCC)) {
1100 return true;
1101 } else
1102 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1103 return false;
1104 }
1105 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001106 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001107
Chris Lattnerdf986172009-01-02 07:01:27 +00001108 Lex.Lex();
1109 return false;
1110}
1111
Chris Lattnerb8c46862009-12-30 05:31:19 +00001112/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001113/// ::= !dbg !42 (',' !dbg !57)*
Chris Lattnerfe805242010-04-01 04:51:13 +00001114bool LLParser::ParseInstructionMetadata(Instruction *Inst) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001115 do {
1116 if (Lex.getKind() != lltok::MetadataVar)
1117 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001118
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001119 std::string Name = Lex.getStrVal();
1120 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001121
Chris Lattner442ffa12009-12-29 21:53:55 +00001122 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001123 unsigned NodeID;
1124 SMLoc Loc = Lex.getLoc();
Chris Lattnere434d272009-12-30 04:56:59 +00001125 if (ParseToken(lltok::exclaim, "expected '!' here") ||
Chris Lattner449c3102010-04-01 05:14:45 +00001126 ParseMDNodeID(Node, NodeID))
Chris Lattnere434d272009-12-30 04:56:59 +00001127 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001128
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001129 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner449c3102010-04-01 05:14:45 +00001130 if (Node) {
1131 // If we got the node, add it to the instruction.
1132 Inst->setMetadata(MDK, Node);
1133 } else {
1134 MDRef R = { Loc, MDK, NodeID };
1135 // Otherwise, remember that this should be resolved later.
1136 ForwardRefInstMetadata[Inst].push_back(R);
1137 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001138
1139 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001140 } while (EatIfPresent(lltok::comma));
1141 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001142}
1143
Chris Lattnerdf986172009-01-02 07:01:27 +00001144/// ParseOptionalAlignment
1145/// ::= /* empty */
1146/// ::= 'align' 4
1147bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1148 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001149 if (!EatIfPresent(lltok::kw_align))
1150 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001151 LocTy AlignLoc = Lex.getLoc();
1152 if (ParseUInt32(Alignment)) return true;
1153 if (!isPowerOf2_32(Alignment))
1154 return Error(AlignLoc, "alignment is not a power of two");
1155 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001156}
1157
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001158/// ParseOptionalCommaAlign
1159/// ::=
1160/// ::= ',' align 4
1161///
1162/// This returns with AteExtraComma set to true if it ate an excess comma at the
1163/// end.
1164bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1165 bool &AteExtraComma) {
1166 AteExtraComma = false;
1167 while (EatIfPresent(lltok::comma)) {
1168 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001169 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001170 AteExtraComma = true;
1171 return false;
1172 }
1173
1174 if (Lex.getKind() == lltok::kw_align) {
Devang Patelf633a062009-09-17 23:04:48 +00001175 if (ParseOptionalAlignment(Alignment)) return true;
1176 } else
1177 return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001178 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001179
Devang Patelf633a062009-09-17 23:04:48 +00001180 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001181}
1182
Charles Davis1e063d12010-02-12 00:31:15 +00001183/// ParseOptionalStackAlignment
1184/// ::= /* empty */
1185/// ::= 'alignstack' '(' 4 ')'
1186bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1187 Alignment = 0;
1188 if (!EatIfPresent(lltok::kw_alignstack))
1189 return false;
1190 LocTy ParenLoc = Lex.getLoc();
1191 if (!EatIfPresent(lltok::lparen))
1192 return Error(ParenLoc, "expected '('");
1193 LocTy AlignLoc = Lex.getLoc();
1194 if (ParseUInt32(Alignment)) return true;
1195 ParenLoc = Lex.getLoc();
1196 if (!EatIfPresent(lltok::rparen))
1197 return Error(ParenLoc, "expected ')'");
1198 if (!isPowerOf2_32(Alignment))
1199 return Error(AlignLoc, "stack alignment is not a power of two");
1200 return false;
1201}
Devang Patelf633a062009-09-17 23:04:48 +00001202
Chris Lattner628c13a2009-12-30 05:14:00 +00001203/// ParseIndexList - This parses the index list for an insert/extractvalue
1204/// instruction. This sets AteExtraComma in the case where we eat an extra
1205/// comma at the end of the line and find that it is followed by metadata.
1206/// Clients that don't allow metadata can call the version of this function that
1207/// only takes one argument.
1208///
Chris Lattnerdf986172009-01-02 07:01:27 +00001209/// ParseIndexList
1210/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001211///
1212bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1213 bool &AteExtraComma) {
1214 AteExtraComma = false;
1215
Chris Lattnerdf986172009-01-02 07:01:27 +00001216 if (Lex.getKind() != lltok::comma)
1217 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001218
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001219 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001220 if (Lex.getKind() == lltok::MetadataVar) {
1221 AteExtraComma = true;
1222 return false;
1223 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001224 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001225 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001226 Indices.push_back(Idx);
1227 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001228
Chris Lattnerdf986172009-01-02 07:01:27 +00001229 return false;
1230}
1231
1232//===----------------------------------------------------------------------===//
1233// Type Parsing.
1234//===----------------------------------------------------------------------===//
1235
1236/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001237bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1238 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001239 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001240
Chris Lattnerdf986172009-01-02 07:01:27 +00001241 // Verify no unresolved uprefs.
1242 if (!UpRefs.empty())
1243 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001244
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001245 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001246 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001247
Chris Lattnerdf986172009-01-02 07:01:27 +00001248 return false;
1249}
1250
1251/// HandleUpRefs - Every time we finish a new layer of types, this function is
1252/// called. It loops through the UpRefs vector, which is a list of the
1253/// currently active types. For each type, if the up-reference is contained in
1254/// the newly completed type, we decrement the level count. When the level
1255/// count reaches zero, the up-referenced type is the type that is passed in:
1256/// thus we can complete the cycle.
1257///
1258PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1259 // If Ty isn't abstract, or if there are no up-references in it, then there is
1260 // nothing to resolve here.
1261 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001262
Chris Lattnerdf986172009-01-02 07:01:27 +00001263 PATypeHolder Ty(ty);
1264#if 0
David Greene0e28d762009-12-23 23:38:28 +00001265 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001266 << "' newly formed. Resolving upreferences.\n"
1267 << UpRefs.size() << " upreferences active!\n";
1268#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001269
Chris Lattnerdf986172009-01-02 07:01:27 +00001270 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1271 // to zero), we resolve them all together before we resolve them to Ty. At
1272 // the end of the loop, if there is anything to resolve to Ty, it will be in
1273 // this variable.
1274 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001275
Chris Lattnerdf986172009-01-02 07:01:27 +00001276 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1277 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1278 bool ContainsType =
1279 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1280 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001281
Chris Lattnerdf986172009-01-02 07:01:27 +00001282#if 0
David Greene0e28d762009-12-23 23:38:28 +00001283 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001284 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1285 << (ContainsType ? "true" : "false")
1286 << " level=" << UpRefs[i].NestingLevel << "\n";
1287#endif
1288 if (!ContainsType)
1289 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001290
Chris Lattnerdf986172009-01-02 07:01:27 +00001291 // Decrement level of upreference
1292 unsigned Level = --UpRefs[i].NestingLevel;
1293 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001294
Chris Lattnerdf986172009-01-02 07:01:27 +00001295 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1296 if (Level != 0)
1297 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001298
Chris Lattnerdf986172009-01-02 07:01:27 +00001299#if 0
David Greene0e28d762009-12-23 23:38:28 +00001300 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001301#endif
1302 if (!TypeToResolve)
1303 TypeToResolve = UpRefs[i].UpRefTy;
1304 else
1305 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1306 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1307 --i; // Do not skip the next element.
1308 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001309
Chris Lattnerdf986172009-01-02 07:01:27 +00001310 if (TypeToResolve)
1311 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001312
Chris Lattnerdf986172009-01-02 07:01:27 +00001313 return Ty;
1314}
1315
1316
1317/// ParseTypeRec - The recursive function used to process the internal
1318/// implementation details of types.
1319bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1320 switch (Lex.getKind()) {
1321 default:
1322 return TokError("expected type");
1323 case lltok::Type:
1324 // TypeRec ::= 'float' | 'void' (etc)
1325 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001326 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001327 break;
1328 case lltok::kw_opaque:
1329 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001330 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001331 Lex.Lex();
1332 break;
1333 case lltok::lbrace:
1334 // TypeRec ::= '{' ... '}'
1335 if (ParseStructType(Result, false))
1336 return true;
1337 break;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00001338 case lltok::kw_union:
1339 // TypeRec ::= 'union' '{' ... '}'
1340 if (ParseUnionType(Result))
1341 return true;
1342 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001343 case lltok::lsquare:
1344 // TypeRec ::= '[' ... ']'
1345 Lex.Lex(); // eat the lsquare.
1346 if (ParseArrayVectorType(Result, false))
1347 return true;
1348 break;
1349 case lltok::less: // Either vector or packed struct.
1350 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001351 Lex.Lex();
1352 if (Lex.getKind() == lltok::lbrace) {
1353 if (ParseStructType(Result, true) ||
1354 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001355 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001356 } else if (ParseArrayVectorType(Result, true))
1357 return true;
1358 break;
1359 case lltok::LocalVar:
1360 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1361 // TypeRec ::= %foo
1362 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1363 Result = T;
1364 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001365 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001366 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1367 std::make_pair(Result,
1368 Lex.getLoc())));
1369 M->addTypeName(Lex.getStrVal(), Result.get());
1370 }
1371 Lex.Lex();
1372 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001373
Chris Lattnerdf986172009-01-02 07:01:27 +00001374 case lltok::LocalVarID:
1375 // TypeRec ::= %4
1376 if (Lex.getUIntVal() < NumberedTypes.size())
1377 Result = NumberedTypes[Lex.getUIntVal()];
1378 else {
1379 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1380 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1381 if (I != ForwardRefTypeIDs.end())
1382 Result = I->second.first;
1383 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001384 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001385 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1386 std::make_pair(Result,
1387 Lex.getLoc())));
1388 }
1389 }
1390 Lex.Lex();
1391 break;
1392 case lltok::backslash: {
1393 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001394 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001395 unsigned Val;
1396 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001397 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001398 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1399 Result = OT;
1400 break;
1401 }
1402 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001403
1404 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001405 while (1) {
1406 switch (Lex.getKind()) {
1407 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001408 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001409
1410 // TypeRec ::= TypeRec '*'
1411 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001412 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001413 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001414 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001415 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001416 if (!PointerType::isValidElementType(Result.get()))
1417 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001418 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001419 Lex.Lex();
1420 break;
1421
1422 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1423 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001424 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001425 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001426 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001427 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001428 if (!PointerType::isValidElementType(Result.get()))
1429 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001430 unsigned AddrSpace;
1431 if (ParseOptionalAddrSpace(AddrSpace) ||
1432 ParseToken(lltok::star, "expected '*' in address space"))
1433 return true;
1434
Owen Andersondebcb012009-07-29 22:17:13 +00001435 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001436 break;
1437 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001438
Chris Lattnerdf986172009-01-02 07:01:27 +00001439 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1440 case lltok::lparen:
1441 if (ParseFunctionType(Result))
1442 return true;
1443 break;
1444 }
1445 }
1446}
1447
1448/// ParseParameterList
1449/// ::= '(' ')'
1450/// ::= '(' Arg (',' Arg)* ')'
1451/// Arg
1452/// ::= Type OptionalAttributes Value OptionalAttributes
1453bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1454 PerFunctionState &PFS) {
1455 if (ParseToken(lltok::lparen, "expected '(' in call"))
1456 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001457
Chris Lattnerdf986172009-01-02 07:01:27 +00001458 while (Lex.getKind() != lltok::rparen) {
1459 // If this isn't the first argument, we need a comma.
1460 if (!ArgList.empty() &&
1461 ParseToken(lltok::comma, "expected ',' in argument list"))
1462 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001463
Chris Lattnerdf986172009-01-02 07:01:27 +00001464 // Parse the argument.
1465 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001466 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001467 unsigned ArgAttrs1 = Attribute::None;
1468 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001469 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001470 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001471 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001472
Chris Lattner287881d2009-12-30 02:11:14 +00001473 // Otherwise, handle normal operands.
1474 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1475 ParseValue(ArgTy, V, PFS) ||
1476 // FIXME: Should not allow attributes after the argument, remove this
1477 // in LLVM 3.0.
1478 ParseOptionalAttrs(ArgAttrs2, 3))
1479 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001480 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1481 }
1482
1483 Lex.Lex(); // Lex the ')'.
1484 return false;
1485}
1486
1487
1488
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001489/// ParseArgumentList - Parse the argument list for a function type or function
1490/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001491/// ::= '(' ArgTypeListI ')'
1492/// ArgTypeListI
1493/// ::= /*empty*/
1494/// ::= '...'
1495/// ::= ArgTypeList ',' '...'
1496/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001497///
Chris Lattnerdf986172009-01-02 07:01:27 +00001498bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001499 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001500 isVarArg = false;
1501 assert(Lex.getKind() == lltok::lparen);
1502 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001503
Chris Lattnerdf986172009-01-02 07:01:27 +00001504 if (Lex.getKind() == lltok::rparen) {
1505 // empty
1506 } else if (Lex.getKind() == lltok::dotdotdot) {
1507 isVarArg = true;
1508 Lex.Lex();
1509 } else {
1510 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001511 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001512 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001513 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001514
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001515 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1516 // types (such as a function returning a pointer to itself). If parsing a
1517 // function prototype, we require fully resolved types.
1518 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001519 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001520
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001521 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001522 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001523
Chris Lattnerdf986172009-01-02 07:01:27 +00001524 if (Lex.getKind() == lltok::LocalVar ||
1525 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1526 Name = Lex.getStrVal();
1527 Lex.Lex();
1528 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001529
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001530 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001531 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001532
Chris Lattnerdf986172009-01-02 07:01:27 +00001533 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001534
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001535 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001536 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001537 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001538 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001539 break;
1540 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001541
Chris Lattnerdf986172009-01-02 07:01:27 +00001542 // Otherwise must be an argument type.
1543 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001544 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001545 ParseOptionalAttrs(Attrs, 0)) return true;
1546
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001547 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001548 return Error(TypeLoc, "argument can not have void type");
1549
Chris Lattnerdf986172009-01-02 07:01:27 +00001550 if (Lex.getKind() == lltok::LocalVar ||
1551 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1552 Name = Lex.getStrVal();
1553 Lex.Lex();
1554 } else {
1555 Name = "";
1556 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001557
Duncan Sands47c51882010-02-16 14:50:09 +00001558 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001559 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001560
Chris Lattnerdf986172009-01-02 07:01:27 +00001561 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1562 }
1563 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001564
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001565 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001566}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001567
Chris Lattnerdf986172009-01-02 07:01:27 +00001568/// ParseFunctionType
1569/// ::= Type ArgumentList OptionalAttrs
1570bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1571 assert(Lex.getKind() == lltok::lparen);
1572
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001573 if (!FunctionType::isValidReturnType(Result))
1574 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001575
Chris Lattnerdf986172009-01-02 07:01:27 +00001576 std::vector<ArgInfo> ArgList;
1577 bool isVarArg;
1578 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001579 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001580 // FIXME: Allow, but ignore attributes on function types!
1581 // FIXME: Remove in LLVM 3.0
1582 ParseOptionalAttrs(Attrs, 2))
1583 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001584
Chris Lattnerdf986172009-01-02 07:01:27 +00001585 // Reject names on the arguments lists.
1586 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1587 if (!ArgList[i].Name.empty())
1588 return Error(ArgList[i].Loc, "argument name invalid in function type");
1589 if (!ArgList[i].Attrs != 0) {
1590 // Allow but ignore attributes on function types; this permits
1591 // auto-upgrade.
1592 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1593 }
1594 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001595
Chris Lattnerdf986172009-01-02 07:01:27 +00001596 std::vector<const Type*> ArgListTy;
1597 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1598 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001599
Owen Andersondebcb012009-07-29 22:17:13 +00001600 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001601 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001602 return false;
1603}
1604
1605/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1606/// TypeRec
1607/// ::= '{' '}'
1608/// ::= '{' TypeRec (',' TypeRec)* '}'
1609/// ::= '<' '{' '}' '>'
1610/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1611bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1612 assert(Lex.getKind() == lltok::lbrace);
1613 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001614
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001615 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001616 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001617 return false;
1618 }
1619
1620 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001621 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001622 if (ParseTypeRec(Result)) return true;
1623 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001624
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001625 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001626 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001627 if (!StructType::isValidElementType(Result))
1628 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001629
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001630 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001631 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001632 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001633
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001634 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001635 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001636 if (!StructType::isValidElementType(Result))
1637 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001638
Chris Lattnerdf986172009-01-02 07:01:27 +00001639 ParamsList.push_back(Result);
1640 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001641
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001642 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1643 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001644
Chris Lattnerdf986172009-01-02 07:01:27 +00001645 std::vector<const Type*> ParamsListTy;
1646 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1647 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001648 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001649 return false;
1650}
1651
Chris Lattnerfdfeb692010-02-12 20:49:41 +00001652/// ParseUnionType
1653/// TypeRec
1654/// ::= 'union' '{' TypeRec (',' TypeRec)* '}'
1655bool LLParser::ParseUnionType(PATypeHolder &Result) {
1656 assert(Lex.getKind() == lltok::kw_union);
1657 Lex.Lex(); // Consume the 'union'
1658
1659 if (ParseToken(lltok::lbrace, "'{' expected after 'union'")) return true;
1660
1661 SmallVector<PATypeHolder, 8> ParamsList;
1662 do {
1663 LocTy EltTyLoc = Lex.getLoc();
1664 if (ParseTypeRec(Result)) return true;
1665 ParamsList.push_back(Result);
1666
1667 if (Result->isVoidTy())
1668 return Error(EltTyLoc, "union element can not have void type");
1669 if (!UnionType::isValidElementType(Result))
1670 return Error(EltTyLoc, "invalid element type for union");
1671
1672 } while (EatIfPresent(lltok::comma)) ;
1673
1674 if (ParseToken(lltok::rbrace, "expected '}' at end of union"))
1675 return true;
1676
1677 SmallVector<const Type*, 8> ParamsListTy;
1678 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1679 ParamsListTy.push_back(ParamsList[i].get());
1680 Result = HandleUpRefs(UnionType::get(&ParamsListTy[0], ParamsListTy.size()));
1681 return false;
1682}
1683
Chris Lattnerdf986172009-01-02 07:01:27 +00001684/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1685/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001686/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001687/// ::= '[' APSINTVAL 'x' Types ']'
1688/// ::= '<' APSINTVAL 'x' Types '>'
1689bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1690 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1691 Lex.getAPSIntVal().getBitWidth() > 64)
1692 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001693
Chris Lattnerdf986172009-01-02 07:01:27 +00001694 LocTy SizeLoc = Lex.getLoc();
1695 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001696 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001697
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001698 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1699 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001700
1701 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001702 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001703 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001704
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001705 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001706 return Error(TypeLoc, "array and vector element type cannot be void");
1707
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001708 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1709 "expected end of sequential type"))
1710 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001711
Chris Lattnerdf986172009-01-02 07:01:27 +00001712 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001713 if (Size == 0)
1714 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001715 if ((unsigned)Size != Size)
1716 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001717 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001718 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001719 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001720 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001721 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001722 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001723 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001724 }
1725 return false;
1726}
1727
1728//===----------------------------------------------------------------------===//
1729// Function Semantic Analysis.
1730//===----------------------------------------------------------------------===//
1731
Chris Lattner09d9ef42009-10-28 03:39:23 +00001732LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1733 int functionNumber)
1734 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001735
1736 // Insert unnamed arguments into the NumberedVals list.
1737 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1738 AI != E; ++AI)
1739 if (!AI->hasName())
1740 NumberedVals.push_back(AI);
1741}
1742
1743LLParser::PerFunctionState::~PerFunctionState() {
1744 // If there were any forward referenced non-basicblock values, delete them.
1745 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1746 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1747 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001748 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001749 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001750 delete I->second.first;
1751 I->second.first = 0;
1752 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001753
Chris Lattnerdf986172009-01-02 07:01:27 +00001754 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1755 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1756 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001757 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001758 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001759 delete I->second.first;
1760 I->second.first = 0;
1761 }
1762}
1763
Chris Lattner09d9ef42009-10-28 03:39:23 +00001764bool LLParser::PerFunctionState::FinishFunction() {
1765 // Check to see if someone took the address of labels in this block.
1766 if (!P.ForwardRefBlockAddresses.empty()) {
1767 ValID FunctionID;
1768 if (!F.getName().empty()) {
1769 FunctionID.Kind = ValID::t_GlobalName;
1770 FunctionID.StrVal = F.getName();
1771 } else {
1772 FunctionID.Kind = ValID::t_GlobalID;
1773 FunctionID.UIntVal = FunctionNumber;
1774 }
1775
1776 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1777 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1778 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1779 // Resolve all these references.
1780 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1781 return true;
1782
1783 P.ForwardRefBlockAddresses.erase(FRBAI);
1784 }
1785 }
1786
Chris Lattnerdf986172009-01-02 07:01:27 +00001787 if (!ForwardRefVals.empty())
1788 return P.Error(ForwardRefVals.begin()->second.second,
1789 "use of undefined value '%" + ForwardRefVals.begin()->first +
1790 "'");
1791 if (!ForwardRefValIDs.empty())
1792 return P.Error(ForwardRefValIDs.begin()->second.second,
1793 "use of undefined value '%" +
1794 utostr(ForwardRefValIDs.begin()->first) + "'");
1795 return false;
1796}
1797
1798
1799/// GetVal - Get a value with the specified name or ID, creating a
1800/// forward reference record if needed. This can return null if the value
1801/// exists but does not have the right type.
1802Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1803 const Type *Ty, LocTy Loc) {
1804 // Look this name up in the normal function symbol table.
1805 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001806
Chris Lattnerdf986172009-01-02 07:01:27 +00001807 // If this is a forward reference for the value, see if we already created a
1808 // forward ref record.
1809 if (Val == 0) {
1810 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1811 I = ForwardRefVals.find(Name);
1812 if (I != ForwardRefVals.end())
1813 Val = I->second.first;
1814 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001815
Chris Lattnerdf986172009-01-02 07:01:27 +00001816 // If we have the value in the symbol table or fwd-ref table, return it.
1817 if (Val) {
1818 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001819 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001820 P.Error(Loc, "'%" + Name + "' is not a basic block");
1821 else
1822 P.Error(Loc, "'%" + Name + "' defined with type '" +
1823 Val->getType()->getDescription() + "'");
1824 return 0;
1825 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001826
Chris Lattnerdf986172009-01-02 07:01:27 +00001827 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001828 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001829 P.Error(Loc, "invalid use of a non-first-class type");
1830 return 0;
1831 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001832
Chris Lattnerdf986172009-01-02 07:01:27 +00001833 // Otherwise, create a new forward reference for this value and remember it.
1834 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001835 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001836 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001837 else
1838 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001839
Chris Lattnerdf986172009-01-02 07:01:27 +00001840 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1841 return FwdVal;
1842}
1843
1844Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1845 LocTy Loc) {
1846 // Look this name up in the normal function symbol table.
1847 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001848
Chris Lattnerdf986172009-01-02 07:01:27 +00001849 // If this is a forward reference for the value, see if we already created a
1850 // forward ref record.
1851 if (Val == 0) {
1852 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1853 I = ForwardRefValIDs.find(ID);
1854 if (I != ForwardRefValIDs.end())
1855 Val = I->second.first;
1856 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001857
Chris Lattnerdf986172009-01-02 07:01:27 +00001858 // If we have the value in the symbol table or fwd-ref table, return it.
1859 if (Val) {
1860 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001861 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001862 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1863 else
1864 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1865 Val->getType()->getDescription() + "'");
1866 return 0;
1867 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001868
Duncan Sands47c51882010-02-16 14:50:09 +00001869 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001870 P.Error(Loc, "invalid use of a non-first-class type");
1871 return 0;
1872 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001873
Chris Lattnerdf986172009-01-02 07:01:27 +00001874 // Otherwise, create a new forward reference for this value and remember it.
1875 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001876 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001877 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001878 else
1879 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001880
Chris Lattnerdf986172009-01-02 07:01:27 +00001881 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1882 return FwdVal;
1883}
1884
1885/// SetInstName - After an instruction is parsed and inserted into its
1886/// basic block, this installs its name.
1887bool LLParser::PerFunctionState::SetInstName(int NameID,
1888 const std::string &NameStr,
1889 LocTy NameLoc, Instruction *Inst) {
1890 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001891 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001892 if (NameID != -1 || !NameStr.empty())
1893 return P.Error(NameLoc, "instructions returning void cannot have a name");
1894 return false;
1895 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001896
Chris Lattnerdf986172009-01-02 07:01:27 +00001897 // If this was a numbered instruction, verify that the instruction is the
1898 // expected value and resolve any forward references.
1899 if (NameStr.empty()) {
1900 // If neither a name nor an ID was specified, just use the next ID.
1901 if (NameID == -1)
1902 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001903
Chris Lattnerdf986172009-01-02 07:01:27 +00001904 if (unsigned(NameID) != NumberedVals.size())
1905 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1906 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001907
Chris Lattnerdf986172009-01-02 07:01:27 +00001908 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1909 ForwardRefValIDs.find(NameID);
1910 if (FI != ForwardRefValIDs.end()) {
1911 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001912 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001913 FI->second.first->getType()->getDescription() + "'");
1914 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001915 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001916 ForwardRefValIDs.erase(FI);
1917 }
1918
1919 NumberedVals.push_back(Inst);
1920 return false;
1921 }
1922
1923 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1924 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1925 FI = ForwardRefVals.find(NameStr);
1926 if (FI != ForwardRefVals.end()) {
1927 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001928 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001929 FI->second.first->getType()->getDescription() + "'");
1930 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001931 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001932 ForwardRefVals.erase(FI);
1933 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001934
Chris Lattnerdf986172009-01-02 07:01:27 +00001935 // Set the name on the instruction.
1936 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001937
Chris Lattnerdf986172009-01-02 07:01:27 +00001938 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001939 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001940 NameStr + "'");
1941 return false;
1942}
1943
1944/// GetBB - Get a basic block with the specified name or ID, creating a
1945/// forward reference record if needed.
1946BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1947 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001948 return cast_or_null<BasicBlock>(GetVal(Name,
1949 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001950}
1951
1952BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001953 return cast_or_null<BasicBlock>(GetVal(ID,
1954 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001955}
1956
1957/// DefineBB - Define the specified basic block, which is either named or
1958/// unnamed. If there is an error, this returns null otherwise it returns
1959/// the block being defined.
1960BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1961 LocTy Loc) {
1962 BasicBlock *BB;
1963 if (Name.empty())
1964 BB = GetBB(NumberedVals.size(), Loc);
1965 else
1966 BB = GetBB(Name, Loc);
1967 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001968
Chris Lattnerdf986172009-01-02 07:01:27 +00001969 // Move the block to the end of the function. Forward ref'd blocks are
1970 // inserted wherever they happen to be referenced.
1971 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001972
Chris Lattnerdf986172009-01-02 07:01:27 +00001973 // Remove the block from forward ref sets.
1974 if (Name.empty()) {
1975 ForwardRefValIDs.erase(NumberedVals.size());
1976 NumberedVals.push_back(BB);
1977 } else {
1978 // BB forward references are already in the function symbol table.
1979 ForwardRefVals.erase(Name);
1980 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001981
Chris Lattnerdf986172009-01-02 07:01:27 +00001982 return BB;
1983}
1984
1985//===----------------------------------------------------------------------===//
1986// Constants.
1987//===----------------------------------------------------------------------===//
1988
1989/// ParseValID - Parse an abstract value that doesn't necessarily have a
1990/// type implied. For example, if we parse "4" we don't know what integer type
1991/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001992/// sanity. PFS is used to convert function-local operands of metadata (since
1993/// metadata operands are not just parsed here but also converted to values).
1994/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001995bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001996 ID.Loc = Lex.getLoc();
1997 switch (Lex.getKind()) {
1998 default: return TokError("expected value token");
1999 case lltok::GlobalID: // @42
2000 ID.UIntVal = Lex.getUIntVal();
2001 ID.Kind = ValID::t_GlobalID;
2002 break;
2003 case lltok::GlobalVar: // @foo
2004 ID.StrVal = Lex.getStrVal();
2005 ID.Kind = ValID::t_GlobalName;
2006 break;
2007 case lltok::LocalVarID: // %42
2008 ID.UIntVal = Lex.getUIntVal();
2009 ID.Kind = ValID::t_LocalID;
2010 break;
2011 case lltok::LocalVar: // %foo
2012 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2013 ID.StrVal = Lex.getStrVal();
2014 ID.Kind = ValID::t_LocalName;
2015 break;
Chris Lattnere434d272009-12-30 04:56:59 +00002016 case lltok::exclaim: // !{...} MDNode, !"foo" MDString
Nick Lewycky21cc4462009-04-04 07:22:01 +00002017 Lex.Lex();
Chris Lattner442ffa12009-12-29 21:53:55 +00002018
Chris Lattner3f5132a2009-12-29 22:40:21 +00002019 if (EatIfPresent(lltok::lbrace)) {
Nick Lewyckycb337992009-05-10 20:57:05 +00002020 SmallVector<Value*, 16> Elts;
Victor Hernandez24e64df2010-01-10 07:14:18 +00002021 if (ParseMDNodeVector(Elts, PFS) ||
Nick Lewycky21cc4462009-04-04 07:22:01 +00002022 ParseToken(lltok::rbrace, "expected end of metadata node"))
2023 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00002024
Victor Hernandez24e64df2010-01-10 07:14:18 +00002025 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
Chris Lattner287881d2009-12-30 02:11:14 +00002026 ID.Kind = ValID::t_MDNode;
Nick Lewycky21cc4462009-04-04 07:22:01 +00002027 return false;
2028 }
2029
Devang Patel923078c2009-07-01 19:21:12 +00002030 // Standalone metadata reference
2031 // !{ ..., !42, ... }
Chris Lattner860775c2009-12-30 04:13:37 +00002032 if (Lex.getKind() == lltok::APSInt) {
Chris Lattner4a72efc2009-12-30 04:15:23 +00002033 if (ParseMDNodeID(ID.MDNodeVal)) return true;
Chris Lattner287881d2009-12-30 02:11:14 +00002034 ID.Kind = ValID::t_MDNode;
Devang Patel923078c2009-07-01 19:21:12 +00002035 return false;
Chris Lattner287881d2009-12-30 02:11:14 +00002036 }
2037
Nick Lewycky21cc4462009-04-04 07:22:01 +00002038 // MDString:
2039 // ::= '!' STRINGCONSTANT
Chris Lattner287881d2009-12-30 02:11:14 +00002040 if (ParseMDString(ID.MDStringVal)) return true;
2041 ID.Kind = ValID::t_MDString;
Nick Lewycky21cc4462009-04-04 07:22:01 +00002042 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002043 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002044 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002045 ID.Kind = ValID::t_APSInt;
2046 break;
2047 case lltok::APFloat:
2048 ID.APFloatVal = Lex.getAPFloatVal();
2049 ID.Kind = ValID::t_APFloat;
2050 break;
2051 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002052 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002053 ID.Kind = ValID::t_Constant;
2054 break;
2055 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002056 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002057 ID.Kind = ValID::t_Constant;
2058 break;
2059 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2060 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2061 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002062
Chris Lattnerdf986172009-01-02 07:01:27 +00002063 case lltok::lbrace: {
2064 // ValID ::= '{' ConstVector '}'
2065 Lex.Lex();
2066 SmallVector<Constant*, 16> Elts;
2067 if (ParseGlobalValueVector(Elts) ||
2068 ParseToken(lltok::rbrace, "expected end of struct constant"))
2069 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002070
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002071 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2072 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002073 ID.Kind = ValID::t_Constant;
2074 return false;
2075 }
2076 case lltok::less: {
2077 // ValID ::= '<' ConstVector '>' --> Vector.
2078 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2079 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002080 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002081
Chris Lattnerdf986172009-01-02 07:01:27 +00002082 SmallVector<Constant*, 16> Elts;
2083 LocTy FirstEltLoc = Lex.getLoc();
2084 if (ParseGlobalValueVector(Elts) ||
2085 (isPackedStruct &&
2086 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2087 ParseToken(lltok::greater, "expected end of constant"))
2088 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002089
Chris Lattnerdf986172009-01-02 07:01:27 +00002090 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002091 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002092 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002093 ID.Kind = ValID::t_Constant;
2094 return false;
2095 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002096
Chris Lattnerdf986172009-01-02 07:01:27 +00002097 if (Elts.empty())
2098 return Error(ID.Loc, "constant vector must not be empty");
2099
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002100 if (!Elts[0]->getType()->isIntegerTy() &&
2101 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002102 return Error(FirstEltLoc,
2103 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002104
Chris Lattnerdf986172009-01-02 07:01:27 +00002105 // Verify that all the vector elements have the same type.
2106 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2107 if (Elts[i]->getType() != Elts[0]->getType())
2108 return Error(FirstEltLoc,
2109 "vector element #" + utostr(i) +
2110 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002111
Owen Andersonaf7ec972009-07-28 21:19:26 +00002112 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002113 ID.Kind = ValID::t_Constant;
2114 return false;
2115 }
2116 case lltok::lsquare: { // Array Constant
2117 Lex.Lex();
2118 SmallVector<Constant*, 16> Elts;
2119 LocTy FirstEltLoc = Lex.getLoc();
2120 if (ParseGlobalValueVector(Elts) ||
2121 ParseToken(lltok::rsquare, "expected end of array constant"))
2122 return true;
2123
2124 // Handle empty element.
2125 if (Elts.empty()) {
2126 // Use undef instead of an array because it's inconvenient to determine
2127 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002128 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002129 return false;
2130 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002131
Chris Lattnerdf986172009-01-02 07:01:27 +00002132 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002133 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002134 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002135
Owen Andersondebcb012009-07-29 22:17:13 +00002136 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002137
Chris Lattnerdf986172009-01-02 07:01:27 +00002138 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002139 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002140 if (Elts[i]->getType() != Elts[0]->getType())
2141 return Error(FirstEltLoc,
2142 "array element #" + utostr(i) +
2143 " is not of type '" +Elts[0]->getType()->getDescription());
2144 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002145
Owen Anderson1fd70962009-07-28 18:32:17 +00002146 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002147 ID.Kind = ValID::t_Constant;
2148 return false;
2149 }
2150 case lltok::kw_c: // c "foo"
2151 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002152 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002153 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2154 ID.Kind = ValID::t_Constant;
2155 return false;
2156
2157 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002158 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2159 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002160 Lex.Lex();
2161 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002162 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002163 ParseStringConstant(ID.StrVal) ||
2164 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002165 ParseToken(lltok::StringConstant, "expected constraint string"))
2166 return true;
2167 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002168 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002169 ID.Kind = ValID::t_InlineAsm;
2170 return false;
2171 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002172
Chris Lattner09d9ef42009-10-28 03:39:23 +00002173 case lltok::kw_blockaddress: {
2174 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2175 Lex.Lex();
2176
2177 ValID Fn, Label;
2178 LocTy FnLoc, LabelLoc;
2179
2180 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2181 ParseValID(Fn) ||
2182 ParseToken(lltok::comma, "expected comma in block address expression")||
2183 ParseValID(Label) ||
2184 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2185 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002186
Chris Lattner09d9ef42009-10-28 03:39:23 +00002187 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2188 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002189 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002190 return Error(Label.Loc, "expected basic block name in blockaddress");
2191
2192 // Make a global variable as a placeholder for this reference.
2193 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2194 false, GlobalValue::InternalLinkage,
2195 0, "");
2196 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2197 ID.ConstantVal = FwdRef;
2198 ID.Kind = ValID::t_Constant;
2199 return false;
2200 }
2201
Chris Lattnerdf986172009-01-02 07:01:27 +00002202 case lltok::kw_trunc:
2203 case lltok::kw_zext:
2204 case lltok::kw_sext:
2205 case lltok::kw_fptrunc:
2206 case lltok::kw_fpext:
2207 case lltok::kw_bitcast:
2208 case lltok::kw_uitofp:
2209 case lltok::kw_sitofp:
2210 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002211 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002212 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002213 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002214 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002215 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002216 Constant *SrcVal;
2217 Lex.Lex();
2218 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2219 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002220 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002221 ParseType(DestTy) ||
2222 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2223 return true;
2224 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2225 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2226 SrcVal->getType()->getDescription() + "' to '" +
2227 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002228 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002229 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002230 ID.Kind = ValID::t_Constant;
2231 return false;
2232 }
2233 case lltok::kw_extractvalue: {
2234 Lex.Lex();
2235 Constant *Val;
2236 SmallVector<unsigned, 4> Indices;
2237 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2238 ParseGlobalTypeAndValue(Val) ||
2239 ParseIndexList(Indices) ||
2240 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2241 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002242
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002243 if (!Val->getType()->isAggregateType())
2244 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002245 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2246 Indices.end()))
2247 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002248 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002249 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002250 ID.Kind = ValID::t_Constant;
2251 return false;
2252 }
2253 case lltok::kw_insertvalue: {
2254 Lex.Lex();
2255 Constant *Val0, *Val1;
2256 SmallVector<unsigned, 4> Indices;
2257 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2258 ParseGlobalTypeAndValue(Val0) ||
2259 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2260 ParseGlobalTypeAndValue(Val1) ||
2261 ParseIndexList(Indices) ||
2262 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2263 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002264 if (!Val0->getType()->isAggregateType())
2265 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002266 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2267 Indices.end()))
2268 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002269 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002270 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002271 ID.Kind = ValID::t_Constant;
2272 return false;
2273 }
2274 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002275 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002276 unsigned PredVal, Opc = Lex.getUIntVal();
2277 Constant *Val0, *Val1;
2278 Lex.Lex();
2279 if (ParseCmpPredicate(PredVal, Opc) ||
2280 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2281 ParseGlobalTypeAndValue(Val0) ||
2282 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2283 ParseGlobalTypeAndValue(Val1) ||
2284 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2285 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002286
Chris Lattnerdf986172009-01-02 07:01:27 +00002287 if (Val0->getType() != Val1->getType())
2288 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002289
Chris Lattnerdf986172009-01-02 07:01:27 +00002290 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002291
Chris Lattnerdf986172009-01-02 07:01:27 +00002292 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002293 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002294 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002295 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002296 } else {
2297 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002298 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002299 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002300 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002301 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002302 }
2303 ID.Kind = ValID::t_Constant;
2304 return false;
2305 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002306
Chris Lattnerdf986172009-01-02 07:01:27 +00002307 // Binary Operators.
2308 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002309 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002310 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002311 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002312 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002313 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002314 case lltok::kw_udiv:
2315 case lltok::kw_sdiv:
2316 case lltok::kw_fdiv:
2317 case lltok::kw_urem:
2318 case lltok::kw_srem:
2319 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002320 bool NUW = false;
2321 bool NSW = false;
2322 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002323 unsigned Opc = Lex.getUIntVal();
2324 Constant *Val0, *Val1;
2325 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002326 LocTy ModifierLoc = Lex.getLoc();
2327 if (Opc == Instruction::Add ||
2328 Opc == Instruction::Sub ||
2329 Opc == Instruction::Mul) {
2330 if (EatIfPresent(lltok::kw_nuw))
2331 NUW = true;
2332 if (EatIfPresent(lltok::kw_nsw)) {
2333 NSW = true;
2334 if (EatIfPresent(lltok::kw_nuw))
2335 NUW = true;
2336 }
2337 } else if (Opc == Instruction::SDiv) {
2338 if (EatIfPresent(lltok::kw_exact))
2339 Exact = true;
2340 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002341 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2342 ParseGlobalTypeAndValue(Val0) ||
2343 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2344 ParseGlobalTypeAndValue(Val1) ||
2345 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2346 return true;
2347 if (Val0->getType() != Val1->getType())
2348 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002349 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002350 if (NUW)
2351 return Error(ModifierLoc, "nuw only applies to integer operations");
2352 if (NSW)
2353 return Error(ModifierLoc, "nsw only applies to integer operations");
2354 }
2355 // API compatibility: Accept either integer or floating-point types with
2356 // add, sub, and mul.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002357 if (!Val0->getType()->isIntOrIntVectorTy() &&
2358 !Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002359 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002360 unsigned Flags = 0;
2361 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2362 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2363 if (Exact) Flags |= SDivOperator::IsExact;
2364 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002365 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002366 ID.Kind = ValID::t_Constant;
2367 return false;
2368 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002369
Chris Lattnerdf986172009-01-02 07:01:27 +00002370 // Logical Operations
2371 case lltok::kw_shl:
2372 case lltok::kw_lshr:
2373 case lltok::kw_ashr:
2374 case lltok::kw_and:
2375 case lltok::kw_or:
2376 case lltok::kw_xor: {
2377 unsigned Opc = Lex.getUIntVal();
2378 Constant *Val0, *Val1;
2379 Lex.Lex();
2380 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2381 ParseGlobalTypeAndValue(Val0) ||
2382 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2383 ParseGlobalTypeAndValue(Val1) ||
2384 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2385 return true;
2386 if (Val0->getType() != Val1->getType())
2387 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002388 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002389 return Error(ID.Loc,
2390 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002391 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002392 ID.Kind = ValID::t_Constant;
2393 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002394 }
2395
Chris Lattnerdf986172009-01-02 07:01:27 +00002396 case lltok::kw_getelementptr:
2397 case lltok::kw_shufflevector:
2398 case lltok::kw_insertelement:
2399 case lltok::kw_extractelement:
2400 case lltok::kw_select: {
2401 unsigned Opc = Lex.getUIntVal();
2402 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002403 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002404 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002405 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002406 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002407 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2408 ParseGlobalValueVector(Elts) ||
2409 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2410 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002411
Chris Lattnerdf986172009-01-02 07:01:27 +00002412 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002413 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002414 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002415
Chris Lattnerdf986172009-01-02 07:01:27 +00002416 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002417 (Value**)(Elts.data() + 1),
2418 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002419 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002420 ID.ConstantVal = InBounds ?
2421 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2422 Elts.data() + 1,
2423 Elts.size() - 1) :
2424 ConstantExpr::getGetElementPtr(Elts[0],
2425 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002426 } else if (Opc == Instruction::Select) {
2427 if (Elts.size() != 3)
2428 return Error(ID.Loc, "expected three operands to select");
2429 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2430 Elts[2]))
2431 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002432 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002433 } else if (Opc == Instruction::ShuffleVector) {
2434 if (Elts.size() != 3)
2435 return Error(ID.Loc, "expected three operands to shufflevector");
2436 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2437 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002438 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002439 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002440 } else if (Opc == Instruction::ExtractElement) {
2441 if (Elts.size() != 2)
2442 return Error(ID.Loc, "expected two operands to extractelement");
2443 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2444 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002445 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002446 } else {
2447 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2448 if (Elts.size() != 3)
2449 return Error(ID.Loc, "expected three operands to insertelement");
2450 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2451 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002452 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002453 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002454 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002455
Chris Lattnerdf986172009-01-02 07:01:27 +00002456 ID.Kind = ValID::t_Constant;
2457 return false;
2458 }
2459 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002460
Chris Lattnerdf986172009-01-02 07:01:27 +00002461 Lex.Lex();
2462 return false;
2463}
2464
2465/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002466bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2467 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002468 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002469 Value *V = NULL;
2470 bool Parsed = ParseValID(ID) ||
2471 ConvertValIDToValue(Ty, ID, V, NULL);
2472 if (V && !(C = dyn_cast<Constant>(V)))
2473 return Error(ID.Loc, "global values must be constants");
2474 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002475}
2476
Victor Hernandez92f238d2010-01-11 22:31:58 +00002477bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2478 PATypeHolder Type(Type::getVoidTy(Context));
2479 return ParseType(Type) ||
2480 ParseGlobalValue(Type, V);
2481}
2482
2483/// ParseGlobalValueVector
2484/// ::= /*empty*/
2485/// ::= TypeAndValue (',' TypeAndValue)*
2486bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2487 // Empty list.
2488 if (Lex.getKind() == lltok::rbrace ||
2489 Lex.getKind() == lltok::rsquare ||
2490 Lex.getKind() == lltok::greater ||
2491 Lex.getKind() == lltok::rparen)
2492 return false;
2493
2494 Constant *C;
2495 if (ParseGlobalTypeAndValue(C)) return true;
2496 Elts.push_back(C);
2497
2498 while (EatIfPresent(lltok::comma)) {
2499 if (ParseGlobalTypeAndValue(C)) return true;
2500 Elts.push_back(C);
2501 }
2502
2503 return false;
2504}
2505
2506
2507//===----------------------------------------------------------------------===//
2508// Function Parsing.
2509//===----------------------------------------------------------------------===//
2510
2511bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2512 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002513 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002514 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002515
Chris Lattnerdf986172009-01-02 07:01:27 +00002516 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002517 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002518 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002519 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2520 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2521 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002522 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002523 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2524 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2525 return (V == 0);
2526 case ValID::t_InlineAsm: {
2527 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2528 const FunctionType *FTy =
2529 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2530 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2531 return Error(ID.Loc, "invalid type for inline asm constraint string");
2532 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2533 return false;
2534 }
2535 case ValID::t_MDNode:
2536 if (!Ty->isMetadataTy())
2537 return Error(ID.Loc, "metadata value must have metadata type");
2538 V = ID.MDNodeVal;
2539 return false;
2540 case ValID::t_MDString:
2541 if (!Ty->isMetadataTy())
2542 return Error(ID.Loc, "metadata value must have metadata type");
2543 V = ID.MDStringVal;
2544 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002545 case ValID::t_GlobalName:
2546 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2547 return V == 0;
2548 case ValID::t_GlobalID:
2549 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2550 return V == 0;
2551 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002552 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002553 return Error(ID.Loc, "integer constant must have integer type");
2554 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002555 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002556 return false;
2557 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002558 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002559 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2560 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002561
Chris Lattnerdf986172009-01-02 07:01:27 +00002562 // The lexer has no type info, so builds all float and double FP constants
2563 // as double. Fix this here. Long double does not need this.
2564 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002565 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002566 bool Ignored;
2567 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2568 &Ignored);
2569 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002570 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002571
Chris Lattner959873d2009-01-05 18:24:23 +00002572 if (V->getType() != Ty)
2573 return Error(ID.Loc, "floating point constant does not have type '" +
2574 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002575
Chris Lattnerdf986172009-01-02 07:01:27 +00002576 return false;
2577 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002578 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002579 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002580 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002581 return false;
2582 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002583 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002584 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002585 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002586 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002587 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002588 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002589 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002590 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002591 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002592 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002593 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002594 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002595 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002596 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002597 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002598 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002599 return false;
2600 case ValID::t_Constant:
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002601 if (ID.ConstantVal->getType() != Ty) {
2602 // Allow a constant struct with a single member to be converted
2603 // to a union, if the union has a member which is the same type
2604 // as the struct member.
2605 if (const UnionType* utype = dyn_cast<UnionType>(Ty)) {
2606 return ParseUnionValue(utype, ID, V);
2607 }
2608
Chris Lattnerdf986172009-01-02 07:01:27 +00002609 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002610 }
2611
Chris Lattnerdf986172009-01-02 07:01:27 +00002612 V = ID.ConstantVal;
2613 return false;
2614 }
2615}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002616
Chris Lattnerdf986172009-01-02 07:01:27 +00002617bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2618 V = 0;
2619 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002620 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002621 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002622}
2623
2624bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002625 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002626 return ParseType(T) ||
2627 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002628}
2629
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002630bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2631 PerFunctionState &PFS) {
2632 Value *V;
2633 Loc = Lex.getLoc();
2634 if (ParseTypeAndValue(V, PFS)) return true;
2635 if (!isa<BasicBlock>(V))
2636 return Error(Loc, "expected a basic block");
2637 BB = cast<BasicBlock>(V);
2638 return false;
2639}
2640
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002641bool LLParser::ParseUnionValue(const UnionType* utype, ValID &ID, Value *&V) {
2642 if (const StructType* stype = dyn_cast<StructType>(ID.ConstantVal->getType())) {
2643 if (stype->getNumContainedTypes() != 1)
2644 return Error(ID.Loc, "constant expression type mismatch");
2645 int index = utype->getElementTypeIndex(stype->getContainedType(0));
2646 if (index < 0)
2647 return Error(ID.Loc, "initializer type is not a member of the union");
2648
2649 V = ConstantUnion::get(
2650 utype, cast<Constant>(ID.ConstantVal->getOperand(0)));
2651 return false;
2652 }
2653
2654 return Error(ID.Loc, "constant expression type mismatch");
2655}
2656
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002657
Chris Lattnerdf986172009-01-02 07:01:27 +00002658/// FunctionHeader
2659/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2660/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2661/// OptionalAlign OptGC
2662bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2663 // Parse the linkage.
2664 LocTy LinkageLoc = Lex.getLoc();
2665 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002666
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002667 unsigned Visibility, RetAttrs;
2668 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002669 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002670 LocTy RetTypeLoc = Lex.getLoc();
2671 if (ParseOptionalLinkage(Linkage) ||
2672 ParseOptionalVisibility(Visibility) ||
2673 ParseOptionalCallingConv(CC) ||
2674 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002675 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002676 return true;
2677
2678 // Verify that the linkage is ok.
2679 switch ((GlobalValue::LinkageTypes)Linkage) {
2680 case GlobalValue::ExternalLinkage:
2681 break; // always ok.
2682 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002683 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002684 if (isDefine)
2685 return Error(LinkageLoc, "invalid linkage for function definition");
2686 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002687 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002688 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002689 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002690 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002691 case GlobalValue::LinkOnceAnyLinkage:
2692 case GlobalValue::LinkOnceODRLinkage:
2693 case GlobalValue::WeakAnyLinkage:
2694 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002695 case GlobalValue::DLLExportLinkage:
2696 if (!isDefine)
2697 return Error(LinkageLoc, "invalid linkage for function declaration");
2698 break;
2699 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002700 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002701 return Error(LinkageLoc, "invalid function linkage type");
2702 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002703
Chris Lattner99bb3152009-01-05 08:00:30 +00002704 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002705 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002706 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002707
Chris Lattnerdf986172009-01-02 07:01:27 +00002708 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002709
2710 std::string FunctionName;
2711 if (Lex.getKind() == lltok::GlobalVar) {
2712 FunctionName = Lex.getStrVal();
2713 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2714 unsigned NameID = Lex.getUIntVal();
2715
2716 if (NameID != NumberedVals.size())
2717 return TokError("function expected to be numbered '%" +
2718 utostr(NumberedVals.size()) + "'");
2719 } else {
2720 return TokError("expected function name");
2721 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002722
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002723 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002724
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002725 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002726 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002727
Chris Lattnerdf986172009-01-02 07:01:27 +00002728 std::vector<ArgInfo> ArgList;
2729 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002730 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002731 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002732 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002733 std::string GC;
2734
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002735 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002736 ParseOptionalAttrs(FuncAttrs, 2) ||
2737 (EatIfPresent(lltok::kw_section) &&
2738 ParseStringConstant(Section)) ||
2739 ParseOptionalAlignment(Alignment) ||
2740 (EatIfPresent(lltok::kw_gc) &&
2741 ParseStringConstant(GC)))
2742 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002743
2744 // If the alignment was parsed as an attribute, move to the alignment field.
2745 if (FuncAttrs & Attribute::Alignment) {
2746 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2747 FuncAttrs &= ~Attribute::Alignment;
2748 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002749
Chris Lattnerdf986172009-01-02 07:01:27 +00002750 // Okay, if we got here, the function is syntactically valid. Convert types
2751 // and do semantic checks.
2752 std::vector<const Type*> ParamTypeList;
2753 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002754 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002755 // attributes.
2756 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2757 if (FuncAttrs & ObsoleteFuncAttrs) {
2758 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2759 FuncAttrs &= ~ObsoleteFuncAttrs;
2760 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002761
Chris Lattnerdf986172009-01-02 07:01:27 +00002762 if (RetAttrs != Attribute::None)
2763 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002764
Chris Lattnerdf986172009-01-02 07:01:27 +00002765 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2766 ParamTypeList.push_back(ArgList[i].Type);
2767 if (ArgList[i].Attrs != Attribute::None)
2768 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2769 }
2770
2771 if (FuncAttrs != Attribute::None)
2772 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2773
2774 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002775
Benjamin Kramerf0127052010-01-05 13:12:22 +00002776 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002777 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2778
Owen Andersonfba933c2009-07-01 23:57:11 +00002779 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002780 FunctionType::get(RetType, ParamTypeList, isVarArg);
2781 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002782
2783 Fn = 0;
2784 if (!FunctionName.empty()) {
2785 // If this was a definition of a forward reference, remove the definition
2786 // from the forward reference table and fill in the forward ref.
2787 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2788 ForwardRefVals.find(FunctionName);
2789 if (FRVI != ForwardRefVals.end()) {
2790 Fn = M->getFunction(FunctionName);
2791 ForwardRefVals.erase(FRVI);
2792 } else if ((Fn = M->getFunction(FunctionName))) {
2793 // If this function already exists in the symbol table, then it is
2794 // multiply defined. We accept a few cases for old backwards compat.
2795 // FIXME: Remove this stuff for LLVM 3.0.
2796 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2797 (!Fn->isDeclaration() && isDefine)) {
2798 // If the redefinition has different type or different attributes,
2799 // reject it. If both have bodies, reject it.
2800 return Error(NameLoc, "invalid redefinition of function '" +
2801 FunctionName + "'");
2802 } else if (Fn->isDeclaration()) {
2803 // Make sure to strip off any argument names so we can't get conflicts.
2804 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2805 AI != AE; ++AI)
2806 AI->setName("");
2807 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002808 } else if (M->getNamedValue(FunctionName)) {
2809 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002810 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002811
Dan Gohman41905542009-08-29 23:37:49 +00002812 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002813 // If this is a definition of a forward referenced function, make sure the
2814 // types agree.
2815 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2816 = ForwardRefValIDs.find(NumberedVals.size());
2817 if (I != ForwardRefValIDs.end()) {
2818 Fn = cast<Function>(I->second.first);
2819 if (Fn->getType() != PFT)
2820 return Error(NameLoc, "type of definition and forward reference of '@" +
2821 utostr(NumberedVals.size()) +"' disagree");
2822 ForwardRefValIDs.erase(I);
2823 }
2824 }
2825
2826 if (Fn == 0)
2827 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2828 else // Move the forward-reference to the correct spot in the module.
2829 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2830
2831 if (FunctionName.empty())
2832 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002833
Chris Lattnerdf986172009-01-02 07:01:27 +00002834 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2835 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2836 Fn->setCallingConv(CC);
2837 Fn->setAttributes(PAL);
2838 Fn->setAlignment(Alignment);
2839 Fn->setSection(Section);
2840 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002841
Chris Lattnerdf986172009-01-02 07:01:27 +00002842 // Add all of the arguments we parsed to the function.
2843 Function::arg_iterator ArgIt = Fn->arg_begin();
2844 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002845 // If we run out of arguments in the Function prototype, exit early.
2846 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2847 if (ArgIt == Fn->arg_end()) break;
2848
Chris Lattnerdf986172009-01-02 07:01:27 +00002849 // If the argument has a name, insert it into the argument symbol table.
2850 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002851
Chris Lattnerdf986172009-01-02 07:01:27 +00002852 // Set the name, if it conflicted, it will be auto-renamed.
2853 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002854
Chris Lattnerdf986172009-01-02 07:01:27 +00002855 if (ArgIt->getNameStr() != ArgList[i].Name)
2856 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2857 ArgList[i].Name + "'");
2858 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002859
Chris Lattnerdf986172009-01-02 07:01:27 +00002860 return false;
2861}
2862
2863
2864/// ParseFunctionBody
2865/// ::= '{' BasicBlock+ '}'
2866/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2867///
2868bool LLParser::ParseFunctionBody(Function &Fn) {
2869 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2870 return TokError("expected '{' in function body");
2871 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002872
Chris Lattner09d9ef42009-10-28 03:39:23 +00002873 int FunctionNumber = -1;
2874 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2875
2876 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002877
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002878 // We need at least one basic block.
2879 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2880 return TokError("function body requires at least one basic block");
2881
Chris Lattnerdf986172009-01-02 07:01:27 +00002882 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2883 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002884
Chris Lattnerdf986172009-01-02 07:01:27 +00002885 // Eat the }.
2886 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002887
Chris Lattnerdf986172009-01-02 07:01:27 +00002888 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002889 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002890}
2891
2892/// ParseBasicBlock
2893/// ::= LabelStr? Instruction*
2894bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2895 // If this basic block starts out with a name, remember it.
2896 std::string Name;
2897 LocTy NameLoc = Lex.getLoc();
2898 if (Lex.getKind() == lltok::LabelStr) {
2899 Name = Lex.getStrVal();
2900 Lex.Lex();
2901 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002902
Chris Lattnerdf986172009-01-02 07:01:27 +00002903 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2904 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002905
Chris Lattnerdf986172009-01-02 07:01:27 +00002906 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002907
Chris Lattnerdf986172009-01-02 07:01:27 +00002908 // Parse the instructions in this block until we get a terminator.
2909 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002910 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002911 do {
2912 // This instruction may have three possibilities for a name: a) none
2913 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2914 LocTy NameLoc = Lex.getLoc();
2915 int NameID = -1;
2916 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002917
Chris Lattnerdf986172009-01-02 07:01:27 +00002918 if (Lex.getKind() == lltok::LocalVarID) {
2919 NameID = Lex.getUIntVal();
2920 Lex.Lex();
2921 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2922 return true;
2923 } else if (Lex.getKind() == lltok::LocalVar ||
2924 // FIXME: REMOVE IN LLVM 3.0
2925 Lex.getKind() == lltok::StringConstant) {
2926 NameStr = Lex.getStrVal();
2927 Lex.Lex();
2928 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2929 return true;
2930 }
Devang Patelf633a062009-09-17 23:04:48 +00002931
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002932 switch (ParseInstruction(Inst, BB, PFS)) {
2933 default: assert(0 && "Unknown ParseInstruction result!");
2934 case InstError: return true;
2935 case InstNormal:
2936 // With a normal result, we check to see if the instruction is followed by
2937 // a comma and metadata.
2938 if (EatIfPresent(lltok::comma))
Chris Lattnerfe805242010-04-01 04:51:13 +00002939 if (ParseInstructionMetadata(Inst))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002940 return true;
2941 break;
2942 case InstExtraComma:
2943 // If the instruction parser ate an extra comma at the end of it, it
2944 // *must* be followed by metadata.
Chris Lattnerfe805242010-04-01 04:51:13 +00002945 if (ParseInstructionMetadata(Inst))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002946 return true;
2947 break;
2948 }
Devang Patelf633a062009-09-17 23:04:48 +00002949
Chris Lattnerdf986172009-01-02 07:01:27 +00002950 BB->getInstList().push_back(Inst);
2951
2952 // Set the name on the instruction.
2953 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2954 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002955
Chris Lattnerdf986172009-01-02 07:01:27 +00002956 return false;
2957}
2958
2959//===----------------------------------------------------------------------===//
2960// Instruction Parsing.
2961//===----------------------------------------------------------------------===//
2962
2963/// ParseInstruction - Parse one of the many different instructions.
2964///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002965int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2966 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002967 lltok::Kind Token = Lex.getKind();
2968 if (Token == lltok::Eof)
2969 return TokError("found end of file when expecting more instructions");
2970 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002971 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002972 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002973
Chris Lattnerdf986172009-01-02 07:01:27 +00002974 switch (Token) {
2975 default: return Error(Loc, "expected instruction opcode");
2976 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002977 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2978 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002979 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2980 case lltok::kw_br: return ParseBr(Inst, PFS);
2981 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002982 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002983 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2984 // Binary Operators.
2985 case lltok::kw_add:
2986 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002987 case lltok::kw_mul: {
2988 bool NUW = false;
2989 bool NSW = false;
2990 LocTy ModifierLoc = Lex.getLoc();
2991 if (EatIfPresent(lltok::kw_nuw))
2992 NUW = true;
2993 if (EatIfPresent(lltok::kw_nsw)) {
2994 NSW = true;
2995 if (EatIfPresent(lltok::kw_nuw))
2996 NUW = true;
2997 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002998 // API compatibility: Accept either integer or floating-point types.
Dan Gohman59858cf2009-07-27 16:11:46 +00002999 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
3000 if (!Result) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003001 if (!Inst->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00003002 if (NUW)
3003 return Error(ModifierLoc, "nuw only applies to integer operations");
3004 if (NSW)
3005 return Error(ModifierLoc, "nsw only applies to integer operations");
3006 }
3007 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003008 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003009 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003010 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003011 }
3012 return Result;
3013 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003014 case lltok::kw_fadd:
3015 case lltok::kw_fsub:
3016 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3017
Dan Gohman59858cf2009-07-27 16:11:46 +00003018 case lltok::kw_sdiv: {
3019 bool Exact = false;
3020 if (EatIfPresent(lltok::kw_exact))
3021 Exact = true;
3022 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3023 if (!Result)
3024 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003025 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003026 return Result;
3027 }
3028
Chris Lattnerdf986172009-01-02 07:01:27 +00003029 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00003030 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003031 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00003032 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003033 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00003034 case lltok::kw_shl:
3035 case lltok::kw_lshr:
3036 case lltok::kw_ashr:
3037 case lltok::kw_and:
3038 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003039 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003040 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003041 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003042 // Casts.
3043 case lltok::kw_trunc:
3044 case lltok::kw_zext:
3045 case lltok::kw_sext:
3046 case lltok::kw_fptrunc:
3047 case lltok::kw_fpext:
3048 case lltok::kw_bitcast:
3049 case lltok::kw_uitofp:
3050 case lltok::kw_sitofp:
3051 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003052 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003053 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003054 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003055 // Other.
3056 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003057 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003058 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3059 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3060 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3061 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3062 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3063 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3064 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003065 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3066 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00003067 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003068 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3069 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3070 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003071 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00003072 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003073 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00003074 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003075 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003076 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003077 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3078 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3079 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3080 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3081 }
3082}
3083
3084/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3085bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003086 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003087 switch (Lex.getKind()) {
3088 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3089 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3090 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3091 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3092 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3093 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3094 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3095 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3096 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3097 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3098 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3099 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3100 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3101 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3102 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3103 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3104 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3105 }
3106 } else {
3107 switch (Lex.getKind()) {
3108 default: TokError("expected icmp predicate (e.g. 'eq')");
3109 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3110 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3111 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3112 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3113 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3114 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3115 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3116 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3117 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3118 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3119 }
3120 }
3121 Lex.Lex();
3122 return false;
3123}
3124
3125//===----------------------------------------------------------------------===//
3126// Terminator Instructions.
3127//===----------------------------------------------------------------------===//
3128
3129/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003130/// ::= 'ret' void (',' !dbg, !1)*
3131/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3132/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00003133/// [[obsolete: LLVM 3.0]]
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003134int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3135 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003136 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003137 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003138
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003139 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003140 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003141 return false;
3142 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003143
Chris Lattnerdf986172009-01-02 07:01:27 +00003144 Value *RV;
3145 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003146
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003147 bool ExtraComma = false;
Devang Patelf633a062009-09-17 23:04:48 +00003148 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003149 // Parse optional custom metadata, e.g. !dbg
Chris Lattner1d928312009-12-30 05:02:06 +00003150 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003151 ExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003152 } else {
3153 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003154 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3155 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003156 SmallVector<Value*, 8> RVs;
3157 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003158
Devang Patelf633a062009-09-17 23:04:48 +00003159 do {
Devang Patel0475c912009-09-29 00:01:14 +00003160 // If optional custom metadata, e.g. !dbg is seen then this is the
3161 // end of MRV.
Chris Lattner1d928312009-12-30 05:02:06 +00003162 if (Lex.getKind() == lltok::MetadataVar)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003163 break;
3164 if (ParseTypeAndValue(RV, PFS)) return true;
3165 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003166 } while (EatIfPresent(lltok::comma));
3167
3168 RV = UndefValue::get(PFS.getFunction().getReturnType());
3169 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003170 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3171 BB->getInstList().push_back(I);
3172 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003173 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003174 }
3175 }
Devang Patelf633a062009-09-17 23:04:48 +00003176
Owen Anderson1d0be152009-08-13 21:58:54 +00003177 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003178 return ExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003179}
3180
3181
3182/// ParseBr
3183/// ::= 'br' TypeAndValue
3184/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3185bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3186 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003187 Value *Op0;
3188 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003189 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003190
Chris Lattnerdf986172009-01-02 07:01:27 +00003191 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3192 Inst = BranchInst::Create(BB);
3193 return false;
3194 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003195
Owen Anderson1d0be152009-08-13 21:58:54 +00003196 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003197 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003198
Chris Lattnerdf986172009-01-02 07:01:27 +00003199 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003200 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003201 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003202 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003203 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003204
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003205 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003206 return false;
3207}
3208
3209/// ParseSwitch
3210/// Instruction
3211/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3212/// JumpTable
3213/// ::= (TypeAndValue ',' TypeAndValue)*
3214bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3215 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003216 Value *Cond;
3217 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003218 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3219 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003220 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003221 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3222 return true;
3223
Duncan Sands1df98592010-02-16 11:11:14 +00003224 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003225 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003226
Chris Lattnerdf986172009-01-02 07:01:27 +00003227 // Parse the jump table pairs.
3228 SmallPtrSet<Value*, 32> SeenCases;
3229 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3230 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003231 Value *Constant;
3232 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003233
Chris Lattnerdf986172009-01-02 07:01:27 +00003234 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3235 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003236 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003237 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003238
Chris Lattnerdf986172009-01-02 07:01:27 +00003239 if (!SeenCases.insert(Constant))
3240 return Error(CondLoc, "duplicate case value in switch");
3241 if (!isa<ConstantInt>(Constant))
3242 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003243
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003244 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003245 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003246
Chris Lattnerdf986172009-01-02 07:01:27 +00003247 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003248
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003249 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003250 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3251 SI->addCase(Table[i].first, Table[i].second);
3252 Inst = SI;
3253 return false;
3254}
3255
Chris Lattnerab21db72009-10-28 00:19:10 +00003256/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003257/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003258/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3259bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003260 LocTy AddrLoc;
3261 Value *Address;
3262 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003263 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3264 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003265 return true;
3266
Duncan Sands1df98592010-02-16 11:11:14 +00003267 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003268 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003269
3270 // Parse the destination list.
3271 SmallVector<BasicBlock*, 16> DestList;
3272
3273 if (Lex.getKind() != lltok::rsquare) {
3274 BasicBlock *DestBB;
3275 if (ParseTypeAndBasicBlock(DestBB, PFS))
3276 return true;
3277 DestList.push_back(DestBB);
3278
3279 while (EatIfPresent(lltok::comma)) {
3280 if (ParseTypeAndBasicBlock(DestBB, PFS))
3281 return true;
3282 DestList.push_back(DestBB);
3283 }
3284 }
3285
3286 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3287 return true;
3288
Chris Lattnerab21db72009-10-28 00:19:10 +00003289 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003290 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3291 IBI->addDestination(DestList[i]);
3292 Inst = IBI;
3293 return false;
3294}
3295
3296
Chris Lattnerdf986172009-01-02 07:01:27 +00003297/// ParseInvoke
3298/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3299/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3300bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3301 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003302 unsigned RetAttrs, FnAttrs;
3303 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003304 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003305 LocTy RetTypeLoc;
3306 ValID CalleeID;
3307 SmallVector<ParamInfo, 16> ArgList;
3308
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003309 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003310 if (ParseOptionalCallingConv(CC) ||
3311 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003312 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003313 ParseValID(CalleeID) ||
3314 ParseParameterList(ArgList, PFS) ||
3315 ParseOptionalAttrs(FnAttrs, 2) ||
3316 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003317 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003318 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003319 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003320 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003321
Chris Lattnerdf986172009-01-02 07:01:27 +00003322 // If RetType is a non-function pointer type, then this is the short syntax
3323 // for the call, which means that RetType is just the return type. Infer the
3324 // rest of the function argument types from the arguments that are present.
3325 const PointerType *PFTy = 0;
3326 const FunctionType *Ty = 0;
3327 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3328 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3329 // Pull out the types of all of the arguments...
3330 std::vector<const Type*> ParamTypes;
3331 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3332 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003333
Chris Lattnerdf986172009-01-02 07:01:27 +00003334 if (!FunctionType::isValidReturnType(RetType))
3335 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003336
Owen Andersondebcb012009-07-29 22:17:13 +00003337 Ty = FunctionType::get(RetType, ParamTypes, false);
3338 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003339 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003340
Chris Lattnerdf986172009-01-02 07:01:27 +00003341 // Look up the callee.
3342 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003343 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003344
Chris Lattnerdf986172009-01-02 07:01:27 +00003345 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3346 // function attributes.
3347 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3348 if (FnAttrs & ObsoleteFuncAttrs) {
3349 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3350 FnAttrs &= ~ObsoleteFuncAttrs;
3351 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003352
Chris Lattnerdf986172009-01-02 07:01:27 +00003353 // Set up the Attributes for the function.
3354 SmallVector<AttributeWithIndex, 8> Attrs;
3355 if (RetAttrs != Attribute::None)
3356 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003357
Chris Lattnerdf986172009-01-02 07:01:27 +00003358 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003359
Chris Lattnerdf986172009-01-02 07:01:27 +00003360 // Loop through FunctionType's arguments and ensure they are specified
3361 // correctly. Also, gather any parameter attributes.
3362 FunctionType::param_iterator I = Ty->param_begin();
3363 FunctionType::param_iterator E = Ty->param_end();
3364 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3365 const Type *ExpectedTy = 0;
3366 if (I != E) {
3367 ExpectedTy = *I++;
3368 } else if (!Ty->isVarArg()) {
3369 return Error(ArgList[i].Loc, "too many arguments specified");
3370 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003371
Chris Lattnerdf986172009-01-02 07:01:27 +00003372 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3373 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3374 ExpectedTy->getDescription() + "'");
3375 Args.push_back(ArgList[i].V);
3376 if (ArgList[i].Attrs != Attribute::None)
3377 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3378 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003379
Chris Lattnerdf986172009-01-02 07:01:27 +00003380 if (I != E)
3381 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003382
Chris Lattnerdf986172009-01-02 07:01:27 +00003383 if (FnAttrs != Attribute::None)
3384 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003385
Chris Lattnerdf986172009-01-02 07:01:27 +00003386 // Finish off the Attributes and check them
3387 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003388
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003389 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003390 Args.begin(), Args.end());
3391 II->setCallingConv(CC);
3392 II->setAttributes(PAL);
3393 Inst = II;
3394 return false;
3395}
3396
3397
3398
3399//===----------------------------------------------------------------------===//
3400// Binary Operators.
3401//===----------------------------------------------------------------------===//
3402
3403/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003404/// ::= ArithmeticOps TypeAndValue ',' Value
3405///
3406/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3407/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003408bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003409 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003410 LocTy Loc; Value *LHS, *RHS;
3411 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3412 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3413 ParseValue(LHS->getType(), RHS, PFS))
3414 return true;
3415
Chris Lattnere914b592009-01-05 08:24:46 +00003416 bool Valid;
3417 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003418 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003419 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003420 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3421 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003422 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003423 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3424 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003425 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003426
Chris Lattnere914b592009-01-05 08:24:46 +00003427 if (!Valid)
3428 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003429
Chris Lattnerdf986172009-01-02 07:01:27 +00003430 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3431 return false;
3432}
3433
3434/// ParseLogical
3435/// ::= ArithmeticOps TypeAndValue ',' Value {
3436bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3437 unsigned Opc) {
3438 LocTy Loc; Value *LHS, *RHS;
3439 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3440 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3441 ParseValue(LHS->getType(), RHS, PFS))
3442 return true;
3443
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003444 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003445 return Error(Loc,"instruction requires integer or integer vector operands");
3446
3447 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3448 return false;
3449}
3450
3451
3452/// ParseCompare
3453/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3454/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003455bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3456 unsigned Opc) {
3457 // Parse the integer/fp comparison predicate.
3458 LocTy Loc;
3459 unsigned Pred;
3460 Value *LHS, *RHS;
3461 if (ParseCmpPredicate(Pred, Opc) ||
3462 ParseTypeAndValue(LHS, Loc, PFS) ||
3463 ParseToken(lltok::comma, "expected ',' after compare value") ||
3464 ParseValue(LHS->getType(), RHS, PFS))
3465 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003466
Chris Lattnerdf986172009-01-02 07:01:27 +00003467 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003468 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003469 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003470 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003471 } else {
3472 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003473 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003474 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003475 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003476 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003477 }
3478 return false;
3479}
3480
3481//===----------------------------------------------------------------------===//
3482// Other Instructions.
3483//===----------------------------------------------------------------------===//
3484
3485
3486/// ParseCast
3487/// ::= CastOpc TypeAndValue 'to' Type
3488bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3489 unsigned Opc) {
3490 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003491 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003492 if (ParseTypeAndValue(Op, Loc, PFS) ||
3493 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3494 ParseType(DestTy))
3495 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003496
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003497 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3498 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003499 return Error(Loc, "invalid cast opcode for cast from '" +
3500 Op->getType()->getDescription() + "' to '" +
3501 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003502 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003503 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3504 return false;
3505}
3506
3507/// ParseSelect
3508/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3509bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3510 LocTy Loc;
3511 Value *Op0, *Op1, *Op2;
3512 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3513 ParseToken(lltok::comma, "expected ',' after select condition") ||
3514 ParseTypeAndValue(Op1, PFS) ||
3515 ParseToken(lltok::comma, "expected ',' after select value") ||
3516 ParseTypeAndValue(Op2, PFS))
3517 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003518
Chris Lattnerdf986172009-01-02 07:01:27 +00003519 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3520 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003521
Chris Lattnerdf986172009-01-02 07:01:27 +00003522 Inst = SelectInst::Create(Op0, Op1, Op2);
3523 return false;
3524}
3525
Chris Lattner0088a5c2009-01-05 08:18:44 +00003526/// ParseVA_Arg
3527/// ::= 'va_arg' TypeAndValue ',' Type
3528bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003529 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003530 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003531 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003532 if (ParseTypeAndValue(Op, PFS) ||
3533 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003534 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003535 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003536
Chris Lattner0088a5c2009-01-05 08:18:44 +00003537 if (!EltTy->isFirstClassType())
3538 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003539
3540 Inst = new VAArgInst(Op, EltTy);
3541 return false;
3542}
3543
3544/// ParseExtractElement
3545/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3546bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3547 LocTy Loc;
3548 Value *Op0, *Op1;
3549 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3550 ParseToken(lltok::comma, "expected ',' after extract value") ||
3551 ParseTypeAndValue(Op1, PFS))
3552 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003553
Chris Lattnerdf986172009-01-02 07:01:27 +00003554 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3555 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003556
Eric Christophera3500da2009-07-25 02:28:41 +00003557 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003558 return false;
3559}
3560
3561/// ParseInsertElement
3562/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3563bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3564 LocTy Loc;
3565 Value *Op0, *Op1, *Op2;
3566 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3567 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3568 ParseTypeAndValue(Op1, PFS) ||
3569 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3570 ParseTypeAndValue(Op2, PFS))
3571 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003572
Chris Lattnerdf986172009-01-02 07:01:27 +00003573 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003574 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003575
Chris Lattnerdf986172009-01-02 07:01:27 +00003576 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3577 return false;
3578}
3579
3580/// ParseShuffleVector
3581/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3582bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3583 LocTy Loc;
3584 Value *Op0, *Op1, *Op2;
3585 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3586 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3587 ParseTypeAndValue(Op1, PFS) ||
3588 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3589 ParseTypeAndValue(Op2, PFS))
3590 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003591
Chris Lattnerdf986172009-01-02 07:01:27 +00003592 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3593 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003594
Chris Lattnerdf986172009-01-02 07:01:27 +00003595 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3596 return false;
3597}
3598
3599/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003600/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003601int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003602 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003603 Value *Op0, *Op1;
3604 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003605
Chris Lattnerdf986172009-01-02 07:01:27 +00003606 if (ParseType(Ty) ||
3607 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3608 ParseValue(Ty, Op0, PFS) ||
3609 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003610 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003611 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3612 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003613
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003614 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003615 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3616 while (1) {
3617 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003618
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003619 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003620 break;
3621
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003622 if (Lex.getKind() == lltok::MetadataVar) {
3623 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003624 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003625 }
Devang Patela43d46f2009-10-16 18:45:49 +00003626
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003627 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003628 ParseValue(Ty, Op0, PFS) ||
3629 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003630 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003631 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3632 return true;
3633 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003634
Chris Lattnerdf986172009-01-02 07:01:27 +00003635 if (!Ty->isFirstClassType())
3636 return Error(TypeLoc, "phi node must have first class type");
3637
3638 PHINode *PN = PHINode::Create(Ty);
3639 PN->reserveOperandSpace(PHIVals.size());
3640 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3641 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3642 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003643 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003644}
3645
3646/// ParseCall
3647/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3648/// ParameterList OptionalAttrs
3649bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3650 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003651 unsigned RetAttrs, FnAttrs;
3652 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003653 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003654 LocTy RetTypeLoc;
3655 ValID CalleeID;
3656 SmallVector<ParamInfo, 16> ArgList;
3657 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003658
Chris Lattnerdf986172009-01-02 07:01:27 +00003659 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3660 ParseOptionalCallingConv(CC) ||
3661 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003662 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003663 ParseValID(CalleeID) ||
3664 ParseParameterList(ArgList, PFS) ||
3665 ParseOptionalAttrs(FnAttrs, 2))
3666 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003667
Chris Lattnerdf986172009-01-02 07:01:27 +00003668 // If RetType is a non-function pointer type, then this is the short syntax
3669 // for the call, which means that RetType is just the return type. Infer the
3670 // rest of the function argument types from the arguments that are present.
3671 const PointerType *PFTy = 0;
3672 const FunctionType *Ty = 0;
3673 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3674 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3675 // Pull out the types of all of the arguments...
3676 std::vector<const Type*> ParamTypes;
3677 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3678 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003679
Chris Lattnerdf986172009-01-02 07:01:27 +00003680 if (!FunctionType::isValidReturnType(RetType))
3681 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003682
Owen Andersondebcb012009-07-29 22:17:13 +00003683 Ty = FunctionType::get(RetType, ParamTypes, false);
3684 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003685 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003686
Chris Lattnerdf986172009-01-02 07:01:27 +00003687 // Look up the callee.
3688 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003689 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003690
Chris Lattnerdf986172009-01-02 07:01:27 +00003691 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3692 // function attributes.
3693 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3694 if (FnAttrs & ObsoleteFuncAttrs) {
3695 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3696 FnAttrs &= ~ObsoleteFuncAttrs;
3697 }
3698
3699 // Set up the Attributes for the function.
3700 SmallVector<AttributeWithIndex, 8> Attrs;
3701 if (RetAttrs != Attribute::None)
3702 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003703
Chris Lattnerdf986172009-01-02 07:01:27 +00003704 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003705
Chris Lattnerdf986172009-01-02 07:01:27 +00003706 // Loop through FunctionType's arguments and ensure they are specified
3707 // correctly. Also, gather any parameter attributes.
3708 FunctionType::param_iterator I = Ty->param_begin();
3709 FunctionType::param_iterator E = Ty->param_end();
3710 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3711 const Type *ExpectedTy = 0;
3712 if (I != E) {
3713 ExpectedTy = *I++;
3714 } else if (!Ty->isVarArg()) {
3715 return Error(ArgList[i].Loc, "too many arguments specified");
3716 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003717
Chris Lattnerdf986172009-01-02 07:01:27 +00003718 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3719 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3720 ExpectedTy->getDescription() + "'");
3721 Args.push_back(ArgList[i].V);
3722 if (ArgList[i].Attrs != Attribute::None)
3723 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3724 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003725
Chris Lattnerdf986172009-01-02 07:01:27 +00003726 if (I != E)
3727 return Error(CallLoc, "not enough parameters specified for call");
3728
3729 if (FnAttrs != Attribute::None)
3730 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3731
3732 // Finish off the Attributes and check them
3733 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003734
Chris Lattnerdf986172009-01-02 07:01:27 +00003735 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3736 CI->setTailCall(isTail);
3737 CI->setCallingConv(CC);
3738 CI->setAttributes(PAL);
3739 Inst = CI;
3740 return false;
3741}
3742
3743//===----------------------------------------------------------------------===//
3744// Memory Instructions.
3745//===----------------------------------------------------------------------===//
3746
3747/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003748/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3749/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003750int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3751 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003752 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003753 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003754 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003755 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003756 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003757
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003758 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003759 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003760 if (Lex.getKind() == lltok::kw_align) {
3761 if (ParseOptionalAlignment(Alignment)) return true;
3762 } else if (Lex.getKind() == lltok::MetadataVar) {
3763 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003764 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003765 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3766 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3767 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003768 }
3769 }
3770
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003771 if (Size && !Size->getType()->isIntegerTy(32))
Chris Lattnerdf986172009-01-02 07:01:27 +00003772 return Error(SizeLoc, "element count must be i32");
3773
Victor Hernandez68afa542009-10-21 19:11:40 +00003774 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003775 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003776 return AteExtraComma ? InstExtraComma : InstNormal;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003777 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003778
3779 // Autoupgrade old malloc instruction to malloc call.
3780 // FIXME: Remove in LLVM 3.0.
3781 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003782 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3783 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
Victor Hernandez68afa542009-10-21 19:11:40 +00003784 if (!MallocF)
3785 // Prototype malloc as "void *(int32)".
3786 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003787 MallocF = cast<Function>(
3788 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003789 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003790return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003791}
3792
3793/// ParseFree
3794/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003795bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3796 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003797 Value *Val; LocTy Loc;
3798 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003799 if (!Val->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003800 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003801 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003802 return false;
3803}
3804
3805/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003806/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003807int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3808 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003809 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003810 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003811 bool AteExtraComma = false;
3812 if (ParseTypeAndValue(Val, Loc, PFS) ||
3813 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3814 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003815
Duncan Sands1df98592010-02-16 11:11:14 +00003816 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003817 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3818 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003819
Chris Lattnerdf986172009-01-02 07:01:27 +00003820 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003821 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003822}
3823
3824/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003825/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003826int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3827 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003828 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003829 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003830 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003831 if (ParseTypeAndValue(Val, Loc, PFS) ||
3832 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003833 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3834 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003835 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003836
Duncan Sands1df98592010-02-16 11:11:14 +00003837 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003838 return Error(PtrLoc, "store operand must be a pointer");
3839 if (!Val->getType()->isFirstClassType())
3840 return Error(Loc, "store operand must be a first class value");
3841 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3842 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003843
Chris Lattnerdf986172009-01-02 07:01:27 +00003844 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003845 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003846}
3847
3848/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003849/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003850/// FIXME: Remove support for getresult in LLVM 3.0
3851bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3852 Value *Val; LocTy ValLoc, EltLoc;
3853 unsigned Element;
3854 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3855 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003856 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003857 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003858
Duncan Sands1df98592010-02-16 11:11:14 +00003859 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003860 return Error(ValLoc, "getresult inst requires an aggregate operand");
3861 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3862 return Error(EltLoc, "invalid getresult index for value");
3863 Inst = ExtractValueInst::Create(Val, Element);
3864 return false;
3865}
3866
3867/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003868/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003869int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003870 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003871
Dan Gohmandcb40a32009-07-29 15:58:36 +00003872 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003873
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003874 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003875
Duncan Sands1df98592010-02-16 11:11:14 +00003876 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003877 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003878
Chris Lattnerdf986172009-01-02 07:01:27 +00003879 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003880 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003881 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003882 if (Lex.getKind() == lltok::MetadataVar) {
3883 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003884 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003885 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003886 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003887 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003888 return Error(EltLoc, "getelementptr index must be an integer");
3889 Indices.push_back(Val);
3890 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003891
Chris Lattnerdf986172009-01-02 07:01:27 +00003892 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3893 Indices.begin(), Indices.end()))
3894 return Error(Loc, "invalid getelementptr indices");
3895 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003896 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003897 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003898 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003899}
3900
3901/// ParseExtractValue
3902/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003903int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003904 Value *Val; LocTy Loc;
3905 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003906 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003907 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003908 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003909 return true;
3910
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003911 if (!Val->getType()->isAggregateType())
3912 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003913
3914 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3915 Indices.end()))
3916 return Error(Loc, "invalid indices for extractvalue");
3917 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003918 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003919}
3920
3921/// ParseInsertValue
3922/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003923int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003924 Value *Val0, *Val1; LocTy Loc0, Loc1;
3925 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003926 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003927 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3928 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3929 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003930 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003931 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003932
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003933 if (!Val0->getType()->isAggregateType())
3934 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003935
Chris Lattnerdf986172009-01-02 07:01:27 +00003936 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3937 Indices.end()))
3938 return Error(Loc0, "invalid indices for insertvalue");
3939 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003940 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003941}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003942
3943//===----------------------------------------------------------------------===//
3944// Embedded metadata.
3945//===----------------------------------------------------------------------===//
3946
3947/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003948/// ::= Element (',' Element)*
3949/// Element
3950/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003951bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003952 PerFunctionState *PFS) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003953 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003954 // Null is a special case since it is typeless.
3955 if (EatIfPresent(lltok::kw_null)) {
3956 Elts.push_back(0);
3957 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003958 }
Chris Lattnera7352392009-12-30 04:42:57 +00003959
3960 Value *V = 0;
3961 PATypeHolder Ty(Type::getVoidTy(Context));
3962 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00003963 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00003964 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00003965 return true;
3966
Nick Lewyckycb337992009-05-10 20:57:05 +00003967 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003968 } while (EatIfPresent(lltok::comma));
3969
3970 return false;
3971}