blob: 0eb1b70c3f20e5d505153b2d13ed9f12daf91105 [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 Wendling5e721d72010-07-01 21:55:59 +0000199 case lltok::kw_private: // OptionalLinkage
200 case lltok::kw_linker_private: // OptionalLinkage
201 case lltok::kw_linker_private_weak: // OptionalLinkage
Bill Wendling55ae5152010-08-20 22:05:50 +0000202 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
Bill Wendling5e721d72010-07-01 21:55:59 +0000203 case lltok::kw_internal: // OptionalLinkage
204 case lltok::kw_weak: // OptionalLinkage
205 case lltok::kw_weak_odr: // OptionalLinkage
206 case lltok::kw_linkonce: // OptionalLinkage
207 case lltok::kw_linkonce_odr: // OptionalLinkage
208 case lltok::kw_appending: // OptionalLinkage
209 case lltok::kw_dllexport: // OptionalLinkage
210 case lltok::kw_common: // OptionalLinkage
211 case lltok::kw_dllimport: // OptionalLinkage
212 case lltok::kw_extern_weak: // OptionalLinkage
213 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000214 unsigned Linkage, Visibility;
215 if (ParseOptionalLinkage(Linkage) ||
216 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000217 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000218 return true;
219 break;
220 }
221 case lltok::kw_default: // OptionalVisibility
222 case lltok::kw_hidden: // OptionalVisibility
223 case lltok::kw_protected: { // OptionalVisibility
224 unsigned Visibility;
225 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000226 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000227 return true;
228 break;
229 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000230
Chris Lattnerdf986172009-01-02 07:01:27 +0000231 case lltok::kw_thread_local: // OptionalThreadLocal
232 case lltok::kw_addrspace: // OptionalAddrSpace
233 case lltok::kw_constant: // GlobalType
234 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000235 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000236 break;
237 }
238 }
239}
240
241
242/// toplevelentity
243/// ::= 'module' 'asm' STRINGCONSTANT
244bool LLParser::ParseModuleAsm() {
245 assert(Lex.getKind() == lltok::kw_module);
246 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000247
248 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000249 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
250 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000251
Chris Lattnerdf986172009-01-02 07:01:27 +0000252 const std::string &AsmSoFar = M->getModuleInlineAsm();
253 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000254 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000255 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000256 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000257 return false;
258}
259
260/// toplevelentity
261/// ::= 'target' 'triple' '=' STRINGCONSTANT
262/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
263bool LLParser::ParseTargetDefinition() {
264 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000265 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000266 switch (Lex.Lex()) {
267 default: return TokError("unknown target property");
268 case lltok::kw_triple:
269 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000270 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
271 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000272 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000273 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000274 return false;
275 case lltok::kw_datalayout:
276 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000277 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
278 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000279 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000280 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000281 return false;
282 }
283}
284
285/// toplevelentity
286/// ::= 'deplibs' '=' '[' ']'
287/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
288bool LLParser::ParseDepLibs() {
289 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000290 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000291 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
292 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
293 return true;
294
295 if (EatIfPresent(lltok::rsquare))
296 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000297
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000298 std::string Str;
299 if (ParseStringConstant(Str)) return true;
300 M->addLibrary(Str);
301
302 while (EatIfPresent(lltok::comma)) {
303 if (ParseStringConstant(Str)) return true;
304 M->addLibrary(Str);
305 }
306
307 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000308}
309
Dan Gohman3845e502009-08-12 23:32:33 +0000310/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000311/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000312/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000313bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000314 unsigned TypeID = NumberedTypes.size();
315
316 // Handle the LocalVarID form.
317 if (Lex.getKind() == lltok::LocalVarID) {
318 if (Lex.getUIntVal() != TypeID)
319 return Error(Lex.getLoc(), "type expected to be numbered '%" +
320 utostr(TypeID) + "'");
321 Lex.Lex(); // eat LocalVarID;
322
323 if (ParseToken(lltok::equal, "expected '=' after name"))
324 return true;
325 }
326
Chris Lattnerdf986172009-01-02 07:01:27 +0000327 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerf7240de2010-04-10 18:01:25 +0000328 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000329
Owen Anderson1d0be152009-08-13 21:58:54 +0000330 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000331 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000332
Chris Lattnerdf986172009-01-02 07:01:27 +0000333 // See if this type was previously referenced.
334 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
335 FI = ForwardRefTypeIDs.find(TypeID);
336 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000337 if (FI->second.first.get() == Ty)
338 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000339
Chris Lattnerdf986172009-01-02 07:01:27 +0000340 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
341 Ty = FI->second.first.get();
342 ForwardRefTypeIDs.erase(FI);
343 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000344
Chris Lattnerdf986172009-01-02 07:01:27 +0000345 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000346
Chris Lattnerdf986172009-01-02 07:01:27 +0000347 return false;
348}
349
350/// toplevelentity
351/// ::= LocalVar '=' 'type' type
352bool LLParser::ParseNamedType() {
353 std::string Name = Lex.getStrVal();
354 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000355 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000356
Owen Anderson1d0be152009-08-13 21:58:54 +0000357 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000358
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000359 if (ParseToken(lltok::equal, "expected '=' after name") ||
360 ParseToken(lltok::kw_type, "expected 'type' after name") ||
361 ParseType(Ty))
362 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000363
Chris Lattnerdf986172009-01-02 07:01:27 +0000364 // Set the type name, checking for conflicts as we do so.
365 bool AlreadyExists = M->addTypeName(Name, Ty);
366 if (!AlreadyExists) return false;
367
368 // See if this type is a forward reference. We need to eagerly resolve
369 // types to allow recursive type redefinitions below.
370 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
371 FI = ForwardRefTypes.find(Name);
372 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000373 if (FI->second.first.get() == Ty)
374 return Error(NameLoc, "self referential type is invalid");
375
Chris Lattnerdf986172009-01-02 07:01:27 +0000376 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
377 Ty = FI->second.first.get();
378 ForwardRefTypes.erase(FI);
379 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000380
Chris Lattnerdf986172009-01-02 07:01:27 +0000381 // Inserting a name that is already defined, get the existing name.
382 const Type *Existing = M->getTypeByName(Name);
383 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000384
Chris Lattnerdf986172009-01-02 07:01:27 +0000385 // Otherwise, this is an attempt to redefine a type. That's okay if
386 // the redefinition is identical to the original.
387 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
388 if (Existing == Ty) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000389
Chris Lattnerdf986172009-01-02 07:01:27 +0000390 // Any other kind of (non-equivalent) redefinition is an error.
391 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
392 Ty->getDescription() + "'");
393}
394
395
396/// toplevelentity
397/// ::= 'declare' FunctionHeader
398bool LLParser::ParseDeclare() {
399 assert(Lex.getKind() == lltok::kw_declare);
400 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000401
Chris Lattnerdf986172009-01-02 07:01:27 +0000402 Function *F;
403 return ParseFunctionHeader(F, false);
404}
405
406/// toplevelentity
407/// ::= 'define' FunctionHeader '{' ...
408bool LLParser::ParseDefine() {
409 assert(Lex.getKind() == lltok::kw_define);
410 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000411
Chris Lattnerdf986172009-01-02 07:01:27 +0000412 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000413 return ParseFunctionHeader(F, true) ||
414 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000415}
416
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000417/// ParseGlobalType
418/// ::= 'constant'
419/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000420bool LLParser::ParseGlobalType(bool &IsConstant) {
421 if (Lex.getKind() == lltok::kw_constant)
422 IsConstant = true;
423 else if (Lex.getKind() == lltok::kw_global)
424 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000425 else {
426 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000427 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000428 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000429 Lex.Lex();
430 return false;
431}
432
Dan Gohman3845e502009-08-12 23:32:33 +0000433/// ParseUnnamedGlobal:
434/// OptionalVisibility ALIAS ...
435/// OptionalLinkage OptionalVisibility ... -> global variable
436/// GlobalID '=' OptionalVisibility ALIAS ...
437/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
438bool LLParser::ParseUnnamedGlobal() {
439 unsigned VarID = NumberedVals.size();
440 std::string Name;
441 LocTy NameLoc = Lex.getLoc();
442
443 // Handle the GlobalID form.
444 if (Lex.getKind() == lltok::GlobalID) {
445 if (Lex.getUIntVal() != VarID)
446 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
447 utostr(VarID) + "'");
448 Lex.Lex(); // eat GlobalID;
449
450 if (ParseToken(lltok::equal, "expected '=' after name"))
451 return true;
452 }
453
454 bool HasLinkage;
455 unsigned Linkage, Visibility;
456 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
457 ParseOptionalVisibility(Visibility))
458 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000459
Dan Gohman3845e502009-08-12 23:32:33 +0000460 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
461 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
462 return ParseAlias(Name, NameLoc, Visibility);
463}
464
Chris Lattnerdf986172009-01-02 07:01:27 +0000465/// ParseNamedGlobal:
466/// GlobalVar '=' OptionalVisibility ALIAS ...
467/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
468bool LLParser::ParseNamedGlobal() {
469 assert(Lex.getKind() == lltok::GlobalVar);
470 LocTy NameLoc = Lex.getLoc();
471 std::string Name = Lex.getStrVal();
472 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000473
Chris Lattnerdf986172009-01-02 07:01:27 +0000474 bool HasLinkage;
475 unsigned Linkage, Visibility;
476 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
477 ParseOptionalLinkage(Linkage, HasLinkage) ||
478 ParseOptionalVisibility(Visibility))
479 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000480
Chris Lattnerdf986172009-01-02 07:01:27 +0000481 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
482 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
483 return ParseAlias(Name, NameLoc, Visibility);
484}
485
Devang Patel256be962009-07-20 19:00:08 +0000486// MDString:
487// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000488bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000489 std::string Str;
490 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000491 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000492 return false;
493}
494
495// MDNode:
496// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000497//
498/// This version of ParseMDNodeID returns the slot number and null in the case
499/// of a forward reference.
500bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
501 // !{ ..., !42, ... }
502 if (ParseUInt32(SlotNo)) return true;
503
504 // Check existing MDNode.
505 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
506 Result = NumberedMetadata[SlotNo];
507 else
508 Result = 0;
509 return false;
510}
511
Chris Lattner4a72efc2009-12-30 04:15:23 +0000512bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000513 // !{ ..., !42, ... }
514 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000515 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000516
Chris Lattner449c3102010-04-01 05:14:45 +0000517 // If not a forward reference, just return it now.
518 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000519
Chris Lattner449c3102010-04-01 05:14:45 +0000520 // Otherwise, create MDNode forward reference.
Dan Gohman489b29b2010-08-20 22:02:26 +0000521 MDNode *FwdNode = MDNode::getTemporary(Context, 0, 0);
Devang Patel256be962009-07-20 19:00:08 +0000522 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000523
524 if (NumberedMetadata.size() <= MID)
525 NumberedMetadata.resize(MID+1);
526 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000527 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000528 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000529}
Devang Patel256be962009-07-20 19:00:08 +0000530
Chris Lattner84d03b12009-12-29 22:35:39 +0000531/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000532/// !foo = !{ !1, !2 }
533bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000534 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000535 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000536 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000537
Chris Lattner84d03b12009-12-29 22:35:39 +0000538 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000539 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000540 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000541 return true;
542
Dan Gohman17aa92c2010-07-21 23:38:33 +0000543 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000544 if (Lex.getKind() != lltok::rbrace)
545 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000546 if (ParseToken(lltok::exclaim, "Expected '!' here"))
547 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000548
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000549 MDNode *N = 0;
550 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000551 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000552 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000553
554 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
555 return true;
556
Devang Pateleff2ab62009-07-29 00:34:02 +0000557 return false;
558}
559
Devang Patel923078c2009-07-01 19:21:12 +0000560/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000561/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000562bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000563 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000564 Lex.Lex();
565 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000566
567 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000568 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000569 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000570 if (ParseUInt32(MetadataID) ||
571 ParseToken(lltok::equal, "expected '=' here") ||
572 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000573 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000574 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000575 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000576 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000577 return true;
578
Owen Anderson647e3012009-07-31 21:35:40 +0000579 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000580
581 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000582 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000583 FI = ForwardRefMDNodes.find(MetadataID);
584 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000585 MDNode *Temp = FI->second.first;
586 Temp->replaceAllUsesWith(Init);
587 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000588 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000589
590 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
591 } else {
592 if (MetadataID >= NumberedMetadata.size())
593 NumberedMetadata.resize(MetadataID+1);
594
595 if (NumberedMetadata[MetadataID] != 0)
596 return TokError("Metadata id is already used");
597 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000598 }
599
Devang Patel923078c2009-07-01 19:21:12 +0000600 return false;
601}
602
Chris Lattnerdf986172009-01-02 07:01:27 +0000603/// ParseAlias:
604/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
605/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000606/// ::= TypeAndValue
607/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000608/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000609///
610/// Everything through visibility has already been parsed.
611///
612bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
613 unsigned Visibility) {
614 assert(Lex.getKind() == lltok::kw_alias);
615 Lex.Lex();
616 unsigned Linkage;
617 LocTy LinkageLoc = Lex.getLoc();
618 if (ParseOptionalLinkage(Linkage))
619 return true;
620
621 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000622 Linkage != GlobalValue::WeakAnyLinkage &&
623 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000624 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000625 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000626 Linkage != GlobalValue::LinkerPrivateLinkage &&
Bill Wendling55ae5152010-08-20 22:05:50 +0000627 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
628 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000629 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000630
Chris Lattnerdf986172009-01-02 07:01:27 +0000631 Constant *Aliasee;
632 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000633 if (Lex.getKind() != lltok::kw_bitcast &&
634 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000635 if (ParseGlobalTypeAndValue(Aliasee)) return true;
636 } else {
637 // The bitcast dest type is not present, it is implied by the dest type.
638 ValID ID;
639 if (ParseValID(ID)) return true;
640 if (ID.Kind != ValID::t_Constant)
641 return Error(AliaseeLoc, "invalid aliasee");
642 Aliasee = ID.ConstantVal;
643 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000644
Duncan Sands1df98592010-02-16 11:11:14 +0000645 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000646 return Error(AliaseeLoc, "alias must have pointer type");
647
648 // Okay, create the alias but do not insert it into the module yet.
649 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
650 (GlobalValue::LinkageTypes)Linkage, Name,
651 Aliasee);
652 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000653
Chris Lattnerdf986172009-01-02 07:01:27 +0000654 // See if this value already exists in the symbol table. If so, it is either
655 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000656 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000657 // See if this was a redefinition. If so, there is no entry in
658 // ForwardRefVals.
659 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
660 I = ForwardRefVals.find(Name);
661 if (I == ForwardRefVals.end())
662 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
663
664 // Otherwise, this was a definition of forward ref. Verify that types
665 // agree.
666 if (Val->getType() != GA->getType())
667 return Error(NameLoc,
668 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000669
Chris Lattnerdf986172009-01-02 07:01:27 +0000670 // If they agree, just RAUW the old value with the alias and remove the
671 // forward ref info.
672 Val->replaceAllUsesWith(GA);
673 Val->eraseFromParent();
674 ForwardRefVals.erase(I);
675 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000676
Chris Lattnerdf986172009-01-02 07:01:27 +0000677 // Insert into the module, we know its name won't collide now.
678 M->getAliasList().push_back(GA);
679 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000680
Chris Lattnerdf986172009-01-02 07:01:27 +0000681 return false;
682}
683
684/// ParseGlobal
685/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
686/// OptionalAddrSpace GlobalType Type Const
687/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
688/// OptionalAddrSpace GlobalType Type Const
689///
690/// Everything through visibility has been parsed already.
691///
692bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
693 unsigned Linkage, bool HasLinkage,
694 unsigned Visibility) {
695 unsigned AddrSpace;
696 bool ThreadLocal, IsConstant;
697 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000698
Owen Anderson1d0be152009-08-13 21:58:54 +0000699 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000700 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
701 ParseOptionalAddrSpace(AddrSpace) ||
702 ParseGlobalType(IsConstant) ||
703 ParseType(Ty, TyLoc))
704 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000705
Chris Lattnerdf986172009-01-02 07:01:27 +0000706 // If the linkage is specified and is external, then no initializer is
707 // present.
708 Constant *Init = 0;
709 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000710 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000711 Linkage != GlobalValue::ExternalLinkage)) {
712 if (ParseGlobalValue(Ty, Init))
713 return true;
714 }
715
Duncan Sands1df98592010-02-16 11:11:14 +0000716 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000717 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000718
Chris Lattnerdf986172009-01-02 07:01:27 +0000719 GlobalVariable *GV = 0;
720
721 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000722 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000723 if (GlobalValue *GVal = M->getNamedValue(Name)) {
724 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
725 return Error(NameLoc, "redefinition of global '@" + Name + "'");
726 GV = cast<GlobalVariable>(GVal);
727 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000728 } else {
729 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
730 I = ForwardRefValIDs.find(NumberedVals.size());
731 if (I != ForwardRefValIDs.end()) {
732 GV = cast<GlobalVariable>(I->second.first);
733 ForwardRefValIDs.erase(I);
734 }
735 }
736
737 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000738 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000739 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000740 } else {
741 if (GV->getType()->getElementType() != Ty)
742 return Error(TyLoc,
743 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000744
Chris Lattnerdf986172009-01-02 07:01:27 +0000745 // Move the forward-reference to the correct spot in the module.
746 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
747 }
748
749 if (Name.empty())
750 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000751
Chris Lattnerdf986172009-01-02 07:01:27 +0000752 // Set the parsed properties on the global.
753 if (Init)
754 GV->setInitializer(Init);
755 GV->setConstant(IsConstant);
756 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
757 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
758 GV->setThreadLocal(ThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000759
Chris Lattnerdf986172009-01-02 07:01:27 +0000760 // Parse attributes on the global.
761 while (Lex.getKind() == lltok::comma) {
762 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000763
Chris Lattnerdf986172009-01-02 07:01:27 +0000764 if (Lex.getKind() == lltok::kw_section) {
765 Lex.Lex();
766 GV->setSection(Lex.getStrVal());
767 if (ParseToken(lltok::StringConstant, "expected global section string"))
768 return true;
769 } else if (Lex.getKind() == lltok::kw_align) {
770 unsigned Alignment;
771 if (ParseOptionalAlignment(Alignment)) return true;
772 GV->setAlignment(Alignment);
773 } else {
774 TokError("unknown global variable property!");
775 }
776 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000777
Chris Lattnerdf986172009-01-02 07:01:27 +0000778 return false;
779}
780
781
782//===----------------------------------------------------------------------===//
783// GlobalValue Reference/Resolution Routines.
784//===----------------------------------------------------------------------===//
785
786/// GetGlobalVal - Get a value with the specified name or ID, creating a
787/// forward reference record if needed. This can return null if the value
788/// exists but does not have the right type.
789GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
790 LocTy Loc) {
791 const PointerType *PTy = dyn_cast<PointerType>(Ty);
792 if (PTy == 0) {
793 Error(Loc, "global variable reference must have pointer type");
794 return 0;
795 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000796
Chris Lattnerdf986172009-01-02 07:01:27 +0000797 // Look this name up in the normal function symbol table.
798 GlobalValue *Val =
799 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000800
Chris Lattnerdf986172009-01-02 07:01:27 +0000801 // If this is a forward reference for the value, see if we already created a
802 // forward ref record.
803 if (Val == 0) {
804 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
805 I = ForwardRefVals.find(Name);
806 if (I != ForwardRefVals.end())
807 Val = I->second.first;
808 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000809
Chris Lattnerdf986172009-01-02 07:01:27 +0000810 // If we have the value in the symbol table or fwd-ref table, return it.
811 if (Val) {
812 if (Val->getType() == Ty) return Val;
813 Error(Loc, "'@" + Name + "' defined with type '" +
814 Val->getType()->getDescription() + "'");
815 return 0;
816 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000817
Chris Lattnerdf986172009-01-02 07:01:27 +0000818 // Otherwise, create a new forward reference for this value and remember it.
819 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000820 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
821 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000822 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner1e407c32009-01-08 19:05:36 +0000823 Error(Loc, "function may not return opaque type");
824 return 0;
825 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000826
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000827 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000828 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000829 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
830 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000831 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000832
Chris Lattnerdf986172009-01-02 07:01:27 +0000833 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
834 return FwdVal;
835}
836
837GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
838 const PointerType *PTy = dyn_cast<PointerType>(Ty);
839 if (PTy == 0) {
840 Error(Loc, "global variable reference must have pointer type");
841 return 0;
842 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000843
Chris Lattnerdf986172009-01-02 07:01:27 +0000844 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000845
Chris Lattnerdf986172009-01-02 07:01:27 +0000846 // If this is a forward reference for the value, see if we already created a
847 // forward ref record.
848 if (Val == 0) {
849 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
850 I = ForwardRefValIDs.find(ID);
851 if (I != ForwardRefValIDs.end())
852 Val = I->second.first;
853 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000854
Chris Lattnerdf986172009-01-02 07:01:27 +0000855 // If we have the value in the symbol table or fwd-ref table, return it.
856 if (Val) {
857 if (Val->getType() == Ty) return Val;
858 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
859 Val->getType()->getDescription() + "'");
860 return 0;
861 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000862
Chris Lattnerdf986172009-01-02 07:01:27 +0000863 // Otherwise, create a new forward reference for this value and remember it.
864 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000865 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
866 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000867 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000868 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000869 return 0;
870 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000871 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000872 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000873 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
874 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000875 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000876
Chris Lattnerdf986172009-01-02 07:01:27 +0000877 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
878 return FwdVal;
879}
880
881
882//===----------------------------------------------------------------------===//
883// Helper Routines.
884//===----------------------------------------------------------------------===//
885
886/// ParseToken - If the current token has the specified kind, eat it and return
887/// success. Otherwise, emit the specified error and return failure.
888bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
889 if (Lex.getKind() != T)
890 return TokError(ErrMsg);
891 Lex.Lex();
892 return false;
893}
894
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000895/// ParseStringConstant
896/// ::= StringConstant
897bool LLParser::ParseStringConstant(std::string &Result) {
898 if (Lex.getKind() != lltok::StringConstant)
899 return TokError("expected string constant");
900 Result = Lex.getStrVal();
901 Lex.Lex();
902 return false;
903}
904
905/// ParseUInt32
906/// ::= uint32
907bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000908 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
909 return TokError("expected integer");
910 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
911 if (Val64 != unsigned(Val64))
912 return TokError("expected 32-bit integer (too large)");
913 Val = Val64;
914 Lex.Lex();
915 return false;
916}
917
918
919/// ParseOptionalAddrSpace
920/// := /*empty*/
921/// := 'addrspace' '(' uint32 ')'
922bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
923 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000924 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000925 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000926 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000927 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000928 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000929}
Chris Lattnerdf986172009-01-02 07:01:27 +0000930
931/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
932/// indicates what kind of attribute list this is: 0: function arg, 1: result,
933/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000934/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000935bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
936 Attrs = Attribute::None;
937 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000938
Chris Lattnerdf986172009-01-02 07:01:27 +0000939 while (1) {
940 switch (Lex.getKind()) {
941 case lltok::kw_sext:
942 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000943 // Treat these as signext/zeroext if they occur in the argument list after
944 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
945 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
946 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000947 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000948 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000949 if (Lex.getKind() == lltok::kw_sext)
950 Attrs |= Attribute::SExt;
951 else
952 Attrs |= Attribute::ZExt;
953 break;
954 }
955 // FALL THROUGH.
956 default: // End of attributes.
957 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
958 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000959
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000960 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000961 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000962
Chris Lattnerdf986172009-01-02 07:01:27 +0000963 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000964 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
965 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
966 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
967 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
968 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
969 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
970 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
971 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000972
Devang Patel578efa92009-06-05 21:57:13 +0000973 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
974 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
975 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
976 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
977 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000978 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000979 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
980 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
981 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
982 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
983 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
984 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000985 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000986
Charles Davis1e063d12010-02-12 00:31:15 +0000987 case lltok::kw_alignstack: {
988 unsigned Alignment;
989 if (ParseOptionalStackAlignment(Alignment))
990 return true;
991 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
992 continue;
993 }
994
Chris Lattnerdf986172009-01-02 07:01:27 +0000995 case lltok::kw_align: {
996 unsigned Alignment;
997 if (ParseOptionalAlignment(Alignment))
998 return true;
999 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
1000 continue;
1001 }
Charles Davis1e063d12010-02-12 00:31:15 +00001002
Chris Lattnerdf986172009-01-02 07:01:27 +00001003 }
1004 Lex.Lex();
1005 }
1006}
1007
1008/// ParseOptionalLinkage
1009/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001010/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001011/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +00001012/// ::= 'linker_private_weak'
Bill Wendling55ae5152010-08-20 22:05:50 +00001013/// ::= 'linker_private_weak_def_auto'
Chris Lattnerdf986172009-01-02 07:01:27 +00001014/// ::= 'internal'
1015/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001016/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001017/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001018/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +00001019/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +00001020/// ::= 'appending'
1021/// ::= 'dllexport'
1022/// ::= 'common'
1023/// ::= 'dllimport'
1024/// ::= 'extern_weak'
1025/// ::= 'external'
1026bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1027 HasLinkage = false;
1028 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001029 default: Res=GlobalValue::ExternalLinkage; return false;
1030 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1031 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001032 case lltok::kw_linker_private_weak:
1033 Res = GlobalValue::LinkerPrivateWeakLinkage;
1034 break;
Bill Wendling55ae5152010-08-20 22:05:50 +00001035 case lltok::kw_linker_private_weak_def_auto:
1036 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1037 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001038 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1039 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1040 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1041 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1042 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001043 case lltok::kw_available_externally:
1044 Res = GlobalValue::AvailableExternallyLinkage;
1045 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001046 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1047 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1048 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1049 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1050 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1051 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001052 }
1053 Lex.Lex();
1054 HasLinkage = true;
1055 return false;
1056}
1057
1058/// ParseOptionalVisibility
1059/// ::= /*empty*/
1060/// ::= 'default'
1061/// ::= 'hidden'
1062/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001063///
Chris Lattnerdf986172009-01-02 07:01:27 +00001064bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1065 switch (Lex.getKind()) {
1066 default: Res = GlobalValue::DefaultVisibility; return false;
1067 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1068 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1069 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1070 }
1071 Lex.Lex();
1072 return false;
1073}
1074
1075/// ParseOptionalCallingConv
1076/// ::= /*empty*/
1077/// ::= 'ccc'
1078/// ::= 'fastcc'
1079/// ::= 'coldcc'
1080/// ::= 'x86_stdcallcc'
1081/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001082/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001083/// ::= 'arm_apcscc'
1084/// ::= 'arm_aapcscc'
1085/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001086/// ::= 'msp430_intrcc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001087/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001088///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001089bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001090 switch (Lex.getKind()) {
1091 default: CC = CallingConv::C; return false;
1092 case lltok::kw_ccc: CC = CallingConv::C; break;
1093 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1094 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1095 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1096 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001097 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001098 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1099 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1100 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001101 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001102 case lltok::kw_cc: {
1103 unsigned ArbitraryCC;
1104 Lex.Lex();
1105 if (ParseUInt32(ArbitraryCC)) {
1106 return true;
1107 } else
1108 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1109 return false;
1110 }
1111 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001112 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001113
Chris Lattnerdf986172009-01-02 07:01:27 +00001114 Lex.Lex();
1115 return false;
1116}
1117
Chris Lattnerb8c46862009-12-30 05:31:19 +00001118/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001119/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001120bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1121 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001122 do {
1123 if (Lex.getKind() != lltok::MetadataVar)
1124 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001125
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001126 std::string Name = Lex.getStrVal();
Dan Gohman309b3af2010-08-24 02:24:03 +00001127 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001128 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001129
Chris Lattner442ffa12009-12-29 21:53:55 +00001130 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001131 unsigned NodeID;
1132 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001133
1134 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001135 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001136
Dan Gohman309b3af2010-08-24 02:24:03 +00001137 if (Lex.getKind() == lltok::lbrace) {
1138 ValID ID;
1139 if (ParseMetadataListValue(ID, PFS))
1140 return true;
1141 assert(ID.Kind == ValID::t_MDNode);
1142 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001143 } else {
Dan Gohman309b3af2010-08-24 02:24:03 +00001144 if (ParseMDNodeID(Node, NodeID))
1145 return true;
1146 if (Node) {
1147 // If we got the node, add it to the instruction.
1148 Inst->setMetadata(MDK, Node);
1149 } else {
1150 MDRef R = { Loc, MDK, NodeID };
1151 // Otherwise, remember that this should be resolved later.
1152 ForwardRefInstMetadata[Inst].push_back(R);
1153 }
Chris Lattner449c3102010-04-01 05:14:45 +00001154 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001155
1156 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001157 } while (EatIfPresent(lltok::comma));
1158 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001159}
1160
Chris Lattnerdf986172009-01-02 07:01:27 +00001161/// ParseOptionalAlignment
1162/// ::= /* empty */
1163/// ::= 'align' 4
1164bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1165 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001166 if (!EatIfPresent(lltok::kw_align))
1167 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001168 LocTy AlignLoc = Lex.getLoc();
1169 if (ParseUInt32(Alignment)) return true;
1170 if (!isPowerOf2_32(Alignment))
1171 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001172 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001173 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001174 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001175}
1176
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001177/// ParseOptionalCommaAlign
1178/// ::=
1179/// ::= ',' align 4
1180///
1181/// This returns with AteExtraComma set to true if it ate an excess comma at the
1182/// end.
1183bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1184 bool &AteExtraComma) {
1185 AteExtraComma = false;
1186 while (EatIfPresent(lltok::comma)) {
1187 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001188 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001189 AteExtraComma = true;
1190 return false;
1191 }
1192
Chris Lattner093eed12010-04-23 00:50:50 +00001193 if (Lex.getKind() != lltok::kw_align)
1194 return Error(Lex.getLoc(), "expected metadata or 'align'");
1195
Dan Gohman138aa2a2010-07-28 20:12:04 +00001196 LocTy AlignLoc = Lex.getLoc();
Chris Lattner093eed12010-04-23 00:50:50 +00001197 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001198 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001199
Devang Patelf633a062009-09-17 23:04:48 +00001200 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001201}
1202
Charles Davis1e063d12010-02-12 00:31:15 +00001203/// ParseOptionalStackAlignment
1204/// ::= /* empty */
1205/// ::= 'alignstack' '(' 4 ')'
1206bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1207 Alignment = 0;
1208 if (!EatIfPresent(lltok::kw_alignstack))
1209 return false;
1210 LocTy ParenLoc = Lex.getLoc();
1211 if (!EatIfPresent(lltok::lparen))
1212 return Error(ParenLoc, "expected '('");
1213 LocTy AlignLoc = Lex.getLoc();
1214 if (ParseUInt32(Alignment)) return true;
1215 ParenLoc = Lex.getLoc();
1216 if (!EatIfPresent(lltok::rparen))
1217 return Error(ParenLoc, "expected ')'");
1218 if (!isPowerOf2_32(Alignment))
1219 return Error(AlignLoc, "stack alignment is not a power of two");
1220 return false;
1221}
Devang Patelf633a062009-09-17 23:04:48 +00001222
Chris Lattner628c13a2009-12-30 05:14:00 +00001223/// ParseIndexList - This parses the index list for an insert/extractvalue
1224/// instruction. This sets AteExtraComma in the case where we eat an extra
1225/// comma at the end of the line and find that it is followed by metadata.
1226/// Clients that don't allow metadata can call the version of this function that
1227/// only takes one argument.
1228///
Chris Lattnerdf986172009-01-02 07:01:27 +00001229/// ParseIndexList
1230/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001231///
1232bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1233 bool &AteExtraComma) {
1234 AteExtraComma = false;
1235
Chris Lattnerdf986172009-01-02 07:01:27 +00001236 if (Lex.getKind() != lltok::comma)
1237 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001238
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001239 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001240 if (Lex.getKind() == lltok::MetadataVar) {
1241 AteExtraComma = true;
1242 return false;
1243 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001244 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001245 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001246 Indices.push_back(Idx);
1247 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001248
Chris Lattnerdf986172009-01-02 07:01:27 +00001249 return false;
1250}
1251
1252//===----------------------------------------------------------------------===//
1253// Type Parsing.
1254//===----------------------------------------------------------------------===//
1255
1256/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001257bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1258 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001259 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001260
Chris Lattnerdf986172009-01-02 07:01:27 +00001261 // Verify no unresolved uprefs.
1262 if (!UpRefs.empty())
1263 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001264
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001265 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001266 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001267
Chris Lattnerdf986172009-01-02 07:01:27 +00001268 return false;
1269}
1270
1271/// HandleUpRefs - Every time we finish a new layer of types, this function is
1272/// called. It loops through the UpRefs vector, which is a list of the
1273/// currently active types. For each type, if the up-reference is contained in
1274/// the newly completed type, we decrement the level count. When the level
1275/// count reaches zero, the up-referenced type is the type that is passed in:
1276/// thus we can complete the cycle.
1277///
1278PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1279 // If Ty isn't abstract, or if there are no up-references in it, then there is
1280 // nothing to resolve here.
1281 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001282
Chris Lattnerdf986172009-01-02 07:01:27 +00001283 PATypeHolder Ty(ty);
1284#if 0
David Greene0e28d762009-12-23 23:38:28 +00001285 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001286 << "' newly formed. Resolving upreferences.\n"
1287 << UpRefs.size() << " upreferences active!\n";
1288#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001289
Chris Lattnerdf986172009-01-02 07:01:27 +00001290 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1291 // to zero), we resolve them all together before we resolve them to Ty. At
1292 // the end of the loop, if there is anything to resolve to Ty, it will be in
1293 // this variable.
1294 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001295
Chris Lattnerdf986172009-01-02 07:01:27 +00001296 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1297 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1298 bool ContainsType =
1299 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1300 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001301
Chris Lattnerdf986172009-01-02 07:01:27 +00001302#if 0
David Greene0e28d762009-12-23 23:38:28 +00001303 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001304 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1305 << (ContainsType ? "true" : "false")
1306 << " level=" << UpRefs[i].NestingLevel << "\n";
1307#endif
1308 if (!ContainsType)
1309 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001310
Chris Lattnerdf986172009-01-02 07:01:27 +00001311 // Decrement level of upreference
1312 unsigned Level = --UpRefs[i].NestingLevel;
1313 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001314
Chris Lattnerdf986172009-01-02 07:01:27 +00001315 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1316 if (Level != 0)
1317 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001318
Chris Lattnerdf986172009-01-02 07:01:27 +00001319#if 0
David Greene0e28d762009-12-23 23:38:28 +00001320 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001321#endif
1322 if (!TypeToResolve)
1323 TypeToResolve = UpRefs[i].UpRefTy;
1324 else
1325 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1326 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1327 --i; // Do not skip the next element.
1328 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001329
Chris Lattnerdf986172009-01-02 07:01:27 +00001330 if (TypeToResolve)
1331 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001332
Chris Lattnerdf986172009-01-02 07:01:27 +00001333 return Ty;
1334}
1335
1336
1337/// ParseTypeRec - The recursive function used to process the internal
1338/// implementation details of types.
1339bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1340 switch (Lex.getKind()) {
1341 default:
1342 return TokError("expected type");
1343 case lltok::Type:
1344 // TypeRec ::= 'float' | 'void' (etc)
1345 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001346 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001347 break;
1348 case lltok::kw_opaque:
1349 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001350 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001351 Lex.Lex();
1352 break;
1353 case lltok::lbrace:
1354 // TypeRec ::= '{' ... '}'
1355 if (ParseStructType(Result, false))
1356 return true;
1357 break;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00001358 case lltok::kw_union:
1359 // TypeRec ::= 'union' '{' ... '}'
1360 if (ParseUnionType(Result))
1361 return true;
1362 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001363 case lltok::lsquare:
1364 // TypeRec ::= '[' ... ']'
1365 Lex.Lex(); // eat the lsquare.
1366 if (ParseArrayVectorType(Result, false))
1367 return true;
1368 break;
1369 case lltok::less: // Either vector or packed struct.
1370 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001371 Lex.Lex();
1372 if (Lex.getKind() == lltok::lbrace) {
1373 if (ParseStructType(Result, true) ||
1374 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001375 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001376 } else if (ParseArrayVectorType(Result, true))
1377 return true;
1378 break;
1379 case lltok::LocalVar:
1380 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1381 // TypeRec ::= %foo
1382 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1383 Result = T;
1384 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001385 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001386 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1387 std::make_pair(Result,
1388 Lex.getLoc())));
1389 M->addTypeName(Lex.getStrVal(), Result.get());
1390 }
1391 Lex.Lex();
1392 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001393
Chris Lattnerdf986172009-01-02 07:01:27 +00001394 case lltok::LocalVarID:
1395 // TypeRec ::= %4
1396 if (Lex.getUIntVal() < NumberedTypes.size())
1397 Result = NumberedTypes[Lex.getUIntVal()];
1398 else {
1399 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1400 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1401 if (I != ForwardRefTypeIDs.end())
1402 Result = I->second.first;
1403 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001404 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001405 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1406 std::make_pair(Result,
1407 Lex.getLoc())));
1408 }
1409 }
1410 Lex.Lex();
1411 break;
1412 case lltok::backslash: {
1413 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001414 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001415 unsigned Val;
1416 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001417 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001418 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1419 Result = OT;
1420 break;
1421 }
1422 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001423
1424 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001425 while (1) {
1426 switch (Lex.getKind()) {
1427 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001428 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001429
1430 // TypeRec ::= TypeRec '*'
1431 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001432 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001433 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001434 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001435 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001436 if (!PointerType::isValidElementType(Result.get()))
1437 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001438 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001439 Lex.Lex();
1440 break;
1441
1442 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1443 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001444 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001445 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001446 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001447 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001448 if (!PointerType::isValidElementType(Result.get()))
1449 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001450 unsigned AddrSpace;
1451 if (ParseOptionalAddrSpace(AddrSpace) ||
1452 ParseToken(lltok::star, "expected '*' in address space"))
1453 return true;
1454
Owen Andersondebcb012009-07-29 22:17:13 +00001455 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001456 break;
1457 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001458
Chris Lattnerdf986172009-01-02 07:01:27 +00001459 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1460 case lltok::lparen:
1461 if (ParseFunctionType(Result))
1462 return true;
1463 break;
1464 }
1465 }
1466}
1467
1468/// ParseParameterList
1469/// ::= '(' ')'
1470/// ::= '(' Arg (',' Arg)* ')'
1471/// Arg
1472/// ::= Type OptionalAttributes Value OptionalAttributes
1473bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1474 PerFunctionState &PFS) {
1475 if (ParseToken(lltok::lparen, "expected '(' in call"))
1476 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001477
Chris Lattnerdf986172009-01-02 07:01:27 +00001478 while (Lex.getKind() != lltok::rparen) {
1479 // If this isn't the first argument, we need a comma.
1480 if (!ArgList.empty() &&
1481 ParseToken(lltok::comma, "expected ',' in argument list"))
1482 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001483
Chris Lattnerdf986172009-01-02 07:01:27 +00001484 // Parse the argument.
1485 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001486 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001487 unsigned ArgAttrs1 = Attribute::None;
1488 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001489 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001490 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001491 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001492
Chris Lattner287881d2009-12-30 02:11:14 +00001493 // Otherwise, handle normal operands.
1494 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1495 ParseValue(ArgTy, V, PFS) ||
1496 // FIXME: Should not allow attributes after the argument, remove this
1497 // in LLVM 3.0.
1498 ParseOptionalAttrs(ArgAttrs2, 3))
1499 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001500 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1501 }
1502
1503 Lex.Lex(); // Lex the ')'.
1504 return false;
1505}
1506
1507
1508
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001509/// ParseArgumentList - Parse the argument list for a function type or function
1510/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001511/// ::= '(' ArgTypeListI ')'
1512/// ArgTypeListI
1513/// ::= /*empty*/
1514/// ::= '...'
1515/// ::= ArgTypeList ',' '...'
1516/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001517///
Chris Lattnerdf986172009-01-02 07:01:27 +00001518bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001519 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001520 isVarArg = false;
1521 assert(Lex.getKind() == lltok::lparen);
1522 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001523
Chris Lattnerdf986172009-01-02 07:01:27 +00001524 if (Lex.getKind() == lltok::rparen) {
1525 // empty
1526 } else if (Lex.getKind() == lltok::dotdotdot) {
1527 isVarArg = true;
1528 Lex.Lex();
1529 } else {
1530 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001531 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001532 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001533 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001534
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001535 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1536 // types (such as a function returning a pointer to itself). If parsing a
1537 // function prototype, we require fully resolved types.
1538 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001539 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001540
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001541 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001542 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001543
Chris Lattnerdf986172009-01-02 07:01:27 +00001544 if (Lex.getKind() == lltok::LocalVar ||
1545 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1546 Name = Lex.getStrVal();
1547 Lex.Lex();
1548 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001549
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001550 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001551 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001552
Chris Lattnerdf986172009-01-02 07:01:27 +00001553 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001554
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001555 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001556 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001557 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001558 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001559 break;
1560 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001561
Chris Lattnerdf986172009-01-02 07:01:27 +00001562 // Otherwise must be an argument type.
1563 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001564 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001565 ParseOptionalAttrs(Attrs, 0)) return true;
1566
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001567 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001568 return Error(TypeLoc, "argument can not have void type");
1569
Chris Lattnerdf986172009-01-02 07:01:27 +00001570 if (Lex.getKind() == lltok::LocalVar ||
1571 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1572 Name = Lex.getStrVal();
1573 Lex.Lex();
1574 } else {
1575 Name = "";
1576 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001577
Duncan Sands47c51882010-02-16 14:50:09 +00001578 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001579 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001580
Chris Lattnerdf986172009-01-02 07:01:27 +00001581 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1582 }
1583 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001584
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001585 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001586}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001587
Chris Lattnerdf986172009-01-02 07:01:27 +00001588/// ParseFunctionType
1589/// ::= Type ArgumentList OptionalAttrs
1590bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1591 assert(Lex.getKind() == lltok::lparen);
1592
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001593 if (!FunctionType::isValidReturnType(Result))
1594 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001595
Chris Lattnerdf986172009-01-02 07:01:27 +00001596 std::vector<ArgInfo> ArgList;
1597 bool isVarArg;
1598 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001599 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001600 // FIXME: Allow, but ignore attributes on function types!
1601 // FIXME: Remove in LLVM 3.0
1602 ParseOptionalAttrs(Attrs, 2))
1603 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001604
Chris Lattnerdf986172009-01-02 07:01:27 +00001605 // Reject names on the arguments lists.
1606 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1607 if (!ArgList[i].Name.empty())
1608 return Error(ArgList[i].Loc, "argument name invalid in function type");
1609 if (!ArgList[i].Attrs != 0) {
1610 // Allow but ignore attributes on function types; this permits
1611 // auto-upgrade.
1612 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1613 }
1614 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001615
Chris Lattnerdf986172009-01-02 07:01:27 +00001616 std::vector<const Type*> ArgListTy;
1617 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1618 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001619
Owen Andersondebcb012009-07-29 22:17:13 +00001620 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001621 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001622 return false;
1623}
1624
1625/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1626/// TypeRec
1627/// ::= '{' '}'
1628/// ::= '{' TypeRec (',' TypeRec)* '}'
1629/// ::= '<' '{' '}' '>'
1630/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1631bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1632 assert(Lex.getKind() == lltok::lbrace);
1633 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001634
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001635 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001636 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001637 return false;
1638 }
1639
1640 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001641 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001642 if (ParseTypeRec(Result)) return true;
1643 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001644
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001645 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001646 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001647 if (!StructType::isValidElementType(Result))
1648 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001649
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001650 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001651 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001652 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001653
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001654 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001655 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001656 if (!StructType::isValidElementType(Result))
1657 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001658
Chris Lattnerdf986172009-01-02 07:01:27 +00001659 ParamsList.push_back(Result);
1660 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001661
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001662 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1663 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001664
Chris Lattnerdf986172009-01-02 07:01:27 +00001665 std::vector<const Type*> ParamsListTy;
1666 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1667 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001668 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001669 return false;
1670}
1671
Chris Lattnerfdfeb692010-02-12 20:49:41 +00001672/// ParseUnionType
1673/// TypeRec
1674/// ::= 'union' '{' TypeRec (',' TypeRec)* '}'
1675bool LLParser::ParseUnionType(PATypeHolder &Result) {
1676 assert(Lex.getKind() == lltok::kw_union);
1677 Lex.Lex(); // Consume the 'union'
1678
1679 if (ParseToken(lltok::lbrace, "'{' expected after 'union'")) return true;
1680
1681 SmallVector<PATypeHolder, 8> ParamsList;
1682 do {
1683 LocTy EltTyLoc = Lex.getLoc();
1684 if (ParseTypeRec(Result)) return true;
1685 ParamsList.push_back(Result);
1686
1687 if (Result->isVoidTy())
1688 return Error(EltTyLoc, "union element can not have void type");
1689 if (!UnionType::isValidElementType(Result))
1690 return Error(EltTyLoc, "invalid element type for union");
1691
1692 } while (EatIfPresent(lltok::comma)) ;
1693
1694 if (ParseToken(lltok::rbrace, "expected '}' at end of union"))
1695 return true;
1696
1697 SmallVector<const Type*, 8> ParamsListTy;
1698 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1699 ParamsListTy.push_back(ParamsList[i].get());
1700 Result = HandleUpRefs(UnionType::get(&ParamsListTy[0], ParamsListTy.size()));
1701 return false;
1702}
1703
Chris Lattnerdf986172009-01-02 07:01:27 +00001704/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1705/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001706/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001707/// ::= '[' APSINTVAL 'x' Types ']'
1708/// ::= '<' APSINTVAL 'x' Types '>'
1709bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1710 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1711 Lex.getAPSIntVal().getBitWidth() > 64)
1712 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001713
Chris Lattnerdf986172009-01-02 07:01:27 +00001714 LocTy SizeLoc = Lex.getLoc();
1715 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001716 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001717
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001718 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1719 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001720
1721 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001722 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001723 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001724
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001725 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001726 return Error(TypeLoc, "array and vector element type cannot be void");
1727
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001728 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1729 "expected end of sequential type"))
1730 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001731
Chris Lattnerdf986172009-01-02 07:01:27 +00001732 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001733 if (Size == 0)
1734 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001735 if ((unsigned)Size != Size)
1736 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001737 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001738 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001739 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001740 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001741 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001742 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001743 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001744 }
1745 return false;
1746}
1747
1748//===----------------------------------------------------------------------===//
1749// Function Semantic Analysis.
1750//===----------------------------------------------------------------------===//
1751
Chris Lattner09d9ef42009-10-28 03:39:23 +00001752LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1753 int functionNumber)
1754 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001755
1756 // Insert unnamed arguments into the NumberedVals list.
1757 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1758 AI != E; ++AI)
1759 if (!AI->hasName())
1760 NumberedVals.push_back(AI);
1761}
1762
1763LLParser::PerFunctionState::~PerFunctionState() {
1764 // If there were any forward referenced non-basicblock values, delete them.
1765 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1766 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1767 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001768 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001769 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001770 delete I->second.first;
1771 I->second.first = 0;
1772 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001773
Chris Lattnerdf986172009-01-02 07:01:27 +00001774 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1775 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1776 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001777 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001778 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001779 delete I->second.first;
1780 I->second.first = 0;
1781 }
1782}
1783
Chris Lattner09d9ef42009-10-28 03:39:23 +00001784bool LLParser::PerFunctionState::FinishFunction() {
1785 // Check to see if someone took the address of labels in this block.
1786 if (!P.ForwardRefBlockAddresses.empty()) {
1787 ValID FunctionID;
1788 if (!F.getName().empty()) {
1789 FunctionID.Kind = ValID::t_GlobalName;
1790 FunctionID.StrVal = F.getName();
1791 } else {
1792 FunctionID.Kind = ValID::t_GlobalID;
1793 FunctionID.UIntVal = FunctionNumber;
1794 }
1795
1796 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1797 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1798 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1799 // Resolve all these references.
1800 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1801 return true;
1802
1803 P.ForwardRefBlockAddresses.erase(FRBAI);
1804 }
1805 }
1806
Chris Lattnerdf986172009-01-02 07:01:27 +00001807 if (!ForwardRefVals.empty())
1808 return P.Error(ForwardRefVals.begin()->second.second,
1809 "use of undefined value '%" + ForwardRefVals.begin()->first +
1810 "'");
1811 if (!ForwardRefValIDs.empty())
1812 return P.Error(ForwardRefValIDs.begin()->second.second,
1813 "use of undefined value '%" +
1814 utostr(ForwardRefValIDs.begin()->first) + "'");
1815 return false;
1816}
1817
1818
1819/// GetVal - Get a value with the specified name or ID, creating a
1820/// forward reference record if needed. This can return null if the value
1821/// exists but does not have the right type.
1822Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1823 const Type *Ty, LocTy Loc) {
1824 // Look this name up in the normal function symbol table.
1825 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001826
Chris Lattnerdf986172009-01-02 07:01:27 +00001827 // If this is a forward reference for the value, see if we already created a
1828 // forward ref record.
1829 if (Val == 0) {
1830 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1831 I = ForwardRefVals.find(Name);
1832 if (I != ForwardRefVals.end())
1833 Val = I->second.first;
1834 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001835
Chris Lattnerdf986172009-01-02 07:01:27 +00001836 // If we have the value in the symbol table or fwd-ref table, return it.
1837 if (Val) {
1838 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001839 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001840 P.Error(Loc, "'%" + Name + "' is not a basic block");
1841 else
1842 P.Error(Loc, "'%" + Name + "' defined with type '" +
1843 Val->getType()->getDescription() + "'");
1844 return 0;
1845 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001846
Chris Lattnerdf986172009-01-02 07:01:27 +00001847 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001848 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001849 P.Error(Loc, "invalid use of a non-first-class type");
1850 return 0;
1851 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001852
Chris Lattnerdf986172009-01-02 07:01:27 +00001853 // Otherwise, create a new forward reference for this value and remember it.
1854 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001855 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001856 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001857 else
1858 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001859
Chris Lattnerdf986172009-01-02 07:01:27 +00001860 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1861 return FwdVal;
1862}
1863
1864Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1865 LocTy Loc) {
1866 // Look this name up in the normal function symbol table.
1867 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001868
Chris Lattnerdf986172009-01-02 07:01:27 +00001869 // If this is a forward reference for the value, see if we already created a
1870 // forward ref record.
1871 if (Val == 0) {
1872 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1873 I = ForwardRefValIDs.find(ID);
1874 if (I != ForwardRefValIDs.end())
1875 Val = I->second.first;
1876 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001877
Chris Lattnerdf986172009-01-02 07:01:27 +00001878 // If we have the value in the symbol table or fwd-ref table, return it.
1879 if (Val) {
1880 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001881 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001882 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1883 else
1884 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1885 Val->getType()->getDescription() + "'");
1886 return 0;
1887 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001888
Duncan Sands47c51882010-02-16 14:50:09 +00001889 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001890 P.Error(Loc, "invalid use of a non-first-class type");
1891 return 0;
1892 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001893
Chris Lattnerdf986172009-01-02 07:01:27 +00001894 // Otherwise, create a new forward reference for this value and remember it.
1895 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001896 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001897 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001898 else
1899 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001900
Chris Lattnerdf986172009-01-02 07:01:27 +00001901 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1902 return FwdVal;
1903}
1904
1905/// SetInstName - After an instruction is parsed and inserted into its
1906/// basic block, this installs its name.
1907bool LLParser::PerFunctionState::SetInstName(int NameID,
1908 const std::string &NameStr,
1909 LocTy NameLoc, Instruction *Inst) {
1910 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001911 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001912 if (NameID != -1 || !NameStr.empty())
1913 return P.Error(NameLoc, "instructions returning void cannot have a name");
1914 return false;
1915 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001916
Chris Lattnerdf986172009-01-02 07:01:27 +00001917 // If this was a numbered instruction, verify that the instruction is the
1918 // expected value and resolve any forward references.
1919 if (NameStr.empty()) {
1920 // If neither a name nor an ID was specified, just use the next ID.
1921 if (NameID == -1)
1922 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001923
Chris Lattnerdf986172009-01-02 07:01:27 +00001924 if (unsigned(NameID) != NumberedVals.size())
1925 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1926 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001927
Chris Lattnerdf986172009-01-02 07:01:27 +00001928 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1929 ForwardRefValIDs.find(NameID);
1930 if (FI != ForwardRefValIDs.end()) {
1931 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001932 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001933 FI->second.first->getType()->getDescription() + "'");
1934 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001935 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001936 ForwardRefValIDs.erase(FI);
1937 }
1938
1939 NumberedVals.push_back(Inst);
1940 return false;
1941 }
1942
1943 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1944 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1945 FI = ForwardRefVals.find(NameStr);
1946 if (FI != ForwardRefVals.end()) {
1947 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001948 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001949 FI->second.first->getType()->getDescription() + "'");
1950 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001951 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001952 ForwardRefVals.erase(FI);
1953 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001954
Chris Lattnerdf986172009-01-02 07:01:27 +00001955 // Set the name on the instruction.
1956 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001957
Chris Lattnerdf986172009-01-02 07:01:27 +00001958 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001959 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001960 NameStr + "'");
1961 return false;
1962}
1963
1964/// GetBB - Get a basic block with the specified name or ID, creating a
1965/// forward reference record if needed.
1966BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1967 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001968 return cast_or_null<BasicBlock>(GetVal(Name,
1969 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001970}
1971
1972BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001973 return cast_or_null<BasicBlock>(GetVal(ID,
1974 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001975}
1976
1977/// DefineBB - Define the specified basic block, which is either named or
1978/// unnamed. If there is an error, this returns null otherwise it returns
1979/// the block being defined.
1980BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1981 LocTy Loc) {
1982 BasicBlock *BB;
1983 if (Name.empty())
1984 BB = GetBB(NumberedVals.size(), Loc);
1985 else
1986 BB = GetBB(Name, Loc);
1987 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001988
Chris Lattnerdf986172009-01-02 07:01:27 +00001989 // Move the block to the end of the function. Forward ref'd blocks are
1990 // inserted wherever they happen to be referenced.
1991 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001992
Chris Lattnerdf986172009-01-02 07:01:27 +00001993 // Remove the block from forward ref sets.
1994 if (Name.empty()) {
1995 ForwardRefValIDs.erase(NumberedVals.size());
1996 NumberedVals.push_back(BB);
1997 } else {
1998 // BB forward references are already in the function symbol table.
1999 ForwardRefVals.erase(Name);
2000 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002001
Chris Lattnerdf986172009-01-02 07:01:27 +00002002 return BB;
2003}
2004
2005//===----------------------------------------------------------------------===//
2006// Constants.
2007//===----------------------------------------------------------------------===//
2008
2009/// ParseValID - Parse an abstract value that doesn't necessarily have a
2010/// type implied. For example, if we parse "4" we don't know what integer type
2011/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00002012/// sanity. PFS is used to convert function-local operands of metadata (since
2013/// metadata operands are not just parsed here but also converted to values).
2014/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00002015bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002016 ID.Loc = Lex.getLoc();
2017 switch (Lex.getKind()) {
2018 default: return TokError("expected value token");
2019 case lltok::GlobalID: // @42
2020 ID.UIntVal = Lex.getUIntVal();
2021 ID.Kind = ValID::t_GlobalID;
2022 break;
2023 case lltok::GlobalVar: // @foo
2024 ID.StrVal = Lex.getStrVal();
2025 ID.Kind = ValID::t_GlobalName;
2026 break;
2027 case lltok::LocalVarID: // %42
2028 ID.UIntVal = Lex.getUIntVal();
2029 ID.Kind = ValID::t_LocalID;
2030 break;
2031 case lltok::LocalVar: // %foo
2032 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2033 ID.StrVal = Lex.getStrVal();
2034 ID.Kind = ValID::t_LocalName;
2035 break;
Dan Gohman83448032010-07-14 18:26:50 +00002036 case lltok::exclaim: // !42, !{...}, or !"foo"
2037 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002038 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002039 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002040 ID.Kind = ValID::t_APSInt;
2041 break;
2042 case lltok::APFloat:
2043 ID.APFloatVal = Lex.getAPFloatVal();
2044 ID.Kind = ValID::t_APFloat;
2045 break;
2046 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002047 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002048 ID.Kind = ValID::t_Constant;
2049 break;
2050 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002051 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002052 ID.Kind = ValID::t_Constant;
2053 break;
2054 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2055 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2056 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002057
Chris Lattnerdf986172009-01-02 07:01:27 +00002058 case lltok::lbrace: {
2059 // ValID ::= '{' ConstVector '}'
2060 Lex.Lex();
2061 SmallVector<Constant*, 16> Elts;
2062 if (ParseGlobalValueVector(Elts) ||
2063 ParseToken(lltok::rbrace, "expected end of struct constant"))
2064 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002065
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002066 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2067 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002068 ID.Kind = ValID::t_Constant;
2069 return false;
2070 }
2071 case lltok::less: {
2072 // ValID ::= '<' ConstVector '>' --> Vector.
2073 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2074 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002075 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002076
Chris Lattnerdf986172009-01-02 07:01:27 +00002077 SmallVector<Constant*, 16> Elts;
2078 LocTy FirstEltLoc = Lex.getLoc();
2079 if (ParseGlobalValueVector(Elts) ||
2080 (isPackedStruct &&
2081 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2082 ParseToken(lltok::greater, "expected end of constant"))
2083 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002084
Chris Lattnerdf986172009-01-02 07:01:27 +00002085 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002086 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002087 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002088 ID.Kind = ValID::t_Constant;
2089 return false;
2090 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002091
Chris Lattnerdf986172009-01-02 07:01:27 +00002092 if (Elts.empty())
2093 return Error(ID.Loc, "constant vector must not be empty");
2094
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002095 if (!Elts[0]->getType()->isIntegerTy() &&
2096 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002097 return Error(FirstEltLoc,
2098 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002099
Chris Lattnerdf986172009-01-02 07:01:27 +00002100 // Verify that all the vector elements have the same type.
2101 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2102 if (Elts[i]->getType() != Elts[0]->getType())
2103 return Error(FirstEltLoc,
2104 "vector element #" + utostr(i) +
2105 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002106
Owen Andersonaf7ec972009-07-28 21:19:26 +00002107 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002108 ID.Kind = ValID::t_Constant;
2109 return false;
2110 }
2111 case lltok::lsquare: { // Array Constant
2112 Lex.Lex();
2113 SmallVector<Constant*, 16> Elts;
2114 LocTy FirstEltLoc = Lex.getLoc();
2115 if (ParseGlobalValueVector(Elts) ||
2116 ParseToken(lltok::rsquare, "expected end of array constant"))
2117 return true;
2118
2119 // Handle empty element.
2120 if (Elts.empty()) {
2121 // Use undef instead of an array because it's inconvenient to determine
2122 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002123 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002124 return false;
2125 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002126
Chris Lattnerdf986172009-01-02 07:01:27 +00002127 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002128 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002129 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002130
Owen Andersondebcb012009-07-29 22:17:13 +00002131 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002132
Chris Lattnerdf986172009-01-02 07:01:27 +00002133 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002134 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002135 if (Elts[i]->getType() != Elts[0]->getType())
2136 return Error(FirstEltLoc,
2137 "array element #" + utostr(i) +
2138 " is not of type '" +Elts[0]->getType()->getDescription());
2139 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002140
Owen Anderson1fd70962009-07-28 18:32:17 +00002141 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002142 ID.Kind = ValID::t_Constant;
2143 return false;
2144 }
2145 case lltok::kw_c: // c "foo"
2146 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002147 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002148 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2149 ID.Kind = ValID::t_Constant;
2150 return false;
2151
2152 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002153 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2154 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002155 Lex.Lex();
2156 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002157 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002158 ParseStringConstant(ID.StrVal) ||
2159 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002160 ParseToken(lltok::StringConstant, "expected constraint string"))
2161 return true;
2162 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002163 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002164 ID.Kind = ValID::t_InlineAsm;
2165 return false;
2166 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002167
Chris Lattner09d9ef42009-10-28 03:39:23 +00002168 case lltok::kw_blockaddress: {
2169 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2170 Lex.Lex();
2171
2172 ValID Fn, Label;
2173 LocTy FnLoc, LabelLoc;
2174
2175 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2176 ParseValID(Fn) ||
2177 ParseToken(lltok::comma, "expected comma in block address expression")||
2178 ParseValID(Label) ||
2179 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2180 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002181
Chris Lattner09d9ef42009-10-28 03:39:23 +00002182 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2183 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002184 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002185 return Error(Label.Loc, "expected basic block name in blockaddress");
2186
2187 // Make a global variable as a placeholder for this reference.
2188 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2189 false, GlobalValue::InternalLinkage,
2190 0, "");
2191 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2192 ID.ConstantVal = FwdRef;
2193 ID.Kind = ValID::t_Constant;
2194 return false;
2195 }
2196
Chris Lattnerdf986172009-01-02 07:01:27 +00002197 case lltok::kw_trunc:
2198 case lltok::kw_zext:
2199 case lltok::kw_sext:
2200 case lltok::kw_fptrunc:
2201 case lltok::kw_fpext:
2202 case lltok::kw_bitcast:
2203 case lltok::kw_uitofp:
2204 case lltok::kw_sitofp:
2205 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002206 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002207 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002208 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002209 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002210 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002211 Constant *SrcVal;
2212 Lex.Lex();
2213 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2214 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002215 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002216 ParseType(DestTy) ||
2217 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2218 return true;
2219 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2220 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2221 SrcVal->getType()->getDescription() + "' to '" +
2222 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002223 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002224 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002225 ID.Kind = ValID::t_Constant;
2226 return false;
2227 }
2228 case lltok::kw_extractvalue: {
2229 Lex.Lex();
2230 Constant *Val;
2231 SmallVector<unsigned, 4> Indices;
2232 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2233 ParseGlobalTypeAndValue(Val) ||
2234 ParseIndexList(Indices) ||
2235 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2236 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002237
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002238 if (!Val->getType()->isAggregateType())
2239 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002240 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2241 Indices.end()))
2242 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002243 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002244 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002245 ID.Kind = ValID::t_Constant;
2246 return false;
2247 }
2248 case lltok::kw_insertvalue: {
2249 Lex.Lex();
2250 Constant *Val0, *Val1;
2251 SmallVector<unsigned, 4> Indices;
2252 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2253 ParseGlobalTypeAndValue(Val0) ||
2254 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2255 ParseGlobalTypeAndValue(Val1) ||
2256 ParseIndexList(Indices) ||
2257 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2258 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002259 if (!Val0->getType()->isAggregateType())
2260 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002261 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2262 Indices.end()))
2263 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002264 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002265 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002266 ID.Kind = ValID::t_Constant;
2267 return false;
2268 }
2269 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002270 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002271 unsigned PredVal, Opc = Lex.getUIntVal();
2272 Constant *Val0, *Val1;
2273 Lex.Lex();
2274 if (ParseCmpPredicate(PredVal, Opc) ||
2275 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2276 ParseGlobalTypeAndValue(Val0) ||
2277 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2278 ParseGlobalTypeAndValue(Val1) ||
2279 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2280 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002281
Chris Lattnerdf986172009-01-02 07:01:27 +00002282 if (Val0->getType() != Val1->getType())
2283 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002284
Chris Lattnerdf986172009-01-02 07:01:27 +00002285 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002286
Chris Lattnerdf986172009-01-02 07:01:27 +00002287 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002288 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002289 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002290 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002291 } else {
2292 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002293 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002294 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002295 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002296 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002297 }
2298 ID.Kind = ValID::t_Constant;
2299 return false;
2300 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002301
Chris Lattnerdf986172009-01-02 07:01:27 +00002302 // Binary Operators.
2303 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002304 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002305 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002306 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002307 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002308 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002309 case lltok::kw_udiv:
2310 case lltok::kw_sdiv:
2311 case lltok::kw_fdiv:
2312 case lltok::kw_urem:
2313 case lltok::kw_srem:
2314 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002315 bool NUW = false;
2316 bool NSW = false;
2317 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002318 unsigned Opc = Lex.getUIntVal();
2319 Constant *Val0, *Val1;
2320 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002321 LocTy ModifierLoc = Lex.getLoc();
2322 if (Opc == Instruction::Add ||
2323 Opc == Instruction::Sub ||
2324 Opc == Instruction::Mul) {
2325 if (EatIfPresent(lltok::kw_nuw))
2326 NUW = true;
2327 if (EatIfPresent(lltok::kw_nsw)) {
2328 NSW = true;
2329 if (EatIfPresent(lltok::kw_nuw))
2330 NUW = true;
2331 }
2332 } else if (Opc == Instruction::SDiv) {
2333 if (EatIfPresent(lltok::kw_exact))
2334 Exact = true;
2335 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002336 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2337 ParseGlobalTypeAndValue(Val0) ||
2338 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2339 ParseGlobalTypeAndValue(Val1) ||
2340 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2341 return true;
2342 if (Val0->getType() != Val1->getType())
2343 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002344 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002345 if (NUW)
2346 return Error(ModifierLoc, "nuw only applies to integer operations");
2347 if (NSW)
2348 return Error(ModifierLoc, "nsw only applies to integer operations");
2349 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002350 // Check that the type is valid for the operator.
2351 switch (Opc) {
2352 case Instruction::Add:
2353 case Instruction::Sub:
2354 case Instruction::Mul:
2355 case Instruction::UDiv:
2356 case Instruction::SDiv:
2357 case Instruction::URem:
2358 case Instruction::SRem:
2359 if (!Val0->getType()->isIntOrIntVectorTy())
2360 return Error(ID.Loc, "constexpr requires integer operands");
2361 break;
2362 case Instruction::FAdd:
2363 case Instruction::FSub:
2364 case Instruction::FMul:
2365 case Instruction::FDiv:
2366 case Instruction::FRem:
2367 if (!Val0->getType()->isFPOrFPVectorTy())
2368 return Error(ID.Loc, "constexpr requires fp operands");
2369 break;
2370 default: llvm_unreachable("Unknown binary operator!");
2371 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002372 unsigned Flags = 0;
2373 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2374 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2375 if (Exact) Flags |= SDivOperator::IsExact;
2376 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002377 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002378 ID.Kind = ValID::t_Constant;
2379 return false;
2380 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002381
Chris Lattnerdf986172009-01-02 07:01:27 +00002382 // Logical Operations
2383 case lltok::kw_shl:
2384 case lltok::kw_lshr:
2385 case lltok::kw_ashr:
2386 case lltok::kw_and:
2387 case lltok::kw_or:
2388 case lltok::kw_xor: {
2389 unsigned Opc = Lex.getUIntVal();
2390 Constant *Val0, *Val1;
2391 Lex.Lex();
2392 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2393 ParseGlobalTypeAndValue(Val0) ||
2394 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2395 ParseGlobalTypeAndValue(Val1) ||
2396 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2397 return true;
2398 if (Val0->getType() != Val1->getType())
2399 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002400 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002401 return Error(ID.Loc,
2402 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002403 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002404 ID.Kind = ValID::t_Constant;
2405 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002406 }
2407
Chris Lattnerdf986172009-01-02 07:01:27 +00002408 case lltok::kw_getelementptr:
2409 case lltok::kw_shufflevector:
2410 case lltok::kw_insertelement:
2411 case lltok::kw_extractelement:
2412 case lltok::kw_select: {
2413 unsigned Opc = Lex.getUIntVal();
2414 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002415 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002416 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002417 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002418 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002419 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2420 ParseGlobalValueVector(Elts) ||
2421 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2422 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002423
Chris Lattnerdf986172009-01-02 07:01:27 +00002424 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002425 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002426 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002427
Chris Lattnerdf986172009-01-02 07:01:27 +00002428 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002429 (Value**)(Elts.data() + 1),
2430 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002431 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002432 ID.ConstantVal = InBounds ?
2433 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2434 Elts.data() + 1,
2435 Elts.size() - 1) :
2436 ConstantExpr::getGetElementPtr(Elts[0],
2437 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002438 } else if (Opc == Instruction::Select) {
2439 if (Elts.size() != 3)
2440 return Error(ID.Loc, "expected three operands to select");
2441 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2442 Elts[2]))
2443 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002444 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002445 } else if (Opc == Instruction::ShuffleVector) {
2446 if (Elts.size() != 3)
2447 return Error(ID.Loc, "expected three operands to shufflevector");
2448 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2449 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002450 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002451 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002452 } else if (Opc == Instruction::ExtractElement) {
2453 if (Elts.size() != 2)
2454 return Error(ID.Loc, "expected two operands to extractelement");
2455 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2456 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002457 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002458 } else {
2459 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2460 if (Elts.size() != 3)
2461 return Error(ID.Loc, "expected three operands to insertelement");
2462 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2463 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002464 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002465 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002466 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002467
Chris Lattnerdf986172009-01-02 07:01:27 +00002468 ID.Kind = ValID::t_Constant;
2469 return false;
2470 }
2471 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002472
Chris Lattnerdf986172009-01-02 07:01:27 +00002473 Lex.Lex();
2474 return false;
2475}
2476
2477/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002478bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2479 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002480 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002481 Value *V = NULL;
2482 bool Parsed = ParseValID(ID) ||
2483 ConvertValIDToValue(Ty, ID, V, NULL);
2484 if (V && !(C = dyn_cast<Constant>(V)))
2485 return Error(ID.Loc, "global values must be constants");
2486 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002487}
2488
Victor Hernandez92f238d2010-01-11 22:31:58 +00002489bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2490 PATypeHolder Type(Type::getVoidTy(Context));
2491 return ParseType(Type) ||
2492 ParseGlobalValue(Type, V);
2493}
2494
2495/// ParseGlobalValueVector
2496/// ::= /*empty*/
2497/// ::= TypeAndValue (',' TypeAndValue)*
2498bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2499 // Empty list.
2500 if (Lex.getKind() == lltok::rbrace ||
2501 Lex.getKind() == lltok::rsquare ||
2502 Lex.getKind() == lltok::greater ||
2503 Lex.getKind() == lltok::rparen)
2504 return false;
2505
2506 Constant *C;
2507 if (ParseGlobalTypeAndValue(C)) return true;
2508 Elts.push_back(C);
2509
2510 while (EatIfPresent(lltok::comma)) {
2511 if (ParseGlobalTypeAndValue(C)) return true;
2512 Elts.push_back(C);
2513 }
2514
2515 return false;
2516}
2517
Dan Gohman309b3af2010-08-24 02:24:03 +00002518bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2519 assert(Lex.getKind() == lltok::lbrace);
2520 Lex.Lex();
2521
2522 SmallVector<Value*, 16> Elts;
2523 if (ParseMDNodeVector(Elts, PFS) ||
2524 ParseToken(lltok::rbrace, "expected end of metadata node"))
2525 return true;
2526
2527 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
2528 ID.Kind = ValID::t_MDNode;
2529 return false;
2530}
2531
Dan Gohman83448032010-07-14 18:26:50 +00002532/// ParseMetadataValue
2533/// ::= !42
2534/// ::= !{...}
2535/// ::= !"string"
2536bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2537 assert(Lex.getKind() == lltok::exclaim);
2538 Lex.Lex();
2539
2540 // MDNode:
2541 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002542 if (Lex.getKind() == lltok::lbrace)
2543 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002544
2545 // Standalone metadata reference
2546 // !42
2547 if (Lex.getKind() == lltok::APSInt) {
2548 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2549 ID.Kind = ValID::t_MDNode;
2550 return false;
2551 }
2552
2553 // MDString:
2554 // ::= '!' STRINGCONSTANT
2555 if (ParseMDString(ID.MDStringVal)) return true;
2556 ID.Kind = ValID::t_MDString;
2557 return false;
2558}
2559
Victor Hernandez92f238d2010-01-11 22:31:58 +00002560
2561//===----------------------------------------------------------------------===//
2562// Function Parsing.
2563//===----------------------------------------------------------------------===//
2564
2565bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2566 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002567 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002568 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002569
Chris Lattnerdf986172009-01-02 07:01:27 +00002570 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002571 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002572 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002573 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2574 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2575 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002576 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002577 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2578 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2579 return (V == 0);
2580 case ValID::t_InlineAsm: {
2581 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2582 const FunctionType *FTy =
2583 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2584 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2585 return Error(ID.Loc, "invalid type for inline asm constraint string");
2586 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2587 return false;
2588 }
2589 case ValID::t_MDNode:
2590 if (!Ty->isMetadataTy())
2591 return Error(ID.Loc, "metadata value must have metadata type");
2592 V = ID.MDNodeVal;
2593 return false;
2594 case ValID::t_MDString:
2595 if (!Ty->isMetadataTy())
2596 return Error(ID.Loc, "metadata value must have metadata type");
2597 V = ID.MDStringVal;
2598 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002599 case ValID::t_GlobalName:
2600 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2601 return V == 0;
2602 case ValID::t_GlobalID:
2603 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2604 return V == 0;
2605 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002606 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002607 return Error(ID.Loc, "integer constant must have integer type");
2608 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002609 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002610 return false;
2611 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002612 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002613 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2614 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002615
Chris Lattnerdf986172009-01-02 07:01:27 +00002616 // The lexer has no type info, so builds all float and double FP constants
2617 // as double. Fix this here. Long double does not need this.
2618 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002619 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002620 bool Ignored;
2621 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2622 &Ignored);
2623 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002624 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002625
Chris Lattner959873d2009-01-05 18:24:23 +00002626 if (V->getType() != Ty)
2627 return Error(ID.Loc, "floating point constant does not have type '" +
2628 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002629
Chris Lattnerdf986172009-01-02 07:01:27 +00002630 return false;
2631 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002632 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002633 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002634 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002635 return false;
2636 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002637 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002638 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002639 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002640 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002641 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002642 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002643 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002644 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002645 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002646 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002647 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002648 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002649 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002650 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002651 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002652 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002653 return false;
2654 case ValID::t_Constant:
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002655 if (ID.ConstantVal->getType() != Ty) {
2656 // Allow a constant struct with a single member to be converted
2657 // to a union, if the union has a member which is the same type
2658 // as the struct member.
2659 if (const UnionType* utype = dyn_cast<UnionType>(Ty)) {
2660 return ParseUnionValue(utype, ID, V);
2661 }
2662
Chris Lattnerdf986172009-01-02 07:01:27 +00002663 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002664 }
2665
Chris Lattnerdf986172009-01-02 07:01:27 +00002666 V = ID.ConstantVal;
2667 return false;
2668 }
2669}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002670
Chris Lattnerdf986172009-01-02 07:01:27 +00002671bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2672 V = 0;
2673 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002674 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002675 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002676}
2677
2678bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002679 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002680 return ParseType(T) ||
2681 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002682}
2683
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002684bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2685 PerFunctionState &PFS) {
2686 Value *V;
2687 Loc = Lex.getLoc();
2688 if (ParseTypeAndValue(V, PFS)) return true;
2689 if (!isa<BasicBlock>(V))
2690 return Error(Loc, "expected a basic block");
2691 BB = cast<BasicBlock>(V);
2692 return false;
2693}
2694
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002695bool LLParser::ParseUnionValue(const UnionType* utype, ValID &ID, Value *&V) {
2696 if (const StructType* stype = dyn_cast<StructType>(ID.ConstantVal->getType())) {
2697 if (stype->getNumContainedTypes() != 1)
2698 return Error(ID.Loc, "constant expression type mismatch");
2699 int index = utype->getElementTypeIndex(stype->getContainedType(0));
2700 if (index < 0)
2701 return Error(ID.Loc, "initializer type is not a member of the union");
2702
2703 V = ConstantUnion::get(
2704 utype, cast<Constant>(ID.ConstantVal->getOperand(0)));
2705 return false;
2706 }
2707
2708 return Error(ID.Loc, "constant expression type mismatch");
2709}
2710
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002711
Chris Lattnerdf986172009-01-02 07:01:27 +00002712/// FunctionHeader
2713/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2714/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2715/// OptionalAlign OptGC
2716bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2717 // Parse the linkage.
2718 LocTy LinkageLoc = Lex.getLoc();
2719 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002720
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002721 unsigned Visibility, RetAttrs;
2722 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002723 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002724 LocTy RetTypeLoc = Lex.getLoc();
2725 if (ParseOptionalLinkage(Linkage) ||
2726 ParseOptionalVisibility(Visibility) ||
2727 ParseOptionalCallingConv(CC) ||
2728 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002729 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002730 return true;
2731
2732 // Verify that the linkage is ok.
2733 switch ((GlobalValue::LinkageTypes)Linkage) {
2734 case GlobalValue::ExternalLinkage:
2735 break; // always ok.
2736 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002737 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002738 if (isDefine)
2739 return Error(LinkageLoc, "invalid linkage for function definition");
2740 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002741 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002742 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002743 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling55ae5152010-08-20 22:05:50 +00002744 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002745 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002746 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002747 case GlobalValue::LinkOnceAnyLinkage:
2748 case GlobalValue::LinkOnceODRLinkage:
2749 case GlobalValue::WeakAnyLinkage:
2750 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002751 case GlobalValue::DLLExportLinkage:
2752 if (!isDefine)
2753 return Error(LinkageLoc, "invalid linkage for function declaration");
2754 break;
2755 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002756 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002757 return Error(LinkageLoc, "invalid function linkage type");
2758 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002759
Chris Lattner99bb3152009-01-05 08:00:30 +00002760 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002761 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002762 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002763
Chris Lattnerdf986172009-01-02 07:01:27 +00002764 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002765
2766 std::string FunctionName;
2767 if (Lex.getKind() == lltok::GlobalVar) {
2768 FunctionName = Lex.getStrVal();
2769 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2770 unsigned NameID = Lex.getUIntVal();
2771
2772 if (NameID != NumberedVals.size())
2773 return TokError("function expected to be numbered '%" +
2774 utostr(NumberedVals.size()) + "'");
2775 } else {
2776 return TokError("expected function name");
2777 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002778
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002779 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002780
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002781 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002782 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002783
Chris Lattnerdf986172009-01-02 07:01:27 +00002784 std::vector<ArgInfo> ArgList;
2785 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002786 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002787 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002788 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002789 std::string GC;
2790
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002791 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002792 ParseOptionalAttrs(FuncAttrs, 2) ||
2793 (EatIfPresent(lltok::kw_section) &&
2794 ParseStringConstant(Section)) ||
2795 ParseOptionalAlignment(Alignment) ||
2796 (EatIfPresent(lltok::kw_gc) &&
2797 ParseStringConstant(GC)))
2798 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002799
2800 // If the alignment was parsed as an attribute, move to the alignment field.
2801 if (FuncAttrs & Attribute::Alignment) {
2802 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2803 FuncAttrs &= ~Attribute::Alignment;
2804 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002805
Chris Lattnerdf986172009-01-02 07:01:27 +00002806 // Okay, if we got here, the function is syntactically valid. Convert types
2807 // and do semantic checks.
2808 std::vector<const Type*> ParamTypeList;
2809 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002810 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002811 // attributes.
2812 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2813 if (FuncAttrs & ObsoleteFuncAttrs) {
2814 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2815 FuncAttrs &= ~ObsoleteFuncAttrs;
2816 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002817
Chris Lattnerdf986172009-01-02 07:01:27 +00002818 if (RetAttrs != Attribute::None)
2819 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002820
Chris Lattnerdf986172009-01-02 07:01:27 +00002821 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2822 ParamTypeList.push_back(ArgList[i].Type);
2823 if (ArgList[i].Attrs != Attribute::None)
2824 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2825 }
2826
2827 if (FuncAttrs != Attribute::None)
2828 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2829
2830 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002831
Benjamin Kramerf0127052010-01-05 13:12:22 +00002832 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002833 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2834
Owen Andersonfba933c2009-07-01 23:57:11 +00002835 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002836 FunctionType::get(RetType, ParamTypeList, isVarArg);
2837 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002838
2839 Fn = 0;
2840 if (!FunctionName.empty()) {
2841 // If this was a definition of a forward reference, remove the definition
2842 // from the forward reference table and fill in the forward ref.
2843 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2844 ForwardRefVals.find(FunctionName);
2845 if (FRVI != ForwardRefVals.end()) {
2846 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002847 if (Fn->getType() != PFT)
2848 return Error(FRVI->second.second, "invalid forward reference to "
2849 "function '" + FunctionName + "' with wrong type!");
2850
Chris Lattnerdf986172009-01-02 07:01:27 +00002851 ForwardRefVals.erase(FRVI);
2852 } else if ((Fn = M->getFunction(FunctionName))) {
2853 // If this function already exists in the symbol table, then it is
2854 // multiply defined. We accept a few cases for old backwards compat.
2855 // FIXME: Remove this stuff for LLVM 3.0.
2856 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2857 (!Fn->isDeclaration() && isDefine)) {
2858 // If the redefinition has different type or different attributes,
2859 // reject it. If both have bodies, reject it.
2860 return Error(NameLoc, "invalid redefinition of function '" +
2861 FunctionName + "'");
2862 } else if (Fn->isDeclaration()) {
2863 // Make sure to strip off any argument names so we can't get conflicts.
2864 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2865 AI != AE; ++AI)
2866 AI->setName("");
2867 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002868 } else if (M->getNamedValue(FunctionName)) {
2869 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002870 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002871
Dan Gohman41905542009-08-29 23:37:49 +00002872 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002873 // If this is a definition of a forward referenced function, make sure the
2874 // types agree.
2875 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2876 = ForwardRefValIDs.find(NumberedVals.size());
2877 if (I != ForwardRefValIDs.end()) {
2878 Fn = cast<Function>(I->second.first);
2879 if (Fn->getType() != PFT)
2880 return Error(NameLoc, "type of definition and forward reference of '@" +
2881 utostr(NumberedVals.size()) +"' disagree");
2882 ForwardRefValIDs.erase(I);
2883 }
2884 }
2885
2886 if (Fn == 0)
2887 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2888 else // Move the forward-reference to the correct spot in the module.
2889 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2890
2891 if (FunctionName.empty())
2892 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002893
Chris Lattnerdf986172009-01-02 07:01:27 +00002894 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2895 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2896 Fn->setCallingConv(CC);
2897 Fn->setAttributes(PAL);
2898 Fn->setAlignment(Alignment);
2899 Fn->setSection(Section);
2900 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002901
Chris Lattnerdf986172009-01-02 07:01:27 +00002902 // Add all of the arguments we parsed to the function.
2903 Function::arg_iterator ArgIt = Fn->arg_begin();
2904 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002905 // If we run out of arguments in the Function prototype, exit early.
2906 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2907 if (ArgIt == Fn->arg_end()) break;
2908
Chris Lattnerdf986172009-01-02 07:01:27 +00002909 // If the argument has a name, insert it into the argument symbol table.
2910 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002911
Chris Lattnerdf986172009-01-02 07:01:27 +00002912 // Set the name, if it conflicted, it will be auto-renamed.
2913 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002914
Chris Lattnerdf986172009-01-02 07:01:27 +00002915 if (ArgIt->getNameStr() != ArgList[i].Name)
2916 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2917 ArgList[i].Name + "'");
2918 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002919
Chris Lattnerdf986172009-01-02 07:01:27 +00002920 return false;
2921}
2922
2923
2924/// ParseFunctionBody
2925/// ::= '{' BasicBlock+ '}'
2926/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2927///
2928bool LLParser::ParseFunctionBody(Function &Fn) {
2929 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2930 return TokError("expected '{' in function body");
2931 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002932
Chris Lattner09d9ef42009-10-28 03:39:23 +00002933 int FunctionNumber = -1;
2934 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2935
2936 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002937
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002938 // We need at least one basic block.
2939 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2940 return TokError("function body requires at least one basic block");
2941
Chris Lattnerdf986172009-01-02 07:01:27 +00002942 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2943 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002944
Chris Lattnerdf986172009-01-02 07:01:27 +00002945 // Eat the }.
2946 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002947
Chris Lattnerdf986172009-01-02 07:01:27 +00002948 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002949 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002950}
2951
2952/// ParseBasicBlock
2953/// ::= LabelStr? Instruction*
2954bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2955 // If this basic block starts out with a name, remember it.
2956 std::string Name;
2957 LocTy NameLoc = Lex.getLoc();
2958 if (Lex.getKind() == lltok::LabelStr) {
2959 Name = Lex.getStrVal();
2960 Lex.Lex();
2961 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002962
Chris Lattnerdf986172009-01-02 07:01:27 +00002963 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2964 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002965
Chris Lattnerdf986172009-01-02 07:01:27 +00002966 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002967
Chris Lattnerdf986172009-01-02 07:01:27 +00002968 // Parse the instructions in this block until we get a terminator.
2969 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002970 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002971 do {
2972 // This instruction may have three possibilities for a name: a) none
2973 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2974 LocTy NameLoc = Lex.getLoc();
2975 int NameID = -1;
2976 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002977
Chris Lattnerdf986172009-01-02 07:01:27 +00002978 if (Lex.getKind() == lltok::LocalVarID) {
2979 NameID = Lex.getUIntVal();
2980 Lex.Lex();
2981 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2982 return true;
2983 } else if (Lex.getKind() == lltok::LocalVar ||
2984 // FIXME: REMOVE IN LLVM 3.0
2985 Lex.getKind() == lltok::StringConstant) {
2986 NameStr = Lex.getStrVal();
2987 Lex.Lex();
2988 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2989 return true;
2990 }
Devang Patelf633a062009-09-17 23:04:48 +00002991
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002992 switch (ParseInstruction(Inst, BB, PFS)) {
2993 default: assert(0 && "Unknown ParseInstruction result!");
2994 case InstError: return true;
2995 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002996 BB->getInstList().push_back(Inst);
2997
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002998 // With a normal result, we check to see if the instruction is followed by
2999 // a comma and metadata.
3000 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00003001 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003002 return true;
3003 break;
3004 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00003005 BB->getInstList().push_back(Inst);
3006
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003007 // If the instruction parser ate an extra comma at the end of it, it
3008 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00003009 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003010 return true;
3011 break;
3012 }
Devang Patelf633a062009-09-17 23:04:48 +00003013
Chris Lattnerdf986172009-01-02 07:01:27 +00003014 // Set the name on the instruction.
3015 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3016 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003017
Chris Lattnerdf986172009-01-02 07:01:27 +00003018 return false;
3019}
3020
3021//===----------------------------------------------------------------------===//
3022// Instruction Parsing.
3023//===----------------------------------------------------------------------===//
3024
3025/// ParseInstruction - Parse one of the many different instructions.
3026///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003027int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3028 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003029 lltok::Kind Token = Lex.getKind();
3030 if (Token == lltok::Eof)
3031 return TokError("found end of file when expecting more instructions");
3032 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003033 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00003034 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003035
Chris Lattnerdf986172009-01-02 07:01:27 +00003036 switch (Token) {
3037 default: return Error(Loc, "expected instruction opcode");
3038 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00003039 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
3040 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003041 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3042 case lltok::kw_br: return ParseBr(Inst, PFS);
3043 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00003044 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003045 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3046 // Binary Operators.
3047 case lltok::kw_add:
3048 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00003049 case lltok::kw_mul: {
3050 bool NUW = false;
3051 bool NSW = false;
3052 LocTy ModifierLoc = Lex.getLoc();
3053 if (EatIfPresent(lltok::kw_nuw))
3054 NUW = true;
3055 if (EatIfPresent(lltok::kw_nsw)) {
3056 NSW = true;
3057 if (EatIfPresent(lltok::kw_nuw))
3058 NUW = true;
3059 }
Dan Gohman1eaac532010-05-03 22:44:19 +00003060 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
Dan Gohman59858cf2009-07-27 16:11:46 +00003061 if (!Result) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003062 if (!Inst->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00003063 if (NUW)
3064 return Error(ModifierLoc, "nuw only applies to integer operations");
3065 if (NSW)
3066 return Error(ModifierLoc, "nsw only applies to integer operations");
3067 }
3068 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003069 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003070 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003071 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003072 }
3073 return Result;
3074 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003075 case lltok::kw_fadd:
3076 case lltok::kw_fsub:
3077 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3078
Dan Gohman59858cf2009-07-27 16:11:46 +00003079 case lltok::kw_sdiv: {
3080 bool Exact = false;
3081 if (EatIfPresent(lltok::kw_exact))
3082 Exact = true;
3083 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3084 if (!Result)
3085 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003086 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003087 return Result;
3088 }
3089
Chris Lattnerdf986172009-01-02 07:01:27 +00003090 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00003091 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003092 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00003093 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003094 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00003095 case lltok::kw_shl:
3096 case lltok::kw_lshr:
3097 case lltok::kw_ashr:
3098 case lltok::kw_and:
3099 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003100 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003101 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003102 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003103 // Casts.
3104 case lltok::kw_trunc:
3105 case lltok::kw_zext:
3106 case lltok::kw_sext:
3107 case lltok::kw_fptrunc:
3108 case lltok::kw_fpext:
3109 case lltok::kw_bitcast:
3110 case lltok::kw_uitofp:
3111 case lltok::kw_sitofp:
3112 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003113 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003114 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003115 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003116 // Other.
3117 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003118 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003119 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3120 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3121 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3122 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3123 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3124 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3125 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003126 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3127 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00003128 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003129 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3130 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3131 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003132 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00003133 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003134 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00003135 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003136 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003137 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003138 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3139 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3140 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3141 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3142 }
3143}
3144
3145/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3146bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003147 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003148 switch (Lex.getKind()) {
3149 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3150 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3151 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3152 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3153 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3154 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3155 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3156 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3157 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3158 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3159 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3160 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3161 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3162 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3163 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3164 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3165 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3166 }
3167 } else {
3168 switch (Lex.getKind()) {
3169 default: TokError("expected icmp predicate (e.g. 'eq')");
3170 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3171 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3172 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3173 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3174 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3175 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3176 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3177 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3178 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3179 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3180 }
3181 }
3182 Lex.Lex();
3183 return false;
3184}
3185
3186//===----------------------------------------------------------------------===//
3187// Terminator Instructions.
3188//===----------------------------------------------------------------------===//
3189
3190/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003191/// ::= 'ret' void (',' !dbg, !1)*
3192/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3193/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00003194/// [[obsolete: LLVM 3.0]]
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003195int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3196 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003197 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003198 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003199
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003200 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003201 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003202 return false;
3203 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003204
Chris Lattnerdf986172009-01-02 07:01:27 +00003205 Value *RV;
3206 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003207
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003208 bool ExtraComma = false;
Devang Patelf633a062009-09-17 23:04:48 +00003209 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003210 // Parse optional custom metadata, e.g. !dbg
Chris Lattner1d928312009-12-30 05:02:06 +00003211 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003212 ExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003213 } else {
3214 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003215 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3216 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003217 SmallVector<Value*, 8> RVs;
3218 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003219
Devang Patelf633a062009-09-17 23:04:48 +00003220 do {
Devang Patel0475c912009-09-29 00:01:14 +00003221 // If optional custom metadata, e.g. !dbg is seen then this is the
3222 // end of MRV.
Chris Lattner1d928312009-12-30 05:02:06 +00003223 if (Lex.getKind() == lltok::MetadataVar)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003224 break;
3225 if (ParseTypeAndValue(RV, PFS)) return true;
3226 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003227 } while (EatIfPresent(lltok::comma));
3228
3229 RV = UndefValue::get(PFS.getFunction().getReturnType());
3230 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003231 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3232 BB->getInstList().push_back(I);
3233 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003234 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003235 }
3236 }
Devang Patelf633a062009-09-17 23:04:48 +00003237
Owen Anderson1d0be152009-08-13 21:58:54 +00003238 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003239 return ExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003240}
3241
3242
3243/// ParseBr
3244/// ::= 'br' TypeAndValue
3245/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3246bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3247 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003248 Value *Op0;
3249 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003250 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003251
Chris Lattnerdf986172009-01-02 07:01:27 +00003252 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3253 Inst = BranchInst::Create(BB);
3254 return false;
3255 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003256
Owen Anderson1d0be152009-08-13 21:58:54 +00003257 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003258 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003259
Chris Lattnerdf986172009-01-02 07:01:27 +00003260 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003261 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003262 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003263 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003264 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003265
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003266 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003267 return false;
3268}
3269
3270/// ParseSwitch
3271/// Instruction
3272/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3273/// JumpTable
3274/// ::= (TypeAndValue ',' TypeAndValue)*
3275bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3276 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003277 Value *Cond;
3278 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003279 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3280 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003281 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003282 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3283 return true;
3284
Duncan Sands1df98592010-02-16 11:11:14 +00003285 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003286 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003287
Chris Lattnerdf986172009-01-02 07:01:27 +00003288 // Parse the jump table pairs.
3289 SmallPtrSet<Value*, 32> SeenCases;
3290 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3291 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003292 Value *Constant;
3293 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003294
Chris Lattnerdf986172009-01-02 07:01:27 +00003295 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3296 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003297 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003298 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003299
Chris Lattnerdf986172009-01-02 07:01:27 +00003300 if (!SeenCases.insert(Constant))
3301 return Error(CondLoc, "duplicate case value in switch");
3302 if (!isa<ConstantInt>(Constant))
3303 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003304
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003305 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003306 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003307
Chris Lattnerdf986172009-01-02 07:01:27 +00003308 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003309
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003310 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003311 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3312 SI->addCase(Table[i].first, Table[i].second);
3313 Inst = SI;
3314 return false;
3315}
3316
Chris Lattnerab21db72009-10-28 00:19:10 +00003317/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003318/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003319/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3320bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003321 LocTy AddrLoc;
3322 Value *Address;
3323 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003324 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3325 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003326 return true;
3327
Duncan Sands1df98592010-02-16 11:11:14 +00003328 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003329 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003330
3331 // Parse the destination list.
3332 SmallVector<BasicBlock*, 16> DestList;
3333
3334 if (Lex.getKind() != lltok::rsquare) {
3335 BasicBlock *DestBB;
3336 if (ParseTypeAndBasicBlock(DestBB, PFS))
3337 return true;
3338 DestList.push_back(DestBB);
3339
3340 while (EatIfPresent(lltok::comma)) {
3341 if (ParseTypeAndBasicBlock(DestBB, PFS))
3342 return true;
3343 DestList.push_back(DestBB);
3344 }
3345 }
3346
3347 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3348 return true;
3349
Chris Lattnerab21db72009-10-28 00:19:10 +00003350 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003351 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3352 IBI->addDestination(DestList[i]);
3353 Inst = IBI;
3354 return false;
3355}
3356
3357
Chris Lattnerdf986172009-01-02 07:01:27 +00003358/// ParseInvoke
3359/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3360/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3361bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3362 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003363 unsigned RetAttrs, FnAttrs;
3364 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003365 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003366 LocTy RetTypeLoc;
3367 ValID CalleeID;
3368 SmallVector<ParamInfo, 16> ArgList;
3369
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003370 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003371 if (ParseOptionalCallingConv(CC) ||
3372 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003373 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003374 ParseValID(CalleeID) ||
3375 ParseParameterList(ArgList, PFS) ||
3376 ParseOptionalAttrs(FnAttrs, 2) ||
3377 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003378 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003379 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003380 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003381 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003382
Chris Lattnerdf986172009-01-02 07:01:27 +00003383 // If RetType is a non-function pointer type, then this is the short syntax
3384 // for the call, which means that RetType is just the return type. Infer the
3385 // rest of the function argument types from the arguments that are present.
3386 const PointerType *PFTy = 0;
3387 const FunctionType *Ty = 0;
3388 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3389 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3390 // Pull out the types of all of the arguments...
3391 std::vector<const Type*> ParamTypes;
3392 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3393 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003394
Chris Lattnerdf986172009-01-02 07:01:27 +00003395 if (!FunctionType::isValidReturnType(RetType))
3396 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003397
Owen Andersondebcb012009-07-29 22:17:13 +00003398 Ty = FunctionType::get(RetType, ParamTypes, false);
3399 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003400 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003401
Chris Lattnerdf986172009-01-02 07:01:27 +00003402 // Look up the callee.
3403 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003404 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003405
Chris Lattnerdf986172009-01-02 07:01:27 +00003406 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3407 // function attributes.
3408 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3409 if (FnAttrs & ObsoleteFuncAttrs) {
3410 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3411 FnAttrs &= ~ObsoleteFuncAttrs;
3412 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003413
Chris Lattnerdf986172009-01-02 07:01:27 +00003414 // Set up the Attributes for the function.
3415 SmallVector<AttributeWithIndex, 8> Attrs;
3416 if (RetAttrs != Attribute::None)
3417 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003418
Chris Lattnerdf986172009-01-02 07:01:27 +00003419 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003420
Chris Lattnerdf986172009-01-02 07:01:27 +00003421 // Loop through FunctionType's arguments and ensure they are specified
3422 // correctly. Also, gather any parameter attributes.
3423 FunctionType::param_iterator I = Ty->param_begin();
3424 FunctionType::param_iterator E = Ty->param_end();
3425 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3426 const Type *ExpectedTy = 0;
3427 if (I != E) {
3428 ExpectedTy = *I++;
3429 } else if (!Ty->isVarArg()) {
3430 return Error(ArgList[i].Loc, "too many arguments specified");
3431 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003432
Chris Lattnerdf986172009-01-02 07:01:27 +00003433 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3434 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3435 ExpectedTy->getDescription() + "'");
3436 Args.push_back(ArgList[i].V);
3437 if (ArgList[i].Attrs != Attribute::None)
3438 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3439 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003440
Chris Lattnerdf986172009-01-02 07:01:27 +00003441 if (I != E)
3442 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003443
Chris Lattnerdf986172009-01-02 07:01:27 +00003444 if (FnAttrs != Attribute::None)
3445 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003446
Chris Lattnerdf986172009-01-02 07:01:27 +00003447 // Finish off the Attributes and check them
3448 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003449
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003450 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003451 Args.begin(), Args.end());
3452 II->setCallingConv(CC);
3453 II->setAttributes(PAL);
3454 Inst = II;
3455 return false;
3456}
3457
3458
3459
3460//===----------------------------------------------------------------------===//
3461// Binary Operators.
3462//===----------------------------------------------------------------------===//
3463
3464/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003465/// ::= ArithmeticOps TypeAndValue ',' Value
3466///
3467/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3468/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003469bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003470 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003471 LocTy Loc; Value *LHS, *RHS;
3472 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3473 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3474 ParseValue(LHS->getType(), RHS, PFS))
3475 return true;
3476
Chris Lattnere914b592009-01-05 08:24:46 +00003477 bool Valid;
3478 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003479 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003480 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003481 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3482 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003483 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003484 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3485 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003486 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003487
Chris Lattnere914b592009-01-05 08:24:46 +00003488 if (!Valid)
3489 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003490
Chris Lattnerdf986172009-01-02 07:01:27 +00003491 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3492 return false;
3493}
3494
3495/// ParseLogical
3496/// ::= ArithmeticOps TypeAndValue ',' Value {
3497bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3498 unsigned Opc) {
3499 LocTy Loc; Value *LHS, *RHS;
3500 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3501 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3502 ParseValue(LHS->getType(), RHS, PFS))
3503 return true;
3504
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003505 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003506 return Error(Loc,"instruction requires integer or integer vector operands");
3507
3508 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3509 return false;
3510}
3511
3512
3513/// ParseCompare
3514/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3515/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003516bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3517 unsigned Opc) {
3518 // Parse the integer/fp comparison predicate.
3519 LocTy Loc;
3520 unsigned Pred;
3521 Value *LHS, *RHS;
3522 if (ParseCmpPredicate(Pred, Opc) ||
3523 ParseTypeAndValue(LHS, Loc, PFS) ||
3524 ParseToken(lltok::comma, "expected ',' after compare value") ||
3525 ParseValue(LHS->getType(), RHS, PFS))
3526 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003527
Chris Lattnerdf986172009-01-02 07:01:27 +00003528 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003529 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003530 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003531 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003532 } else {
3533 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003534 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003535 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003536 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003537 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003538 }
3539 return false;
3540}
3541
3542//===----------------------------------------------------------------------===//
3543// Other Instructions.
3544//===----------------------------------------------------------------------===//
3545
3546
3547/// ParseCast
3548/// ::= CastOpc TypeAndValue 'to' Type
3549bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3550 unsigned Opc) {
3551 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003552 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003553 if (ParseTypeAndValue(Op, Loc, PFS) ||
3554 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3555 ParseType(DestTy))
3556 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003557
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003558 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3559 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003560 return Error(Loc, "invalid cast opcode for cast from '" +
3561 Op->getType()->getDescription() + "' to '" +
3562 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003563 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003564 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3565 return false;
3566}
3567
3568/// ParseSelect
3569/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3570bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3571 LocTy Loc;
3572 Value *Op0, *Op1, *Op2;
3573 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3574 ParseToken(lltok::comma, "expected ',' after select condition") ||
3575 ParseTypeAndValue(Op1, PFS) ||
3576 ParseToken(lltok::comma, "expected ',' after select value") ||
3577 ParseTypeAndValue(Op2, PFS))
3578 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003579
Chris Lattnerdf986172009-01-02 07:01:27 +00003580 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3581 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003582
Chris Lattnerdf986172009-01-02 07:01:27 +00003583 Inst = SelectInst::Create(Op0, Op1, Op2);
3584 return false;
3585}
3586
Chris Lattner0088a5c2009-01-05 08:18:44 +00003587/// ParseVA_Arg
3588/// ::= 'va_arg' TypeAndValue ',' Type
3589bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003590 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003591 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003592 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003593 if (ParseTypeAndValue(Op, PFS) ||
3594 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003595 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003596 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003597
Chris Lattner0088a5c2009-01-05 08:18:44 +00003598 if (!EltTy->isFirstClassType())
3599 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003600
3601 Inst = new VAArgInst(Op, EltTy);
3602 return false;
3603}
3604
3605/// ParseExtractElement
3606/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3607bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3608 LocTy Loc;
3609 Value *Op0, *Op1;
3610 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3611 ParseToken(lltok::comma, "expected ',' after extract value") ||
3612 ParseTypeAndValue(Op1, PFS))
3613 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003614
Chris Lattnerdf986172009-01-02 07:01:27 +00003615 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3616 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003617
Eric Christophera3500da2009-07-25 02:28:41 +00003618 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003619 return false;
3620}
3621
3622/// ParseInsertElement
3623/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3624bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3625 LocTy Loc;
3626 Value *Op0, *Op1, *Op2;
3627 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3628 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3629 ParseTypeAndValue(Op1, PFS) ||
3630 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3631 ParseTypeAndValue(Op2, PFS))
3632 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003633
Chris Lattnerdf986172009-01-02 07:01:27 +00003634 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003635 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003636
Chris Lattnerdf986172009-01-02 07:01:27 +00003637 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3638 return false;
3639}
3640
3641/// ParseShuffleVector
3642/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3643bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3644 LocTy Loc;
3645 Value *Op0, *Op1, *Op2;
3646 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3647 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3648 ParseTypeAndValue(Op1, PFS) ||
3649 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3650 ParseTypeAndValue(Op2, PFS))
3651 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003652
Chris Lattnerdf986172009-01-02 07:01:27 +00003653 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3654 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003655
Chris Lattnerdf986172009-01-02 07:01:27 +00003656 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3657 return false;
3658}
3659
3660/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003661/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003662int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003663 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003664 Value *Op0, *Op1;
3665 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003666
Chris Lattnerdf986172009-01-02 07:01:27 +00003667 if (ParseType(Ty) ||
3668 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3669 ParseValue(Ty, Op0, PFS) ||
3670 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003671 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003672 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3673 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003674
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003675 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003676 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3677 while (1) {
3678 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003679
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003680 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003681 break;
3682
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003683 if (Lex.getKind() == lltok::MetadataVar) {
3684 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003685 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003686 }
Devang Patela43d46f2009-10-16 18:45:49 +00003687
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003688 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003689 ParseValue(Ty, Op0, PFS) ||
3690 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003691 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003692 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3693 return true;
3694 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003695
Chris Lattnerdf986172009-01-02 07:01:27 +00003696 if (!Ty->isFirstClassType())
3697 return Error(TypeLoc, "phi node must have first class type");
3698
3699 PHINode *PN = PHINode::Create(Ty);
3700 PN->reserveOperandSpace(PHIVals.size());
3701 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3702 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3703 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003704 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003705}
3706
3707/// ParseCall
3708/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3709/// ParameterList OptionalAttrs
3710bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3711 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003712 unsigned RetAttrs, FnAttrs;
3713 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003714 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003715 LocTy RetTypeLoc;
3716 ValID CalleeID;
3717 SmallVector<ParamInfo, 16> ArgList;
3718 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003719
Chris Lattnerdf986172009-01-02 07:01:27 +00003720 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3721 ParseOptionalCallingConv(CC) ||
3722 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003723 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003724 ParseValID(CalleeID) ||
3725 ParseParameterList(ArgList, PFS) ||
3726 ParseOptionalAttrs(FnAttrs, 2))
3727 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003728
Chris Lattnerdf986172009-01-02 07:01:27 +00003729 // If RetType is a non-function pointer type, then this is the short syntax
3730 // for the call, which means that RetType is just the return type. Infer the
3731 // rest of the function argument types from the arguments that are present.
3732 const PointerType *PFTy = 0;
3733 const FunctionType *Ty = 0;
3734 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3735 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3736 // Pull out the types of all of the arguments...
3737 std::vector<const Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003738 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3739 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003740
Chris Lattnerdf986172009-01-02 07:01:27 +00003741 if (!FunctionType::isValidReturnType(RetType))
3742 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003743
Owen Andersondebcb012009-07-29 22:17:13 +00003744 Ty = FunctionType::get(RetType, ParamTypes, false);
3745 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003746 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003747
Chris Lattnerdf986172009-01-02 07:01:27 +00003748 // Look up the callee.
3749 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003750 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003751
Chris Lattnerdf986172009-01-02 07:01:27 +00003752 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3753 // function attributes.
3754 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3755 if (FnAttrs & ObsoleteFuncAttrs) {
3756 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3757 FnAttrs &= ~ObsoleteFuncAttrs;
3758 }
3759
3760 // Set up the Attributes for the function.
3761 SmallVector<AttributeWithIndex, 8> Attrs;
3762 if (RetAttrs != Attribute::None)
3763 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003764
Chris Lattnerdf986172009-01-02 07:01:27 +00003765 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003766
Chris Lattnerdf986172009-01-02 07:01:27 +00003767 // Loop through FunctionType's arguments and ensure they are specified
3768 // correctly. Also, gather any parameter attributes.
3769 FunctionType::param_iterator I = Ty->param_begin();
3770 FunctionType::param_iterator E = Ty->param_end();
3771 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3772 const Type *ExpectedTy = 0;
3773 if (I != E) {
3774 ExpectedTy = *I++;
3775 } else if (!Ty->isVarArg()) {
3776 return Error(ArgList[i].Loc, "too many arguments specified");
3777 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003778
Chris Lattnerdf986172009-01-02 07:01:27 +00003779 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3780 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3781 ExpectedTy->getDescription() + "'");
3782 Args.push_back(ArgList[i].V);
3783 if (ArgList[i].Attrs != Attribute::None)
3784 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3785 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003786
Chris Lattnerdf986172009-01-02 07:01:27 +00003787 if (I != E)
3788 return Error(CallLoc, "not enough parameters specified for call");
3789
3790 if (FnAttrs != Attribute::None)
3791 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3792
3793 // Finish off the Attributes and check them
3794 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003795
Chris Lattnerdf986172009-01-02 07:01:27 +00003796 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3797 CI->setTailCall(isTail);
3798 CI->setCallingConv(CC);
3799 CI->setAttributes(PAL);
3800 Inst = CI;
3801 return false;
3802}
3803
3804//===----------------------------------------------------------------------===//
3805// Memory Instructions.
3806//===----------------------------------------------------------------------===//
3807
3808/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003809/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3810/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003811int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3812 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003813 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003814 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003815 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003816 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003817 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003818
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003819 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003820 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003821 if (Lex.getKind() == lltok::kw_align) {
3822 if (ParseOptionalAlignment(Alignment)) return true;
3823 } else if (Lex.getKind() == lltok::MetadataVar) {
3824 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003825 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003826 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3827 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3828 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003829 }
3830 }
3831
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003832 if (Size && !Size->getType()->isIntegerTy())
3833 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003834
Victor Hernandez68afa542009-10-21 19:11:40 +00003835 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003836 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003837 return AteExtraComma ? InstExtraComma : InstNormal;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003838 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003839
3840 // Autoupgrade old malloc instruction to malloc call.
3841 // FIXME: Remove in LLVM 3.0.
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003842 if (Size && !Size->getType()->isIntegerTy(32))
3843 return Error(SizeLoc, "element count must be i32");
Victor Hernandez68afa542009-10-21 19:11:40 +00003844 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003845 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3846 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
Victor Hernandez68afa542009-10-21 19:11:40 +00003847 if (!MallocF)
3848 // Prototype malloc as "void *(int32)".
3849 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003850 MallocF = cast<Function>(
3851 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003852 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003853return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003854}
3855
3856/// ParseFree
3857/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003858bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3859 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003860 Value *Val; LocTy Loc;
3861 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003862 if (!Val->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003863 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003864 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003865 return false;
3866}
3867
3868/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003869/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003870int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3871 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003872 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003873 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003874 bool AteExtraComma = false;
3875 if (ParseTypeAndValue(Val, Loc, PFS) ||
3876 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3877 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003878
Duncan Sands1df98592010-02-16 11:11:14 +00003879 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003880 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3881 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003882
Chris Lattnerdf986172009-01-02 07:01:27 +00003883 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003884 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003885}
3886
3887/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003888/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003889int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3890 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003891 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003892 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003893 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003894 if (ParseTypeAndValue(Val, Loc, PFS) ||
3895 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003896 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3897 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003898 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003899
Duncan Sands1df98592010-02-16 11:11:14 +00003900 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003901 return Error(PtrLoc, "store operand must be a pointer");
3902 if (!Val->getType()->isFirstClassType())
3903 return Error(Loc, "store operand must be a first class value");
3904 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3905 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003906
Chris Lattnerdf986172009-01-02 07:01:27 +00003907 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003908 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003909}
3910
3911/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003912/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003913/// FIXME: Remove support for getresult in LLVM 3.0
3914bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3915 Value *Val; LocTy ValLoc, EltLoc;
3916 unsigned Element;
3917 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3918 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003919 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003920 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003921
Duncan Sands1df98592010-02-16 11:11:14 +00003922 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003923 return Error(ValLoc, "getresult inst requires an aggregate operand");
3924 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3925 return Error(EltLoc, "invalid getresult index for value");
3926 Inst = ExtractValueInst::Create(Val, Element);
3927 return false;
3928}
3929
3930/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003931/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003932int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003933 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003934
Dan Gohmandcb40a32009-07-29 15:58:36 +00003935 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003936
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003937 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003938
Duncan Sands1df98592010-02-16 11:11:14 +00003939 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003940 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003941
Chris Lattnerdf986172009-01-02 07:01:27 +00003942 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003943 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003944 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003945 if (Lex.getKind() == lltok::MetadataVar) {
3946 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003947 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003948 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003949 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003950 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003951 return Error(EltLoc, "getelementptr index must be an integer");
3952 Indices.push_back(Val);
3953 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003954
Chris Lattnerdf986172009-01-02 07:01:27 +00003955 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3956 Indices.begin(), Indices.end()))
3957 return Error(Loc, "invalid getelementptr indices");
3958 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003959 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003960 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003961 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003962}
3963
3964/// ParseExtractValue
3965/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003966int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003967 Value *Val; LocTy Loc;
3968 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003969 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003970 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003971 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003972 return true;
3973
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003974 if (!Val->getType()->isAggregateType())
3975 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003976
3977 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3978 Indices.end()))
3979 return Error(Loc, "invalid indices for extractvalue");
3980 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003981 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003982}
3983
3984/// ParseInsertValue
3985/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003986int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003987 Value *Val0, *Val1; LocTy Loc0, Loc1;
3988 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003989 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003990 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3991 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3992 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003993 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003994 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003995
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003996 if (!Val0->getType()->isAggregateType())
3997 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003998
Chris Lattnerdf986172009-01-02 07:01:27 +00003999 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
4000 Indices.end()))
4001 return Error(Loc0, "invalid indices for insertvalue");
4002 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004003 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004004}
Nick Lewycky21cc4462009-04-04 07:22:01 +00004005
4006//===----------------------------------------------------------------------===//
4007// Embedded metadata.
4008//===----------------------------------------------------------------------===//
4009
4010/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00004011/// ::= Element (',' Element)*
4012/// Element
4013/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00004014bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00004015 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00004016 // Check for an empty list.
4017 if (Lex.getKind() == lltok::rbrace)
4018 return false;
4019
Nick Lewycky21cc4462009-04-04 07:22:01 +00004020 do {
Chris Lattnera7352392009-12-30 04:42:57 +00004021 // Null is a special case since it is typeless.
4022 if (EatIfPresent(lltok::kw_null)) {
4023 Elts.push_back(0);
4024 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00004025 }
Chris Lattnera7352392009-12-30 04:42:57 +00004026
4027 Value *V = 0;
4028 PATypeHolder Ty(Type::getVoidTy(Context));
4029 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00004030 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00004031 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00004032 return true;
4033
Nick Lewyckycb337992009-05-10 20:57:05 +00004034 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00004035 } while (EatIfPresent(lltok::comma));
4036
4037 return false;
4038}