blob: 3a9c47c8f51f97a2847c32859b33a11cabeb653f [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'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001087/// ::= 'ptx_kernel'
1088/// ::= 'ptx_device'
Chris Lattnerdf986172009-01-02 07:01:27 +00001089/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001090///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001091bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001092 switch (Lex.getKind()) {
1093 default: CC = CallingConv::C; return false;
1094 case lltok::kw_ccc: CC = CallingConv::C; break;
1095 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1096 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1097 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1098 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001099 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001100 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1101 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1102 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001103 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001104 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1105 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001106 case lltok::kw_cc: {
1107 unsigned ArbitraryCC;
1108 Lex.Lex();
1109 if (ParseUInt32(ArbitraryCC)) {
1110 return true;
1111 } else
1112 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1113 return false;
1114 }
1115 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001116 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001117
Chris Lattnerdf986172009-01-02 07:01:27 +00001118 Lex.Lex();
1119 return false;
1120}
1121
Chris Lattnerb8c46862009-12-30 05:31:19 +00001122/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001123/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001124bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1125 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001126 do {
1127 if (Lex.getKind() != lltok::MetadataVar)
1128 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001129
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001130 std::string Name = Lex.getStrVal();
Dan Gohman309b3af2010-08-24 02:24:03 +00001131 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001132 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001133
Chris Lattner442ffa12009-12-29 21:53:55 +00001134 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001135 unsigned NodeID;
1136 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001137
1138 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001139 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001140
Dan Gohman68261142010-08-24 14:35:45 +00001141 // This code is similar to that of ParseMetadataValue, however it needs to
1142 // have special-case code for a forward reference; see the comments on
1143 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1144 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001145 if (Lex.getKind() == lltok::lbrace) {
1146 ValID ID;
1147 if (ParseMetadataListValue(ID, PFS))
1148 return true;
1149 assert(ID.Kind == ValID::t_MDNode);
1150 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001151 } else {
Dan Gohman309b3af2010-08-24 02:24:03 +00001152 if (ParseMDNodeID(Node, NodeID))
1153 return true;
1154 if (Node) {
1155 // If we got the node, add it to the instruction.
1156 Inst->setMetadata(MDK, Node);
1157 } else {
1158 MDRef R = { Loc, MDK, NodeID };
1159 // Otherwise, remember that this should be resolved later.
1160 ForwardRefInstMetadata[Inst].push_back(R);
1161 }
Chris Lattner449c3102010-04-01 05:14:45 +00001162 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001163
1164 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001165 } while (EatIfPresent(lltok::comma));
1166 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001167}
1168
Chris Lattnerdf986172009-01-02 07:01:27 +00001169/// ParseOptionalAlignment
1170/// ::= /* empty */
1171/// ::= 'align' 4
1172bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1173 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001174 if (!EatIfPresent(lltok::kw_align))
1175 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001176 LocTy AlignLoc = Lex.getLoc();
1177 if (ParseUInt32(Alignment)) return true;
1178 if (!isPowerOf2_32(Alignment))
1179 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001180 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001181 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001182 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001183}
1184
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001185/// ParseOptionalCommaAlign
1186/// ::=
1187/// ::= ',' align 4
1188///
1189/// This returns with AteExtraComma set to true if it ate an excess comma at the
1190/// end.
1191bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1192 bool &AteExtraComma) {
1193 AteExtraComma = false;
1194 while (EatIfPresent(lltok::comma)) {
1195 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001196 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001197 AteExtraComma = true;
1198 return false;
1199 }
1200
Chris Lattner093eed12010-04-23 00:50:50 +00001201 if (Lex.getKind() != lltok::kw_align)
1202 return Error(Lex.getLoc(), "expected metadata or 'align'");
1203
Dan Gohman138aa2a2010-07-28 20:12:04 +00001204 LocTy AlignLoc = Lex.getLoc();
Chris Lattner093eed12010-04-23 00:50:50 +00001205 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001206 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001207
Devang Patelf633a062009-09-17 23:04:48 +00001208 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001209}
1210
Charles Davis1e063d12010-02-12 00:31:15 +00001211/// ParseOptionalStackAlignment
1212/// ::= /* empty */
1213/// ::= 'alignstack' '(' 4 ')'
1214bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1215 Alignment = 0;
1216 if (!EatIfPresent(lltok::kw_alignstack))
1217 return false;
1218 LocTy ParenLoc = Lex.getLoc();
1219 if (!EatIfPresent(lltok::lparen))
1220 return Error(ParenLoc, "expected '('");
1221 LocTy AlignLoc = Lex.getLoc();
1222 if (ParseUInt32(Alignment)) return true;
1223 ParenLoc = Lex.getLoc();
1224 if (!EatIfPresent(lltok::rparen))
1225 return Error(ParenLoc, "expected ')'");
1226 if (!isPowerOf2_32(Alignment))
1227 return Error(AlignLoc, "stack alignment is not a power of two");
1228 return false;
1229}
Devang Patelf633a062009-09-17 23:04:48 +00001230
Chris Lattner628c13a2009-12-30 05:14:00 +00001231/// ParseIndexList - This parses the index list for an insert/extractvalue
1232/// instruction. This sets AteExtraComma in the case where we eat an extra
1233/// comma at the end of the line and find that it is followed by metadata.
1234/// Clients that don't allow metadata can call the version of this function that
1235/// only takes one argument.
1236///
Chris Lattnerdf986172009-01-02 07:01:27 +00001237/// ParseIndexList
1238/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001239///
1240bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1241 bool &AteExtraComma) {
1242 AteExtraComma = false;
1243
Chris Lattnerdf986172009-01-02 07:01:27 +00001244 if (Lex.getKind() != lltok::comma)
1245 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001246
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001247 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001248 if (Lex.getKind() == lltok::MetadataVar) {
1249 AteExtraComma = true;
1250 return false;
1251 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001252 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001253 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001254 Indices.push_back(Idx);
1255 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001256
Chris Lattnerdf986172009-01-02 07:01:27 +00001257 return false;
1258}
1259
1260//===----------------------------------------------------------------------===//
1261// Type Parsing.
1262//===----------------------------------------------------------------------===//
1263
1264/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001265bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1266 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001267 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001268
Chris Lattnerdf986172009-01-02 07:01:27 +00001269 // Verify no unresolved uprefs.
1270 if (!UpRefs.empty())
1271 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001272
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001273 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001274 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001275
Chris Lattnerdf986172009-01-02 07:01:27 +00001276 return false;
1277}
1278
1279/// HandleUpRefs - Every time we finish a new layer of types, this function is
1280/// called. It loops through the UpRefs vector, which is a list of the
1281/// currently active types. For each type, if the up-reference is contained in
1282/// the newly completed type, we decrement the level count. When the level
1283/// count reaches zero, the up-referenced type is the type that is passed in:
1284/// thus we can complete the cycle.
1285///
1286PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1287 // If Ty isn't abstract, or if there are no up-references in it, then there is
1288 // nothing to resolve here.
1289 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001290
Chris Lattnerdf986172009-01-02 07:01:27 +00001291 PATypeHolder Ty(ty);
1292#if 0
David Greene0e28d762009-12-23 23:38:28 +00001293 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001294 << "' newly formed. Resolving upreferences.\n"
1295 << UpRefs.size() << " upreferences active!\n";
1296#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001297
Chris Lattnerdf986172009-01-02 07:01:27 +00001298 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1299 // to zero), we resolve them all together before we resolve them to Ty. At
1300 // the end of the loop, if there is anything to resolve to Ty, it will be in
1301 // this variable.
1302 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001303
Chris Lattnerdf986172009-01-02 07:01:27 +00001304 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1305 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1306 bool ContainsType =
1307 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1308 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001309
Chris Lattnerdf986172009-01-02 07:01:27 +00001310#if 0
David Greene0e28d762009-12-23 23:38:28 +00001311 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001312 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1313 << (ContainsType ? "true" : "false")
1314 << " level=" << UpRefs[i].NestingLevel << "\n";
1315#endif
1316 if (!ContainsType)
1317 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001318
Chris Lattnerdf986172009-01-02 07:01:27 +00001319 // Decrement level of upreference
1320 unsigned Level = --UpRefs[i].NestingLevel;
1321 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001322
Chris Lattnerdf986172009-01-02 07:01:27 +00001323 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1324 if (Level != 0)
1325 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001326
Chris Lattnerdf986172009-01-02 07:01:27 +00001327#if 0
David Greene0e28d762009-12-23 23:38:28 +00001328 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001329#endif
1330 if (!TypeToResolve)
1331 TypeToResolve = UpRefs[i].UpRefTy;
1332 else
1333 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1334 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1335 --i; // Do not skip the next element.
1336 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001337
Chris Lattnerdf986172009-01-02 07:01:27 +00001338 if (TypeToResolve)
1339 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001340
Chris Lattnerdf986172009-01-02 07:01:27 +00001341 return Ty;
1342}
1343
1344
1345/// ParseTypeRec - The recursive function used to process the internal
1346/// implementation details of types.
1347bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1348 switch (Lex.getKind()) {
1349 default:
1350 return TokError("expected type");
1351 case lltok::Type:
1352 // TypeRec ::= 'float' | 'void' (etc)
1353 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001354 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001355 break;
1356 case lltok::kw_opaque:
1357 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001358 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001359 Lex.Lex();
1360 break;
1361 case lltok::lbrace:
1362 // TypeRec ::= '{' ... '}'
1363 if (ParseStructType(Result, false))
1364 return true;
1365 break;
1366 case lltok::lsquare:
1367 // TypeRec ::= '[' ... ']'
1368 Lex.Lex(); // eat the lsquare.
1369 if (ParseArrayVectorType(Result, false))
1370 return true;
1371 break;
1372 case lltok::less: // Either vector or packed struct.
1373 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001374 Lex.Lex();
1375 if (Lex.getKind() == lltok::lbrace) {
1376 if (ParseStructType(Result, true) ||
1377 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001378 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001379 } else if (ParseArrayVectorType(Result, true))
1380 return true;
1381 break;
1382 case lltok::LocalVar:
1383 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1384 // TypeRec ::= %foo
1385 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1386 Result = T;
1387 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001388 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001389 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1390 std::make_pair(Result,
1391 Lex.getLoc())));
1392 M->addTypeName(Lex.getStrVal(), Result.get());
1393 }
1394 Lex.Lex();
1395 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001396
Chris Lattnerdf986172009-01-02 07:01:27 +00001397 case lltok::LocalVarID:
1398 // TypeRec ::= %4
1399 if (Lex.getUIntVal() < NumberedTypes.size())
1400 Result = NumberedTypes[Lex.getUIntVal()];
1401 else {
1402 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1403 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1404 if (I != ForwardRefTypeIDs.end())
1405 Result = I->second.first;
1406 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001407 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001408 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1409 std::make_pair(Result,
1410 Lex.getLoc())));
1411 }
1412 }
1413 Lex.Lex();
1414 break;
1415 case lltok::backslash: {
1416 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001417 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001418 unsigned Val;
1419 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001420 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001421 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1422 Result = OT;
1423 break;
1424 }
1425 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001426
1427 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001428 while (1) {
1429 switch (Lex.getKind()) {
1430 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001431 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001432
1433 // TypeRec ::= TypeRec '*'
1434 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001435 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001436 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001437 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001438 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001439 if (!PointerType::isValidElementType(Result.get()))
1440 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001441 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001442 Lex.Lex();
1443 break;
1444
1445 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1446 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001447 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001448 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001449 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001450 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001451 if (!PointerType::isValidElementType(Result.get()))
1452 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001453 unsigned AddrSpace;
1454 if (ParseOptionalAddrSpace(AddrSpace) ||
1455 ParseToken(lltok::star, "expected '*' in address space"))
1456 return true;
1457
Owen Andersondebcb012009-07-29 22:17:13 +00001458 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001459 break;
1460 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001461
Chris Lattnerdf986172009-01-02 07:01:27 +00001462 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1463 case lltok::lparen:
1464 if (ParseFunctionType(Result))
1465 return true;
1466 break;
1467 }
1468 }
1469}
1470
1471/// ParseParameterList
1472/// ::= '(' ')'
1473/// ::= '(' Arg (',' Arg)* ')'
1474/// Arg
1475/// ::= Type OptionalAttributes Value OptionalAttributes
1476bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1477 PerFunctionState &PFS) {
1478 if (ParseToken(lltok::lparen, "expected '(' in call"))
1479 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001480
Chris Lattnerdf986172009-01-02 07:01:27 +00001481 while (Lex.getKind() != lltok::rparen) {
1482 // If this isn't the first argument, we need a comma.
1483 if (!ArgList.empty() &&
1484 ParseToken(lltok::comma, "expected ',' in argument list"))
1485 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001486
Chris Lattnerdf986172009-01-02 07:01:27 +00001487 // Parse the argument.
1488 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001489 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001490 unsigned ArgAttrs1 = Attribute::None;
1491 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001492 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001493 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001494 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001495
Chris Lattner287881d2009-12-30 02:11:14 +00001496 // Otherwise, handle normal operands.
1497 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1498 ParseValue(ArgTy, V, PFS) ||
1499 // FIXME: Should not allow attributes after the argument, remove this
1500 // in LLVM 3.0.
1501 ParseOptionalAttrs(ArgAttrs2, 3))
1502 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001503 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1504 }
1505
1506 Lex.Lex(); // Lex the ')'.
1507 return false;
1508}
1509
1510
1511
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001512/// ParseArgumentList - Parse the argument list for a function type or function
1513/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001514/// ::= '(' ArgTypeListI ')'
1515/// ArgTypeListI
1516/// ::= /*empty*/
1517/// ::= '...'
1518/// ::= ArgTypeList ',' '...'
1519/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001520///
Chris Lattnerdf986172009-01-02 07:01:27 +00001521bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001522 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001523 isVarArg = false;
1524 assert(Lex.getKind() == lltok::lparen);
1525 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001526
Chris Lattnerdf986172009-01-02 07:01:27 +00001527 if (Lex.getKind() == lltok::rparen) {
1528 // empty
1529 } else if (Lex.getKind() == lltok::dotdotdot) {
1530 isVarArg = true;
1531 Lex.Lex();
1532 } else {
1533 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001534 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001535 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001536 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001537
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001538 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1539 // types (such as a function returning a pointer to itself). If parsing a
1540 // function prototype, we require fully resolved types.
1541 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001542 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001543
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001544 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001545 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001546
Chris Lattnerdf986172009-01-02 07:01:27 +00001547 if (Lex.getKind() == lltok::LocalVar ||
1548 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1549 Name = Lex.getStrVal();
1550 Lex.Lex();
1551 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001552
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001553 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001554 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001555
Chris Lattnerdf986172009-01-02 07:01:27 +00001556 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001557
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001558 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001559 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001560 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001561 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001562 break;
1563 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001564
Chris Lattnerdf986172009-01-02 07:01:27 +00001565 // Otherwise must be an argument type.
1566 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001567 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001568 ParseOptionalAttrs(Attrs, 0)) return true;
1569
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001570 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001571 return Error(TypeLoc, "argument can not have void type");
1572
Chris Lattnerdf986172009-01-02 07:01:27 +00001573 if (Lex.getKind() == lltok::LocalVar ||
1574 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1575 Name = Lex.getStrVal();
1576 Lex.Lex();
1577 } else {
1578 Name = "";
1579 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001580
Duncan Sands47c51882010-02-16 14:50:09 +00001581 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001582 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001583
Chris Lattnerdf986172009-01-02 07:01:27 +00001584 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1585 }
1586 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001587
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001588 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001589}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001590
Chris Lattnerdf986172009-01-02 07:01:27 +00001591/// ParseFunctionType
1592/// ::= Type ArgumentList OptionalAttrs
1593bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1594 assert(Lex.getKind() == lltok::lparen);
1595
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001596 if (!FunctionType::isValidReturnType(Result))
1597 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001598
Chris Lattnerdf986172009-01-02 07:01:27 +00001599 std::vector<ArgInfo> ArgList;
1600 bool isVarArg;
1601 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001602 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001603 // FIXME: Allow, but ignore attributes on function types!
1604 // FIXME: Remove in LLVM 3.0
1605 ParseOptionalAttrs(Attrs, 2))
1606 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001607
Chris Lattnerdf986172009-01-02 07:01:27 +00001608 // Reject names on the arguments lists.
1609 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1610 if (!ArgList[i].Name.empty())
1611 return Error(ArgList[i].Loc, "argument name invalid in function type");
1612 if (!ArgList[i].Attrs != 0) {
1613 // Allow but ignore attributes on function types; this permits
1614 // auto-upgrade.
1615 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1616 }
1617 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001618
Chris Lattnerdf986172009-01-02 07:01:27 +00001619 std::vector<const Type*> ArgListTy;
1620 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1621 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001622
Owen Andersondebcb012009-07-29 22:17:13 +00001623 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001624 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001625 return false;
1626}
1627
1628/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1629/// TypeRec
1630/// ::= '{' '}'
1631/// ::= '{' TypeRec (',' TypeRec)* '}'
1632/// ::= '<' '{' '}' '>'
1633/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1634bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1635 assert(Lex.getKind() == lltok::lbrace);
1636 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001637
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001638 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001639 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001640 return false;
1641 }
1642
1643 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001644 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001645 if (ParseTypeRec(Result)) return true;
1646 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001647
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001648 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001649 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001650 if (!StructType::isValidElementType(Result))
1651 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001652
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001653 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001654 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001655 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001656
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001657 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001658 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001659 if (!StructType::isValidElementType(Result))
1660 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001661
Chris Lattnerdf986172009-01-02 07:01:27 +00001662 ParamsList.push_back(Result);
1663 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001664
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001665 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1666 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001667
Chris Lattnerdf986172009-01-02 07:01:27 +00001668 std::vector<const Type*> ParamsListTy;
1669 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1670 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001671 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001672 return false;
1673}
1674
1675/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1676/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001677/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001678/// ::= '[' APSINTVAL 'x' Types ']'
1679/// ::= '<' APSINTVAL 'x' Types '>'
1680bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1681 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1682 Lex.getAPSIntVal().getBitWidth() > 64)
1683 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001684
Chris Lattnerdf986172009-01-02 07:01:27 +00001685 LocTy SizeLoc = Lex.getLoc();
1686 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001687 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001688
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001689 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1690 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001691
1692 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001693 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001694 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001695
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001696 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001697 return Error(TypeLoc, "array and vector element type cannot be void");
1698
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001699 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1700 "expected end of sequential type"))
1701 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001702
Chris Lattnerdf986172009-01-02 07:01:27 +00001703 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001704 if (Size == 0)
1705 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001706 if ((unsigned)Size != Size)
1707 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001708 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001709 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001710 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001711 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001712 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001713 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001714 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001715 }
1716 return false;
1717}
1718
1719//===----------------------------------------------------------------------===//
1720// Function Semantic Analysis.
1721//===----------------------------------------------------------------------===//
1722
Chris Lattner09d9ef42009-10-28 03:39:23 +00001723LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1724 int functionNumber)
1725 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001726
1727 // Insert unnamed arguments into the NumberedVals list.
1728 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1729 AI != E; ++AI)
1730 if (!AI->hasName())
1731 NumberedVals.push_back(AI);
1732}
1733
1734LLParser::PerFunctionState::~PerFunctionState() {
1735 // If there were any forward referenced non-basicblock values, delete them.
1736 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1737 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1738 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001739 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001740 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001741 delete I->second.first;
1742 I->second.first = 0;
1743 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001744
Chris Lattnerdf986172009-01-02 07:01:27 +00001745 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1746 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1747 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001748 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001749 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001750 delete I->second.first;
1751 I->second.first = 0;
1752 }
1753}
1754
Chris Lattner09d9ef42009-10-28 03:39:23 +00001755bool LLParser::PerFunctionState::FinishFunction() {
1756 // Check to see if someone took the address of labels in this block.
1757 if (!P.ForwardRefBlockAddresses.empty()) {
1758 ValID FunctionID;
1759 if (!F.getName().empty()) {
1760 FunctionID.Kind = ValID::t_GlobalName;
1761 FunctionID.StrVal = F.getName();
1762 } else {
1763 FunctionID.Kind = ValID::t_GlobalID;
1764 FunctionID.UIntVal = FunctionNumber;
1765 }
1766
1767 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1768 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1769 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1770 // Resolve all these references.
1771 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1772 return true;
1773
1774 P.ForwardRefBlockAddresses.erase(FRBAI);
1775 }
1776 }
1777
Chris Lattnerdf986172009-01-02 07:01:27 +00001778 if (!ForwardRefVals.empty())
1779 return P.Error(ForwardRefVals.begin()->second.second,
1780 "use of undefined value '%" + ForwardRefVals.begin()->first +
1781 "'");
1782 if (!ForwardRefValIDs.empty())
1783 return P.Error(ForwardRefValIDs.begin()->second.second,
1784 "use of undefined value '%" +
1785 utostr(ForwardRefValIDs.begin()->first) + "'");
1786 return false;
1787}
1788
1789
1790/// GetVal - Get a value with the specified name or ID, creating a
1791/// forward reference record if needed. This can return null if the value
1792/// exists but does not have the right type.
1793Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1794 const Type *Ty, LocTy Loc) {
1795 // Look this name up in the normal function symbol table.
1796 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001797
Chris Lattnerdf986172009-01-02 07:01:27 +00001798 // If this is a forward reference for the value, see if we already created a
1799 // forward ref record.
1800 if (Val == 0) {
1801 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1802 I = ForwardRefVals.find(Name);
1803 if (I != ForwardRefVals.end())
1804 Val = I->second.first;
1805 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001806
Chris Lattnerdf986172009-01-02 07:01:27 +00001807 // If we have the value in the symbol table or fwd-ref table, return it.
1808 if (Val) {
1809 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001810 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001811 P.Error(Loc, "'%" + Name + "' is not a basic block");
1812 else
1813 P.Error(Loc, "'%" + Name + "' defined with type '" +
1814 Val->getType()->getDescription() + "'");
1815 return 0;
1816 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001817
Chris Lattnerdf986172009-01-02 07:01:27 +00001818 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001819 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001820 P.Error(Loc, "invalid use of a non-first-class type");
1821 return 0;
1822 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001823
Chris Lattnerdf986172009-01-02 07:01:27 +00001824 // Otherwise, create a new forward reference for this value and remember it.
1825 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001826 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001827 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001828 else
1829 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001830
Chris Lattnerdf986172009-01-02 07:01:27 +00001831 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1832 return FwdVal;
1833}
1834
1835Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1836 LocTy Loc) {
1837 // Look this name up in the normal function symbol table.
1838 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001839
Chris Lattnerdf986172009-01-02 07:01:27 +00001840 // If this is a forward reference for the value, see if we already created a
1841 // forward ref record.
1842 if (Val == 0) {
1843 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1844 I = ForwardRefValIDs.find(ID);
1845 if (I != ForwardRefValIDs.end())
1846 Val = I->second.first;
1847 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001848
Chris Lattnerdf986172009-01-02 07:01:27 +00001849 // If we have the value in the symbol table or fwd-ref table, return it.
1850 if (Val) {
1851 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001852 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001853 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1854 else
1855 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1856 Val->getType()->getDescription() + "'");
1857 return 0;
1858 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001859
Duncan Sands47c51882010-02-16 14:50:09 +00001860 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001861 P.Error(Loc, "invalid use of a non-first-class type");
1862 return 0;
1863 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001864
Chris Lattnerdf986172009-01-02 07:01:27 +00001865 // Otherwise, create a new forward reference for this value and remember it.
1866 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001867 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001868 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001869 else
1870 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001871
Chris Lattnerdf986172009-01-02 07:01:27 +00001872 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1873 return FwdVal;
1874}
1875
1876/// SetInstName - After an instruction is parsed and inserted into its
1877/// basic block, this installs its name.
1878bool LLParser::PerFunctionState::SetInstName(int NameID,
1879 const std::string &NameStr,
1880 LocTy NameLoc, Instruction *Inst) {
1881 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001882 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001883 if (NameID != -1 || !NameStr.empty())
1884 return P.Error(NameLoc, "instructions returning void cannot have a name");
1885 return false;
1886 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001887
Chris Lattnerdf986172009-01-02 07:01:27 +00001888 // If this was a numbered instruction, verify that the instruction is the
1889 // expected value and resolve any forward references.
1890 if (NameStr.empty()) {
1891 // If neither a name nor an ID was specified, just use the next ID.
1892 if (NameID == -1)
1893 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001894
Chris Lattnerdf986172009-01-02 07:01:27 +00001895 if (unsigned(NameID) != NumberedVals.size())
1896 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1897 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001898
Chris Lattnerdf986172009-01-02 07:01:27 +00001899 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1900 ForwardRefValIDs.find(NameID);
1901 if (FI != ForwardRefValIDs.end()) {
1902 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001903 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001904 FI->second.first->getType()->getDescription() + "'");
1905 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001906 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001907 ForwardRefValIDs.erase(FI);
1908 }
1909
1910 NumberedVals.push_back(Inst);
1911 return false;
1912 }
1913
1914 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1915 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1916 FI = ForwardRefVals.find(NameStr);
1917 if (FI != ForwardRefVals.end()) {
1918 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001919 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001920 FI->second.first->getType()->getDescription() + "'");
1921 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001922 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001923 ForwardRefVals.erase(FI);
1924 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001925
Chris Lattnerdf986172009-01-02 07:01:27 +00001926 // Set the name on the instruction.
1927 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001928
Chris Lattnerdf986172009-01-02 07:01:27 +00001929 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001930 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001931 NameStr + "'");
1932 return false;
1933}
1934
1935/// GetBB - Get a basic block with the specified name or ID, creating a
1936/// forward reference record if needed.
1937BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1938 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001939 return cast_or_null<BasicBlock>(GetVal(Name,
1940 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001941}
1942
1943BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001944 return cast_or_null<BasicBlock>(GetVal(ID,
1945 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001946}
1947
1948/// DefineBB - Define the specified basic block, which is either named or
1949/// unnamed. If there is an error, this returns null otherwise it returns
1950/// the block being defined.
1951BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1952 LocTy Loc) {
1953 BasicBlock *BB;
1954 if (Name.empty())
1955 BB = GetBB(NumberedVals.size(), Loc);
1956 else
1957 BB = GetBB(Name, Loc);
1958 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001959
Chris Lattnerdf986172009-01-02 07:01:27 +00001960 // Move the block to the end of the function. Forward ref'd blocks are
1961 // inserted wherever they happen to be referenced.
1962 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001963
Chris Lattnerdf986172009-01-02 07:01:27 +00001964 // Remove the block from forward ref sets.
1965 if (Name.empty()) {
1966 ForwardRefValIDs.erase(NumberedVals.size());
1967 NumberedVals.push_back(BB);
1968 } else {
1969 // BB forward references are already in the function symbol table.
1970 ForwardRefVals.erase(Name);
1971 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001972
Chris Lattnerdf986172009-01-02 07:01:27 +00001973 return BB;
1974}
1975
1976//===----------------------------------------------------------------------===//
1977// Constants.
1978//===----------------------------------------------------------------------===//
1979
1980/// ParseValID - Parse an abstract value that doesn't necessarily have a
1981/// type implied. For example, if we parse "4" we don't know what integer type
1982/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001983/// sanity. PFS is used to convert function-local operands of metadata (since
1984/// metadata operands are not just parsed here but also converted to values).
1985/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001986bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001987 ID.Loc = Lex.getLoc();
1988 switch (Lex.getKind()) {
1989 default: return TokError("expected value token");
1990 case lltok::GlobalID: // @42
1991 ID.UIntVal = Lex.getUIntVal();
1992 ID.Kind = ValID::t_GlobalID;
1993 break;
1994 case lltok::GlobalVar: // @foo
1995 ID.StrVal = Lex.getStrVal();
1996 ID.Kind = ValID::t_GlobalName;
1997 break;
1998 case lltok::LocalVarID: // %42
1999 ID.UIntVal = Lex.getUIntVal();
2000 ID.Kind = ValID::t_LocalID;
2001 break;
2002 case lltok::LocalVar: // %foo
2003 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2004 ID.StrVal = Lex.getStrVal();
2005 ID.Kind = ValID::t_LocalName;
2006 break;
Dan Gohman83448032010-07-14 18:26:50 +00002007 case lltok::exclaim: // !42, !{...}, or !"foo"
2008 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002009 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002010 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002011 ID.Kind = ValID::t_APSInt;
2012 break;
2013 case lltok::APFloat:
2014 ID.APFloatVal = Lex.getAPFloatVal();
2015 ID.Kind = ValID::t_APFloat;
2016 break;
2017 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002018 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002019 ID.Kind = ValID::t_Constant;
2020 break;
2021 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002022 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002023 ID.Kind = ValID::t_Constant;
2024 break;
2025 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2026 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2027 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002028
Chris Lattnerdf986172009-01-02 07:01:27 +00002029 case lltok::lbrace: {
2030 // ValID ::= '{' ConstVector '}'
2031 Lex.Lex();
2032 SmallVector<Constant*, 16> Elts;
2033 if (ParseGlobalValueVector(Elts) ||
2034 ParseToken(lltok::rbrace, "expected end of struct constant"))
2035 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002036
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002037 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2038 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002039 ID.Kind = ValID::t_Constant;
2040 return false;
2041 }
2042 case lltok::less: {
2043 // ValID ::= '<' ConstVector '>' --> Vector.
2044 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2045 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002046 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002047
Chris Lattnerdf986172009-01-02 07:01:27 +00002048 SmallVector<Constant*, 16> Elts;
2049 LocTy FirstEltLoc = Lex.getLoc();
2050 if (ParseGlobalValueVector(Elts) ||
2051 (isPackedStruct &&
2052 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2053 ParseToken(lltok::greater, "expected end of constant"))
2054 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002055
Chris Lattnerdf986172009-01-02 07:01:27 +00002056 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002057 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002058 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002059 ID.Kind = ValID::t_Constant;
2060 return false;
2061 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002062
Chris Lattnerdf986172009-01-02 07:01:27 +00002063 if (Elts.empty())
2064 return Error(ID.Loc, "constant vector must not be empty");
2065
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002066 if (!Elts[0]->getType()->isIntegerTy() &&
2067 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002068 return Error(FirstEltLoc,
2069 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002070
Chris Lattnerdf986172009-01-02 07:01:27 +00002071 // Verify that all the vector elements have the same type.
2072 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2073 if (Elts[i]->getType() != Elts[0]->getType())
2074 return Error(FirstEltLoc,
2075 "vector element #" + utostr(i) +
2076 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002077
Owen Andersonaf7ec972009-07-28 21:19:26 +00002078 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002079 ID.Kind = ValID::t_Constant;
2080 return false;
2081 }
2082 case lltok::lsquare: { // Array Constant
2083 Lex.Lex();
2084 SmallVector<Constant*, 16> Elts;
2085 LocTy FirstEltLoc = Lex.getLoc();
2086 if (ParseGlobalValueVector(Elts) ||
2087 ParseToken(lltok::rsquare, "expected end of array constant"))
2088 return true;
2089
2090 // Handle empty element.
2091 if (Elts.empty()) {
2092 // Use undef instead of an array because it's inconvenient to determine
2093 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002094 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002095 return false;
2096 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002097
Chris Lattnerdf986172009-01-02 07:01:27 +00002098 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002099 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002100 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002101
Owen Andersondebcb012009-07-29 22:17:13 +00002102 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002103
Chris Lattnerdf986172009-01-02 07:01:27 +00002104 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002105 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002106 if (Elts[i]->getType() != Elts[0]->getType())
2107 return Error(FirstEltLoc,
2108 "array element #" + utostr(i) +
2109 " is not of type '" +Elts[0]->getType()->getDescription());
2110 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002111
Owen Anderson1fd70962009-07-28 18:32:17 +00002112 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002113 ID.Kind = ValID::t_Constant;
2114 return false;
2115 }
2116 case lltok::kw_c: // c "foo"
2117 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002118 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002119 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2120 ID.Kind = ValID::t_Constant;
2121 return false;
2122
2123 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002124 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2125 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002126 Lex.Lex();
2127 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002128 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002129 ParseStringConstant(ID.StrVal) ||
2130 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002131 ParseToken(lltok::StringConstant, "expected constraint string"))
2132 return true;
2133 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002134 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002135 ID.Kind = ValID::t_InlineAsm;
2136 return false;
2137 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002138
Chris Lattner09d9ef42009-10-28 03:39:23 +00002139 case lltok::kw_blockaddress: {
2140 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2141 Lex.Lex();
2142
2143 ValID Fn, Label;
2144 LocTy FnLoc, LabelLoc;
2145
2146 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2147 ParseValID(Fn) ||
2148 ParseToken(lltok::comma, "expected comma in block address expression")||
2149 ParseValID(Label) ||
2150 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2151 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002152
Chris Lattner09d9ef42009-10-28 03:39:23 +00002153 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2154 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002155 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002156 return Error(Label.Loc, "expected basic block name in blockaddress");
2157
2158 // Make a global variable as a placeholder for this reference.
2159 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2160 false, GlobalValue::InternalLinkage,
2161 0, "");
2162 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2163 ID.ConstantVal = FwdRef;
2164 ID.Kind = ValID::t_Constant;
2165 return false;
2166 }
2167
Chris Lattnerdf986172009-01-02 07:01:27 +00002168 case lltok::kw_trunc:
2169 case lltok::kw_zext:
2170 case lltok::kw_sext:
2171 case lltok::kw_fptrunc:
2172 case lltok::kw_fpext:
2173 case lltok::kw_bitcast:
2174 case lltok::kw_uitofp:
2175 case lltok::kw_sitofp:
2176 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002177 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002178 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002179 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002180 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002181 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002182 Constant *SrcVal;
2183 Lex.Lex();
2184 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2185 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002186 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002187 ParseType(DestTy) ||
2188 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2189 return true;
2190 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2191 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2192 SrcVal->getType()->getDescription() + "' to '" +
2193 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002194 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002195 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002196 ID.Kind = ValID::t_Constant;
2197 return false;
2198 }
2199 case lltok::kw_extractvalue: {
2200 Lex.Lex();
2201 Constant *Val;
2202 SmallVector<unsigned, 4> Indices;
2203 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2204 ParseGlobalTypeAndValue(Val) ||
2205 ParseIndexList(Indices) ||
2206 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2207 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002208
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002209 if (!Val->getType()->isAggregateType())
2210 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002211 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2212 Indices.end()))
2213 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002214 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002215 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002216 ID.Kind = ValID::t_Constant;
2217 return false;
2218 }
2219 case lltok::kw_insertvalue: {
2220 Lex.Lex();
2221 Constant *Val0, *Val1;
2222 SmallVector<unsigned, 4> Indices;
2223 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2224 ParseGlobalTypeAndValue(Val0) ||
2225 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2226 ParseGlobalTypeAndValue(Val1) ||
2227 ParseIndexList(Indices) ||
2228 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2229 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002230 if (!Val0->getType()->isAggregateType())
2231 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002232 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2233 Indices.end()))
2234 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002235 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002236 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002237 ID.Kind = ValID::t_Constant;
2238 return false;
2239 }
2240 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002241 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002242 unsigned PredVal, Opc = Lex.getUIntVal();
2243 Constant *Val0, *Val1;
2244 Lex.Lex();
2245 if (ParseCmpPredicate(PredVal, Opc) ||
2246 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2247 ParseGlobalTypeAndValue(Val0) ||
2248 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2249 ParseGlobalTypeAndValue(Val1) ||
2250 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2251 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002252
Chris Lattnerdf986172009-01-02 07:01:27 +00002253 if (Val0->getType() != Val1->getType())
2254 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002255
Chris Lattnerdf986172009-01-02 07:01:27 +00002256 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002257
Chris Lattnerdf986172009-01-02 07:01:27 +00002258 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002259 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002260 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002261 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002262 } else {
2263 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002264 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002265 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002266 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002267 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002268 }
2269 ID.Kind = ValID::t_Constant;
2270 return false;
2271 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002272
Chris Lattnerdf986172009-01-02 07:01:27 +00002273 // Binary Operators.
2274 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002275 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002276 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002277 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002278 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002279 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002280 case lltok::kw_udiv:
2281 case lltok::kw_sdiv:
2282 case lltok::kw_fdiv:
2283 case lltok::kw_urem:
2284 case lltok::kw_srem:
2285 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002286 bool NUW = false;
2287 bool NSW = false;
2288 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002289 unsigned Opc = Lex.getUIntVal();
2290 Constant *Val0, *Val1;
2291 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002292 LocTy ModifierLoc = Lex.getLoc();
2293 if (Opc == Instruction::Add ||
2294 Opc == Instruction::Sub ||
2295 Opc == Instruction::Mul) {
2296 if (EatIfPresent(lltok::kw_nuw))
2297 NUW = true;
2298 if (EatIfPresent(lltok::kw_nsw)) {
2299 NSW = true;
2300 if (EatIfPresent(lltok::kw_nuw))
2301 NUW = true;
2302 }
2303 } else if (Opc == Instruction::SDiv) {
2304 if (EatIfPresent(lltok::kw_exact))
2305 Exact = true;
2306 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002307 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2308 ParseGlobalTypeAndValue(Val0) ||
2309 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2310 ParseGlobalTypeAndValue(Val1) ||
2311 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2312 return true;
2313 if (Val0->getType() != Val1->getType())
2314 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002315 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002316 if (NUW)
2317 return Error(ModifierLoc, "nuw only applies to integer operations");
2318 if (NSW)
2319 return Error(ModifierLoc, "nsw only applies to integer operations");
2320 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002321 // Check that the type is valid for the operator.
2322 switch (Opc) {
2323 case Instruction::Add:
2324 case Instruction::Sub:
2325 case Instruction::Mul:
2326 case Instruction::UDiv:
2327 case Instruction::SDiv:
2328 case Instruction::URem:
2329 case Instruction::SRem:
2330 if (!Val0->getType()->isIntOrIntVectorTy())
2331 return Error(ID.Loc, "constexpr requires integer operands");
2332 break;
2333 case Instruction::FAdd:
2334 case Instruction::FSub:
2335 case Instruction::FMul:
2336 case Instruction::FDiv:
2337 case Instruction::FRem:
2338 if (!Val0->getType()->isFPOrFPVectorTy())
2339 return Error(ID.Loc, "constexpr requires fp operands");
2340 break;
2341 default: llvm_unreachable("Unknown binary operator!");
2342 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002343 unsigned Flags = 0;
2344 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2345 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2346 if (Exact) Flags |= SDivOperator::IsExact;
2347 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002348 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002349 ID.Kind = ValID::t_Constant;
2350 return false;
2351 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002352
Chris Lattnerdf986172009-01-02 07:01:27 +00002353 // Logical Operations
2354 case lltok::kw_shl:
2355 case lltok::kw_lshr:
2356 case lltok::kw_ashr:
2357 case lltok::kw_and:
2358 case lltok::kw_or:
2359 case lltok::kw_xor: {
2360 unsigned Opc = Lex.getUIntVal();
2361 Constant *Val0, *Val1;
2362 Lex.Lex();
2363 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2364 ParseGlobalTypeAndValue(Val0) ||
2365 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2366 ParseGlobalTypeAndValue(Val1) ||
2367 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2368 return true;
2369 if (Val0->getType() != Val1->getType())
2370 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002371 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002372 return Error(ID.Loc,
2373 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002374 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002375 ID.Kind = ValID::t_Constant;
2376 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002377 }
2378
Chris Lattnerdf986172009-01-02 07:01:27 +00002379 case lltok::kw_getelementptr:
2380 case lltok::kw_shufflevector:
2381 case lltok::kw_insertelement:
2382 case lltok::kw_extractelement:
2383 case lltok::kw_select: {
2384 unsigned Opc = Lex.getUIntVal();
2385 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002386 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002387 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002388 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002389 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002390 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2391 ParseGlobalValueVector(Elts) ||
2392 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2393 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002394
Chris Lattnerdf986172009-01-02 07:01:27 +00002395 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002396 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002397 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002398
Chris Lattnerdf986172009-01-02 07:01:27 +00002399 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002400 (Value**)(Elts.data() + 1),
2401 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002402 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002403 ID.ConstantVal = InBounds ?
2404 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2405 Elts.data() + 1,
2406 Elts.size() - 1) :
2407 ConstantExpr::getGetElementPtr(Elts[0],
2408 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002409 } else if (Opc == Instruction::Select) {
2410 if (Elts.size() != 3)
2411 return Error(ID.Loc, "expected three operands to select");
2412 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2413 Elts[2]))
2414 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002415 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002416 } else if (Opc == Instruction::ShuffleVector) {
2417 if (Elts.size() != 3)
2418 return Error(ID.Loc, "expected three operands to shufflevector");
2419 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2420 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002421 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002422 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002423 } else if (Opc == Instruction::ExtractElement) {
2424 if (Elts.size() != 2)
2425 return Error(ID.Loc, "expected two operands to extractelement");
2426 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2427 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002428 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002429 } else {
2430 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2431 if (Elts.size() != 3)
2432 return Error(ID.Loc, "expected three operands to insertelement");
2433 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2434 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002435 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002436 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002437 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002438
Chris Lattnerdf986172009-01-02 07:01:27 +00002439 ID.Kind = ValID::t_Constant;
2440 return false;
2441 }
2442 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002443
Chris Lattnerdf986172009-01-02 07:01:27 +00002444 Lex.Lex();
2445 return false;
2446}
2447
2448/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002449bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2450 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002451 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002452 Value *V = NULL;
2453 bool Parsed = ParseValID(ID) ||
2454 ConvertValIDToValue(Ty, ID, V, NULL);
2455 if (V && !(C = dyn_cast<Constant>(V)))
2456 return Error(ID.Loc, "global values must be constants");
2457 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002458}
2459
Victor Hernandez92f238d2010-01-11 22:31:58 +00002460bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2461 PATypeHolder Type(Type::getVoidTy(Context));
2462 return ParseType(Type) ||
2463 ParseGlobalValue(Type, V);
2464}
2465
2466/// ParseGlobalValueVector
2467/// ::= /*empty*/
2468/// ::= TypeAndValue (',' TypeAndValue)*
2469bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2470 // Empty list.
2471 if (Lex.getKind() == lltok::rbrace ||
2472 Lex.getKind() == lltok::rsquare ||
2473 Lex.getKind() == lltok::greater ||
2474 Lex.getKind() == lltok::rparen)
2475 return false;
2476
2477 Constant *C;
2478 if (ParseGlobalTypeAndValue(C)) return true;
2479 Elts.push_back(C);
2480
2481 while (EatIfPresent(lltok::comma)) {
2482 if (ParseGlobalTypeAndValue(C)) return true;
2483 Elts.push_back(C);
2484 }
2485
2486 return false;
2487}
2488
Dan Gohman309b3af2010-08-24 02:24:03 +00002489bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2490 assert(Lex.getKind() == lltok::lbrace);
2491 Lex.Lex();
2492
2493 SmallVector<Value*, 16> Elts;
2494 if (ParseMDNodeVector(Elts, PFS) ||
2495 ParseToken(lltok::rbrace, "expected end of metadata node"))
2496 return true;
2497
2498 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
2499 ID.Kind = ValID::t_MDNode;
2500 return false;
2501}
2502
Dan Gohman83448032010-07-14 18:26:50 +00002503/// ParseMetadataValue
2504/// ::= !42
2505/// ::= !{...}
2506/// ::= !"string"
2507bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2508 assert(Lex.getKind() == lltok::exclaim);
2509 Lex.Lex();
2510
2511 // MDNode:
2512 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002513 if (Lex.getKind() == lltok::lbrace)
2514 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002515
2516 // Standalone metadata reference
2517 // !42
2518 if (Lex.getKind() == lltok::APSInt) {
2519 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2520 ID.Kind = ValID::t_MDNode;
2521 return false;
2522 }
2523
2524 // MDString:
2525 // ::= '!' STRINGCONSTANT
2526 if (ParseMDString(ID.MDStringVal)) return true;
2527 ID.Kind = ValID::t_MDString;
2528 return false;
2529}
2530
Victor Hernandez92f238d2010-01-11 22:31:58 +00002531
2532//===----------------------------------------------------------------------===//
2533// Function Parsing.
2534//===----------------------------------------------------------------------===//
2535
2536bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2537 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002538 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002539 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002540
Chris Lattnerdf986172009-01-02 07:01:27 +00002541 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002542 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002543 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002544 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2545 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2546 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002547 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002548 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2549 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2550 return (V == 0);
2551 case ValID::t_InlineAsm: {
2552 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2553 const FunctionType *FTy =
2554 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2555 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2556 return Error(ID.Loc, "invalid type for inline asm constraint string");
2557 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2558 return false;
2559 }
2560 case ValID::t_MDNode:
2561 if (!Ty->isMetadataTy())
2562 return Error(ID.Loc, "metadata value must have metadata type");
2563 V = ID.MDNodeVal;
2564 return false;
2565 case ValID::t_MDString:
2566 if (!Ty->isMetadataTy())
2567 return Error(ID.Loc, "metadata value must have metadata type");
2568 V = ID.MDStringVal;
2569 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002570 case ValID::t_GlobalName:
2571 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2572 return V == 0;
2573 case ValID::t_GlobalID:
2574 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2575 return V == 0;
2576 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002577 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002578 return Error(ID.Loc, "integer constant must have integer type");
2579 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002580 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002581 return false;
2582 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002583 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002584 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2585 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002586
Chris Lattnerdf986172009-01-02 07:01:27 +00002587 // The lexer has no type info, so builds all float and double FP constants
2588 // as double. Fix this here. Long double does not need this.
2589 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002590 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002591 bool Ignored;
2592 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2593 &Ignored);
2594 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002595 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002596
Chris Lattner959873d2009-01-05 18:24:23 +00002597 if (V->getType() != Ty)
2598 return Error(ID.Loc, "floating point constant does not have type '" +
2599 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002600
Chris Lattnerdf986172009-01-02 07:01:27 +00002601 return false;
2602 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002603 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002604 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002605 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002606 return false;
2607 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002608 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002609 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002610 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002611 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002612 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002613 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002614 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002615 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002616 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002617 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002618 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002619 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002620 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002621 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002622 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002623 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002624 return false;
2625 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002626 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002627 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002628
Chris Lattnerdf986172009-01-02 07:01:27 +00002629 V = ID.ConstantVal;
2630 return false;
2631 }
2632}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002633
Chris Lattnerdf986172009-01-02 07:01:27 +00002634bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2635 V = 0;
2636 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002637 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002638 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002639}
2640
2641bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002642 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002643 return ParseType(T) ||
2644 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002645}
2646
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002647bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2648 PerFunctionState &PFS) {
2649 Value *V;
2650 Loc = Lex.getLoc();
2651 if (ParseTypeAndValue(V, PFS)) return true;
2652 if (!isa<BasicBlock>(V))
2653 return Error(Loc, "expected a basic block");
2654 BB = cast<BasicBlock>(V);
2655 return false;
2656}
2657
2658
Chris Lattnerdf986172009-01-02 07:01:27 +00002659/// FunctionHeader
2660/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2661/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2662/// OptionalAlign OptGC
2663bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2664 // Parse the linkage.
2665 LocTy LinkageLoc = Lex.getLoc();
2666 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002667
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002668 unsigned Visibility, RetAttrs;
2669 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002670 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002671 LocTy RetTypeLoc = Lex.getLoc();
2672 if (ParseOptionalLinkage(Linkage) ||
2673 ParseOptionalVisibility(Visibility) ||
2674 ParseOptionalCallingConv(CC) ||
2675 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002676 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002677 return true;
2678
2679 // Verify that the linkage is ok.
2680 switch ((GlobalValue::LinkageTypes)Linkage) {
2681 case GlobalValue::ExternalLinkage:
2682 break; // always ok.
2683 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002684 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002685 if (isDefine)
2686 return Error(LinkageLoc, "invalid linkage for function definition");
2687 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002688 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002689 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002690 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling55ae5152010-08-20 22:05:50 +00002691 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002692 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002693 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002694 case GlobalValue::LinkOnceAnyLinkage:
2695 case GlobalValue::LinkOnceODRLinkage:
2696 case GlobalValue::WeakAnyLinkage:
2697 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002698 case GlobalValue::DLLExportLinkage:
2699 if (!isDefine)
2700 return Error(LinkageLoc, "invalid linkage for function declaration");
2701 break;
2702 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002703 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002704 return Error(LinkageLoc, "invalid function linkage type");
2705 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002706
Chris Lattner99bb3152009-01-05 08:00:30 +00002707 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002708 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002709 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002710
Chris Lattnerdf986172009-01-02 07:01:27 +00002711 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002712
2713 std::string FunctionName;
2714 if (Lex.getKind() == lltok::GlobalVar) {
2715 FunctionName = Lex.getStrVal();
2716 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2717 unsigned NameID = Lex.getUIntVal();
2718
2719 if (NameID != NumberedVals.size())
2720 return TokError("function expected to be numbered '%" +
2721 utostr(NumberedVals.size()) + "'");
2722 } else {
2723 return TokError("expected function name");
2724 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002725
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002726 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002727
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002728 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002729 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002730
Chris Lattnerdf986172009-01-02 07:01:27 +00002731 std::vector<ArgInfo> ArgList;
2732 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002733 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002734 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002735 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002736 std::string GC;
2737
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002738 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002739 ParseOptionalAttrs(FuncAttrs, 2) ||
2740 (EatIfPresent(lltok::kw_section) &&
2741 ParseStringConstant(Section)) ||
2742 ParseOptionalAlignment(Alignment) ||
2743 (EatIfPresent(lltok::kw_gc) &&
2744 ParseStringConstant(GC)))
2745 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002746
2747 // If the alignment was parsed as an attribute, move to the alignment field.
2748 if (FuncAttrs & Attribute::Alignment) {
2749 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2750 FuncAttrs &= ~Attribute::Alignment;
2751 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002752
Chris Lattnerdf986172009-01-02 07:01:27 +00002753 // Okay, if we got here, the function is syntactically valid. Convert types
2754 // and do semantic checks.
2755 std::vector<const Type*> ParamTypeList;
2756 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002757 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002758 // attributes.
2759 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2760 if (FuncAttrs & ObsoleteFuncAttrs) {
2761 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2762 FuncAttrs &= ~ObsoleteFuncAttrs;
2763 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002764
Chris Lattnerdf986172009-01-02 07:01:27 +00002765 if (RetAttrs != Attribute::None)
2766 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002767
Chris Lattnerdf986172009-01-02 07:01:27 +00002768 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2769 ParamTypeList.push_back(ArgList[i].Type);
2770 if (ArgList[i].Attrs != Attribute::None)
2771 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2772 }
2773
2774 if (FuncAttrs != Attribute::None)
2775 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2776
2777 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002778
Benjamin Kramerf0127052010-01-05 13:12:22 +00002779 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002780 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2781
Owen Andersonfba933c2009-07-01 23:57:11 +00002782 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002783 FunctionType::get(RetType, ParamTypeList, isVarArg);
2784 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002785
2786 Fn = 0;
2787 if (!FunctionName.empty()) {
2788 // If this was a definition of a forward reference, remove the definition
2789 // from the forward reference table and fill in the forward ref.
2790 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2791 ForwardRefVals.find(FunctionName);
2792 if (FRVI != ForwardRefVals.end()) {
2793 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002794 if (Fn->getType() != PFT)
2795 return Error(FRVI->second.second, "invalid forward reference to "
2796 "function '" + FunctionName + "' with wrong type!");
2797
Chris Lattnerdf986172009-01-02 07:01:27 +00002798 ForwardRefVals.erase(FRVI);
2799 } else if ((Fn = M->getFunction(FunctionName))) {
2800 // If this function already exists in the symbol table, then it is
2801 // multiply defined. We accept a few cases for old backwards compat.
2802 // FIXME: Remove this stuff for LLVM 3.0.
2803 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2804 (!Fn->isDeclaration() && isDefine)) {
2805 // If the redefinition has different type or different attributes,
2806 // reject it. If both have bodies, reject it.
2807 return Error(NameLoc, "invalid redefinition of function '" +
2808 FunctionName + "'");
2809 } else if (Fn->isDeclaration()) {
2810 // Make sure to strip off any argument names so we can't get conflicts.
2811 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2812 AI != AE; ++AI)
2813 AI->setName("");
2814 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002815 } else if (M->getNamedValue(FunctionName)) {
2816 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002817 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002818
Dan Gohman41905542009-08-29 23:37:49 +00002819 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002820 // If this is a definition of a forward referenced function, make sure the
2821 // types agree.
2822 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2823 = ForwardRefValIDs.find(NumberedVals.size());
2824 if (I != ForwardRefValIDs.end()) {
2825 Fn = cast<Function>(I->second.first);
2826 if (Fn->getType() != PFT)
2827 return Error(NameLoc, "type of definition and forward reference of '@" +
2828 utostr(NumberedVals.size()) +"' disagree");
2829 ForwardRefValIDs.erase(I);
2830 }
2831 }
2832
2833 if (Fn == 0)
2834 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2835 else // Move the forward-reference to the correct spot in the module.
2836 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2837
2838 if (FunctionName.empty())
2839 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002840
Chris Lattnerdf986172009-01-02 07:01:27 +00002841 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2842 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2843 Fn->setCallingConv(CC);
2844 Fn->setAttributes(PAL);
2845 Fn->setAlignment(Alignment);
2846 Fn->setSection(Section);
2847 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002848
Chris Lattnerdf986172009-01-02 07:01:27 +00002849 // Add all of the arguments we parsed to the function.
2850 Function::arg_iterator ArgIt = Fn->arg_begin();
2851 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002852 // If we run out of arguments in the Function prototype, exit early.
2853 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2854 if (ArgIt == Fn->arg_end()) break;
2855
Chris Lattnerdf986172009-01-02 07:01:27 +00002856 // If the argument has a name, insert it into the argument symbol table.
2857 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002858
Chris Lattnerdf986172009-01-02 07:01:27 +00002859 // Set the name, if it conflicted, it will be auto-renamed.
2860 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002861
Chris Lattnerdf986172009-01-02 07:01:27 +00002862 if (ArgIt->getNameStr() != ArgList[i].Name)
2863 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2864 ArgList[i].Name + "'");
2865 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002866
Chris Lattnerdf986172009-01-02 07:01:27 +00002867 return false;
2868}
2869
2870
2871/// ParseFunctionBody
2872/// ::= '{' BasicBlock+ '}'
2873/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2874///
2875bool LLParser::ParseFunctionBody(Function &Fn) {
2876 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2877 return TokError("expected '{' in function body");
2878 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002879
Chris Lattner09d9ef42009-10-28 03:39:23 +00002880 int FunctionNumber = -1;
2881 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2882
2883 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002884
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002885 // We need at least one basic block.
2886 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2887 return TokError("function body requires at least one basic block");
2888
Chris Lattnerdf986172009-01-02 07:01:27 +00002889 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2890 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002891
Chris Lattnerdf986172009-01-02 07:01:27 +00002892 // Eat the }.
2893 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002894
Chris Lattnerdf986172009-01-02 07:01:27 +00002895 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002896 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002897}
2898
2899/// ParseBasicBlock
2900/// ::= LabelStr? Instruction*
2901bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2902 // If this basic block starts out with a name, remember it.
2903 std::string Name;
2904 LocTy NameLoc = Lex.getLoc();
2905 if (Lex.getKind() == lltok::LabelStr) {
2906 Name = Lex.getStrVal();
2907 Lex.Lex();
2908 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002909
Chris Lattnerdf986172009-01-02 07:01:27 +00002910 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2911 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002912
Chris Lattnerdf986172009-01-02 07:01:27 +00002913 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002914
Chris Lattnerdf986172009-01-02 07:01:27 +00002915 // Parse the instructions in this block until we get a terminator.
2916 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002917 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002918 do {
2919 // This instruction may have three possibilities for a name: a) none
2920 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2921 LocTy NameLoc = Lex.getLoc();
2922 int NameID = -1;
2923 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002924
Chris Lattnerdf986172009-01-02 07:01:27 +00002925 if (Lex.getKind() == lltok::LocalVarID) {
2926 NameID = Lex.getUIntVal();
2927 Lex.Lex();
2928 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2929 return true;
2930 } else if (Lex.getKind() == lltok::LocalVar ||
2931 // FIXME: REMOVE IN LLVM 3.0
2932 Lex.getKind() == lltok::StringConstant) {
2933 NameStr = Lex.getStrVal();
2934 Lex.Lex();
2935 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2936 return true;
2937 }
Devang Patelf633a062009-09-17 23:04:48 +00002938
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002939 switch (ParseInstruction(Inst, BB, PFS)) {
2940 default: assert(0 && "Unknown ParseInstruction result!");
2941 case InstError: return true;
2942 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002943 BB->getInstList().push_back(Inst);
2944
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002945 // With a normal result, we check to see if the instruction is followed by
2946 // a comma and metadata.
2947 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002948 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002949 return true;
2950 break;
2951 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002952 BB->getInstList().push_back(Inst);
2953
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002954 // If the instruction parser ate an extra comma at the end of it, it
2955 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002956 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002957 return true;
2958 break;
2959 }
Devang Patelf633a062009-09-17 23:04:48 +00002960
Chris Lattnerdf986172009-01-02 07:01:27 +00002961 // Set the name on the instruction.
2962 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2963 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002964
Chris Lattnerdf986172009-01-02 07:01:27 +00002965 return false;
2966}
2967
2968//===----------------------------------------------------------------------===//
2969// Instruction Parsing.
2970//===----------------------------------------------------------------------===//
2971
2972/// ParseInstruction - Parse one of the many different instructions.
2973///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002974int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2975 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002976 lltok::Kind Token = Lex.getKind();
2977 if (Token == lltok::Eof)
2978 return TokError("found end of file when expecting more instructions");
2979 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002980 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002981 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002982
Chris Lattnerdf986172009-01-02 07:01:27 +00002983 switch (Token) {
2984 default: return Error(Loc, "expected instruction opcode");
2985 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002986 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2987 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002988 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2989 case lltok::kw_br: return ParseBr(Inst, PFS);
2990 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002991 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002992 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2993 // Binary Operators.
2994 case lltok::kw_add:
2995 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002996 case lltok::kw_mul: {
2997 bool NUW = false;
2998 bool NSW = false;
2999 LocTy ModifierLoc = Lex.getLoc();
3000 if (EatIfPresent(lltok::kw_nuw))
3001 NUW = true;
3002 if (EatIfPresent(lltok::kw_nsw)) {
3003 NSW = true;
3004 if (EatIfPresent(lltok::kw_nuw))
3005 NUW = true;
3006 }
Dan Gohman1eaac532010-05-03 22:44:19 +00003007 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
Dan Gohman59858cf2009-07-27 16:11:46 +00003008 if (!Result) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003009 if (!Inst->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00003010 if (NUW)
3011 return Error(ModifierLoc, "nuw only applies to integer operations");
3012 if (NSW)
3013 return Error(ModifierLoc, "nsw only applies to integer operations");
3014 }
3015 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003016 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003017 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003018 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003019 }
3020 return Result;
3021 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003022 case lltok::kw_fadd:
3023 case lltok::kw_fsub:
3024 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3025
Dan Gohman59858cf2009-07-27 16:11:46 +00003026 case lltok::kw_sdiv: {
3027 bool Exact = false;
3028 if (EatIfPresent(lltok::kw_exact))
3029 Exact = true;
3030 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3031 if (!Result)
3032 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003033 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003034 return Result;
3035 }
3036
Chris Lattnerdf986172009-01-02 07:01:27 +00003037 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00003038 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003039 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00003040 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003041 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00003042 case lltok::kw_shl:
3043 case lltok::kw_lshr:
3044 case lltok::kw_ashr:
3045 case lltok::kw_and:
3046 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003047 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003048 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003049 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003050 // Casts.
3051 case lltok::kw_trunc:
3052 case lltok::kw_zext:
3053 case lltok::kw_sext:
3054 case lltok::kw_fptrunc:
3055 case lltok::kw_fpext:
3056 case lltok::kw_bitcast:
3057 case lltok::kw_uitofp:
3058 case lltok::kw_sitofp:
3059 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003060 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003061 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003062 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003063 // Other.
3064 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003065 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003066 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3067 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3068 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3069 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3070 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3071 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3072 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003073 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3074 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00003075 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003076 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3077 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3078 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003079 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00003080 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003081 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00003082 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003083 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003084 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003085 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3086 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3087 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3088 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3089 }
3090}
3091
3092/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3093bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003094 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003095 switch (Lex.getKind()) {
3096 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3097 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3098 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3099 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3100 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3101 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3102 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3103 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3104 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3105 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3106 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3107 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3108 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3109 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3110 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3111 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3112 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3113 }
3114 } else {
3115 switch (Lex.getKind()) {
3116 default: TokError("expected icmp predicate (e.g. 'eq')");
3117 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3118 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3119 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3120 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3121 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3122 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3123 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3124 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3125 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3126 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3127 }
3128 }
3129 Lex.Lex();
3130 return false;
3131}
3132
3133//===----------------------------------------------------------------------===//
3134// Terminator Instructions.
3135//===----------------------------------------------------------------------===//
3136
3137/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003138/// ::= 'ret' void (',' !dbg, !1)*
3139/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3140/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00003141/// [[obsolete: LLVM 3.0]]
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003142int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3143 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003144 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003145 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003146
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003147 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003148 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003149 return false;
3150 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003151
Chris Lattnerdf986172009-01-02 07:01:27 +00003152 Value *RV;
3153 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003154
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003155 bool ExtraComma = false;
Devang Patelf633a062009-09-17 23:04:48 +00003156 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003157 // Parse optional custom metadata, e.g. !dbg
Chris Lattner1d928312009-12-30 05:02:06 +00003158 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003159 ExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003160 } else {
3161 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003162 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3163 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003164 SmallVector<Value*, 8> RVs;
3165 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003166
Devang Patelf633a062009-09-17 23:04:48 +00003167 do {
Devang Patel0475c912009-09-29 00:01:14 +00003168 // If optional custom metadata, e.g. !dbg is seen then this is the
3169 // end of MRV.
Chris Lattner1d928312009-12-30 05:02:06 +00003170 if (Lex.getKind() == lltok::MetadataVar)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003171 break;
3172 if (ParseTypeAndValue(RV, PFS)) return true;
3173 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003174 } while (EatIfPresent(lltok::comma));
3175
3176 RV = UndefValue::get(PFS.getFunction().getReturnType());
3177 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003178 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3179 BB->getInstList().push_back(I);
3180 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003181 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003182 }
3183 }
Devang Patelf633a062009-09-17 23:04:48 +00003184
Owen Anderson1d0be152009-08-13 21:58:54 +00003185 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003186 return ExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003187}
3188
3189
3190/// ParseBr
3191/// ::= 'br' TypeAndValue
3192/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3193bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3194 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003195 Value *Op0;
3196 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003197 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003198
Chris Lattnerdf986172009-01-02 07:01:27 +00003199 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3200 Inst = BranchInst::Create(BB);
3201 return false;
3202 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003203
Owen Anderson1d0be152009-08-13 21:58:54 +00003204 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003205 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003206
Chris Lattnerdf986172009-01-02 07:01:27 +00003207 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003208 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003209 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003210 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003211 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003212
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003213 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003214 return false;
3215}
3216
3217/// ParseSwitch
3218/// Instruction
3219/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3220/// JumpTable
3221/// ::= (TypeAndValue ',' TypeAndValue)*
3222bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3223 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003224 Value *Cond;
3225 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003226 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3227 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003228 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003229 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3230 return true;
3231
Duncan Sands1df98592010-02-16 11:11:14 +00003232 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003233 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003234
Chris Lattnerdf986172009-01-02 07:01:27 +00003235 // Parse the jump table pairs.
3236 SmallPtrSet<Value*, 32> SeenCases;
3237 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3238 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003239 Value *Constant;
3240 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003241
Chris Lattnerdf986172009-01-02 07:01:27 +00003242 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3243 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003244 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003245 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003246
Chris Lattnerdf986172009-01-02 07:01:27 +00003247 if (!SeenCases.insert(Constant))
3248 return Error(CondLoc, "duplicate case value in switch");
3249 if (!isa<ConstantInt>(Constant))
3250 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003251
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003252 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003253 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003254
Chris Lattnerdf986172009-01-02 07:01:27 +00003255 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003256
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003257 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003258 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3259 SI->addCase(Table[i].first, Table[i].second);
3260 Inst = SI;
3261 return false;
3262}
3263
Chris Lattnerab21db72009-10-28 00:19:10 +00003264/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003265/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003266/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3267bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003268 LocTy AddrLoc;
3269 Value *Address;
3270 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003271 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3272 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003273 return true;
3274
Duncan Sands1df98592010-02-16 11:11:14 +00003275 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003276 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003277
3278 // Parse the destination list.
3279 SmallVector<BasicBlock*, 16> DestList;
3280
3281 if (Lex.getKind() != lltok::rsquare) {
3282 BasicBlock *DestBB;
3283 if (ParseTypeAndBasicBlock(DestBB, PFS))
3284 return true;
3285 DestList.push_back(DestBB);
3286
3287 while (EatIfPresent(lltok::comma)) {
3288 if (ParseTypeAndBasicBlock(DestBB, PFS))
3289 return true;
3290 DestList.push_back(DestBB);
3291 }
3292 }
3293
3294 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3295 return true;
3296
Chris Lattnerab21db72009-10-28 00:19:10 +00003297 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003298 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3299 IBI->addDestination(DestList[i]);
3300 Inst = IBI;
3301 return false;
3302}
3303
3304
Chris Lattnerdf986172009-01-02 07:01:27 +00003305/// ParseInvoke
3306/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3307/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3308bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3309 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003310 unsigned RetAttrs, FnAttrs;
3311 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003312 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003313 LocTy RetTypeLoc;
3314 ValID CalleeID;
3315 SmallVector<ParamInfo, 16> ArgList;
3316
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003317 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003318 if (ParseOptionalCallingConv(CC) ||
3319 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003320 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003321 ParseValID(CalleeID) ||
3322 ParseParameterList(ArgList, PFS) ||
3323 ParseOptionalAttrs(FnAttrs, 2) ||
3324 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003325 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003326 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003327 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003328 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003329
Chris Lattnerdf986172009-01-02 07:01:27 +00003330 // If RetType is a non-function pointer type, then this is the short syntax
3331 // for the call, which means that RetType is just the return type. Infer the
3332 // rest of the function argument types from the arguments that are present.
3333 const PointerType *PFTy = 0;
3334 const FunctionType *Ty = 0;
3335 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3336 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3337 // Pull out the types of all of the arguments...
3338 std::vector<const Type*> ParamTypes;
3339 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3340 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003341
Chris Lattnerdf986172009-01-02 07:01:27 +00003342 if (!FunctionType::isValidReturnType(RetType))
3343 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003344
Owen Andersondebcb012009-07-29 22:17:13 +00003345 Ty = FunctionType::get(RetType, ParamTypes, false);
3346 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003347 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003348
Chris Lattnerdf986172009-01-02 07:01:27 +00003349 // Look up the callee.
3350 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003351 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003352
Chris Lattnerdf986172009-01-02 07:01:27 +00003353 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3354 // function attributes.
3355 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3356 if (FnAttrs & ObsoleteFuncAttrs) {
3357 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3358 FnAttrs &= ~ObsoleteFuncAttrs;
3359 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003360
Chris Lattnerdf986172009-01-02 07:01:27 +00003361 // Set up the Attributes for the function.
3362 SmallVector<AttributeWithIndex, 8> Attrs;
3363 if (RetAttrs != Attribute::None)
3364 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003365
Chris Lattnerdf986172009-01-02 07:01:27 +00003366 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003367
Chris Lattnerdf986172009-01-02 07:01:27 +00003368 // Loop through FunctionType's arguments and ensure they are specified
3369 // correctly. Also, gather any parameter attributes.
3370 FunctionType::param_iterator I = Ty->param_begin();
3371 FunctionType::param_iterator E = Ty->param_end();
3372 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3373 const Type *ExpectedTy = 0;
3374 if (I != E) {
3375 ExpectedTy = *I++;
3376 } else if (!Ty->isVarArg()) {
3377 return Error(ArgList[i].Loc, "too many arguments specified");
3378 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003379
Chris Lattnerdf986172009-01-02 07:01:27 +00003380 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3381 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3382 ExpectedTy->getDescription() + "'");
3383 Args.push_back(ArgList[i].V);
3384 if (ArgList[i].Attrs != Attribute::None)
3385 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3386 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003387
Chris Lattnerdf986172009-01-02 07:01:27 +00003388 if (I != E)
3389 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003390
Chris Lattnerdf986172009-01-02 07:01:27 +00003391 if (FnAttrs != Attribute::None)
3392 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003393
Chris Lattnerdf986172009-01-02 07:01:27 +00003394 // Finish off the Attributes and check them
3395 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003396
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003397 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003398 Args.begin(), Args.end());
3399 II->setCallingConv(CC);
3400 II->setAttributes(PAL);
3401 Inst = II;
3402 return false;
3403}
3404
3405
3406
3407//===----------------------------------------------------------------------===//
3408// Binary Operators.
3409//===----------------------------------------------------------------------===//
3410
3411/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003412/// ::= ArithmeticOps TypeAndValue ',' Value
3413///
3414/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3415/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003416bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003417 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003418 LocTy Loc; Value *LHS, *RHS;
3419 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3420 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3421 ParseValue(LHS->getType(), RHS, PFS))
3422 return true;
3423
Chris Lattnere914b592009-01-05 08:24:46 +00003424 bool Valid;
3425 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003426 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003427 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003428 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3429 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003430 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003431 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3432 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003433 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003434
Chris Lattnere914b592009-01-05 08:24:46 +00003435 if (!Valid)
3436 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003437
Chris Lattnerdf986172009-01-02 07:01:27 +00003438 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3439 return false;
3440}
3441
3442/// ParseLogical
3443/// ::= ArithmeticOps TypeAndValue ',' Value {
3444bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3445 unsigned Opc) {
3446 LocTy Loc; Value *LHS, *RHS;
3447 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3448 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3449 ParseValue(LHS->getType(), RHS, PFS))
3450 return true;
3451
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003452 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003453 return Error(Loc,"instruction requires integer or integer vector operands");
3454
3455 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3456 return false;
3457}
3458
3459
3460/// ParseCompare
3461/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3462/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003463bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3464 unsigned Opc) {
3465 // Parse the integer/fp comparison predicate.
3466 LocTy Loc;
3467 unsigned Pred;
3468 Value *LHS, *RHS;
3469 if (ParseCmpPredicate(Pred, Opc) ||
3470 ParseTypeAndValue(LHS, Loc, PFS) ||
3471 ParseToken(lltok::comma, "expected ',' after compare value") ||
3472 ParseValue(LHS->getType(), RHS, PFS))
3473 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003474
Chris Lattnerdf986172009-01-02 07:01:27 +00003475 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003476 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003477 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003478 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003479 } else {
3480 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003481 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003482 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003483 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003484 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003485 }
3486 return false;
3487}
3488
3489//===----------------------------------------------------------------------===//
3490// Other Instructions.
3491//===----------------------------------------------------------------------===//
3492
3493
3494/// ParseCast
3495/// ::= CastOpc TypeAndValue 'to' Type
3496bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3497 unsigned Opc) {
3498 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003499 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003500 if (ParseTypeAndValue(Op, Loc, PFS) ||
3501 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3502 ParseType(DestTy))
3503 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003504
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003505 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3506 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003507 return Error(Loc, "invalid cast opcode for cast from '" +
3508 Op->getType()->getDescription() + "' to '" +
3509 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003510 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003511 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3512 return false;
3513}
3514
3515/// ParseSelect
3516/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3517bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3518 LocTy Loc;
3519 Value *Op0, *Op1, *Op2;
3520 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3521 ParseToken(lltok::comma, "expected ',' after select condition") ||
3522 ParseTypeAndValue(Op1, PFS) ||
3523 ParseToken(lltok::comma, "expected ',' after select value") ||
3524 ParseTypeAndValue(Op2, PFS))
3525 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003526
Chris Lattnerdf986172009-01-02 07:01:27 +00003527 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3528 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003529
Chris Lattnerdf986172009-01-02 07:01:27 +00003530 Inst = SelectInst::Create(Op0, Op1, Op2);
3531 return false;
3532}
3533
Chris Lattner0088a5c2009-01-05 08:18:44 +00003534/// ParseVA_Arg
3535/// ::= 'va_arg' TypeAndValue ',' Type
3536bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003537 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003538 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003539 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003540 if (ParseTypeAndValue(Op, PFS) ||
3541 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003542 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003543 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003544
Chris Lattner0088a5c2009-01-05 08:18:44 +00003545 if (!EltTy->isFirstClassType())
3546 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003547
3548 Inst = new VAArgInst(Op, EltTy);
3549 return false;
3550}
3551
3552/// ParseExtractElement
3553/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3554bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3555 LocTy Loc;
3556 Value *Op0, *Op1;
3557 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3558 ParseToken(lltok::comma, "expected ',' after extract value") ||
3559 ParseTypeAndValue(Op1, PFS))
3560 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003561
Chris Lattnerdf986172009-01-02 07:01:27 +00003562 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3563 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003564
Eric Christophera3500da2009-07-25 02:28:41 +00003565 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003566 return false;
3567}
3568
3569/// ParseInsertElement
3570/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3571bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3572 LocTy Loc;
3573 Value *Op0, *Op1, *Op2;
3574 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3575 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3576 ParseTypeAndValue(Op1, PFS) ||
3577 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3578 ParseTypeAndValue(Op2, PFS))
3579 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003580
Chris Lattnerdf986172009-01-02 07:01:27 +00003581 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003582 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003583
Chris Lattnerdf986172009-01-02 07:01:27 +00003584 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3585 return false;
3586}
3587
3588/// ParseShuffleVector
3589/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3590bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3591 LocTy Loc;
3592 Value *Op0, *Op1, *Op2;
3593 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3594 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3595 ParseTypeAndValue(Op1, PFS) ||
3596 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3597 ParseTypeAndValue(Op2, PFS))
3598 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003599
Chris Lattnerdf986172009-01-02 07:01:27 +00003600 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3601 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003602
Chris Lattnerdf986172009-01-02 07:01:27 +00003603 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3604 return false;
3605}
3606
3607/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003608/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003609int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003610 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003611 Value *Op0, *Op1;
3612 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003613
Chris Lattnerdf986172009-01-02 07:01:27 +00003614 if (ParseType(Ty) ||
3615 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3616 ParseValue(Ty, Op0, PFS) ||
3617 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003618 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003619 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3620 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003621
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003622 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003623 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3624 while (1) {
3625 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003626
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003627 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003628 break;
3629
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003630 if (Lex.getKind() == lltok::MetadataVar) {
3631 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003632 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003633 }
Devang Patela43d46f2009-10-16 18:45:49 +00003634
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003635 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003636 ParseValue(Ty, Op0, PFS) ||
3637 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003638 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003639 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3640 return true;
3641 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003642
Chris Lattnerdf986172009-01-02 07:01:27 +00003643 if (!Ty->isFirstClassType())
3644 return Error(TypeLoc, "phi node must have first class type");
3645
3646 PHINode *PN = PHINode::Create(Ty);
3647 PN->reserveOperandSpace(PHIVals.size());
3648 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3649 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3650 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003651 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003652}
3653
3654/// ParseCall
3655/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3656/// ParameterList OptionalAttrs
3657bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3658 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003659 unsigned RetAttrs, FnAttrs;
3660 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003661 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003662 LocTy RetTypeLoc;
3663 ValID CalleeID;
3664 SmallVector<ParamInfo, 16> ArgList;
3665 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003666
Chris Lattnerdf986172009-01-02 07:01:27 +00003667 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3668 ParseOptionalCallingConv(CC) ||
3669 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003670 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003671 ParseValID(CalleeID) ||
3672 ParseParameterList(ArgList, PFS) ||
3673 ParseOptionalAttrs(FnAttrs, 2))
3674 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003675
Chris Lattnerdf986172009-01-02 07:01:27 +00003676 // If RetType is a non-function pointer type, then this is the short syntax
3677 // for the call, which means that RetType is just the return type. Infer the
3678 // rest of the function argument types from the arguments that are present.
3679 const PointerType *PFTy = 0;
3680 const FunctionType *Ty = 0;
3681 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3682 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3683 // Pull out the types of all of the arguments...
3684 std::vector<const Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003685 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3686 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003687
Chris Lattnerdf986172009-01-02 07:01:27 +00003688 if (!FunctionType::isValidReturnType(RetType))
3689 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003690
Owen Andersondebcb012009-07-29 22:17:13 +00003691 Ty = FunctionType::get(RetType, ParamTypes, false);
3692 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003693 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003694
Chris Lattnerdf986172009-01-02 07:01:27 +00003695 // Look up the callee.
3696 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003697 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003698
Chris Lattnerdf986172009-01-02 07:01:27 +00003699 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3700 // function attributes.
3701 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3702 if (FnAttrs & ObsoleteFuncAttrs) {
3703 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3704 FnAttrs &= ~ObsoleteFuncAttrs;
3705 }
3706
3707 // Set up the Attributes for the function.
3708 SmallVector<AttributeWithIndex, 8> Attrs;
3709 if (RetAttrs != Attribute::None)
3710 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003711
Chris Lattnerdf986172009-01-02 07:01:27 +00003712 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003713
Chris Lattnerdf986172009-01-02 07:01:27 +00003714 // Loop through FunctionType's arguments and ensure they are specified
3715 // correctly. Also, gather any parameter attributes.
3716 FunctionType::param_iterator I = Ty->param_begin();
3717 FunctionType::param_iterator E = Ty->param_end();
3718 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3719 const Type *ExpectedTy = 0;
3720 if (I != E) {
3721 ExpectedTy = *I++;
3722 } else if (!Ty->isVarArg()) {
3723 return Error(ArgList[i].Loc, "too many arguments specified");
3724 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003725
Chris Lattnerdf986172009-01-02 07:01:27 +00003726 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3727 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3728 ExpectedTy->getDescription() + "'");
3729 Args.push_back(ArgList[i].V);
3730 if (ArgList[i].Attrs != Attribute::None)
3731 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3732 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003733
Chris Lattnerdf986172009-01-02 07:01:27 +00003734 if (I != E)
3735 return Error(CallLoc, "not enough parameters specified for call");
3736
3737 if (FnAttrs != Attribute::None)
3738 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3739
3740 // Finish off the Attributes and check them
3741 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003742
Chris Lattnerdf986172009-01-02 07:01:27 +00003743 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3744 CI->setTailCall(isTail);
3745 CI->setCallingConv(CC);
3746 CI->setAttributes(PAL);
3747 Inst = CI;
3748 return false;
3749}
3750
3751//===----------------------------------------------------------------------===//
3752// Memory Instructions.
3753//===----------------------------------------------------------------------===//
3754
3755/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003756/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3757/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003758int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3759 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003760 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003761 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003762 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003763 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003764 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003765
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003766 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003767 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003768 if (Lex.getKind() == lltok::kw_align) {
3769 if (ParseOptionalAlignment(Alignment)) return true;
3770 } else if (Lex.getKind() == lltok::MetadataVar) {
3771 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003772 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003773 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3774 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3775 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003776 }
3777 }
3778
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003779 if (Size && !Size->getType()->isIntegerTy())
3780 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003781
Victor Hernandez68afa542009-10-21 19:11:40 +00003782 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003783 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003784 return AteExtraComma ? InstExtraComma : InstNormal;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003785 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003786
3787 // Autoupgrade old malloc instruction to malloc call.
3788 // FIXME: Remove in LLVM 3.0.
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003789 if (Size && !Size->getType()->isIntegerTy(32))
3790 return Error(SizeLoc, "element count must be i32");
Victor Hernandez68afa542009-10-21 19:11:40 +00003791 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003792 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3793 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
Victor Hernandez68afa542009-10-21 19:11:40 +00003794 if (!MallocF)
3795 // Prototype malloc as "void *(int32)".
3796 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003797 MallocF = cast<Function>(
3798 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003799 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003800return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003801}
3802
3803/// ParseFree
3804/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003805bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3806 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003807 Value *Val; LocTy Loc;
3808 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003809 if (!Val->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003810 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003811 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003812 return false;
3813}
3814
3815/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003816/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003817int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3818 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003819 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003820 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003821 bool AteExtraComma = false;
3822 if (ParseTypeAndValue(Val, Loc, PFS) ||
3823 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3824 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003825
Duncan Sands1df98592010-02-16 11:11:14 +00003826 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003827 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3828 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003829
Chris Lattnerdf986172009-01-02 07:01:27 +00003830 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003831 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003832}
3833
3834/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003835/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003836int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3837 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003838 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003839 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003840 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003841 if (ParseTypeAndValue(Val, Loc, PFS) ||
3842 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003843 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3844 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003845 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003846
Duncan Sands1df98592010-02-16 11:11:14 +00003847 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003848 return Error(PtrLoc, "store operand must be a pointer");
3849 if (!Val->getType()->isFirstClassType())
3850 return Error(Loc, "store operand must be a first class value");
3851 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3852 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003853
Chris Lattnerdf986172009-01-02 07:01:27 +00003854 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003855 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003856}
3857
3858/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003859/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003860/// FIXME: Remove support for getresult in LLVM 3.0
3861bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3862 Value *Val; LocTy ValLoc, EltLoc;
3863 unsigned Element;
3864 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3865 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003866 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003867 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003868
Duncan Sands1df98592010-02-16 11:11:14 +00003869 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003870 return Error(ValLoc, "getresult inst requires an aggregate operand");
3871 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3872 return Error(EltLoc, "invalid getresult index for value");
3873 Inst = ExtractValueInst::Create(Val, Element);
3874 return false;
3875}
3876
3877/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003878/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003879int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003880 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003881
Dan Gohmandcb40a32009-07-29 15:58:36 +00003882 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003883
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003884 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003885
Duncan Sands1df98592010-02-16 11:11:14 +00003886 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003887 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003888
Chris Lattnerdf986172009-01-02 07:01:27 +00003889 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003890 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003891 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003892 if (Lex.getKind() == lltok::MetadataVar) {
3893 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003894 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003895 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003896 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003897 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003898 return Error(EltLoc, "getelementptr index must be an integer");
3899 Indices.push_back(Val);
3900 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003901
Chris Lattnerdf986172009-01-02 07:01:27 +00003902 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3903 Indices.begin(), Indices.end()))
3904 return Error(Loc, "invalid getelementptr indices");
3905 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003906 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003907 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003908 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003909}
3910
3911/// ParseExtractValue
3912/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003913int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003914 Value *Val; LocTy Loc;
3915 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003916 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003917 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003918 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003919 return true;
3920
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003921 if (!Val->getType()->isAggregateType())
3922 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003923
3924 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3925 Indices.end()))
3926 return Error(Loc, "invalid indices for extractvalue");
3927 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003928 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003929}
3930
3931/// ParseInsertValue
3932/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003933int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003934 Value *Val0, *Val1; LocTy Loc0, Loc1;
3935 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003936 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003937 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3938 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3939 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003940 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003941 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003942
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003943 if (!Val0->getType()->isAggregateType())
3944 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003945
Chris Lattnerdf986172009-01-02 07:01:27 +00003946 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3947 Indices.end()))
3948 return Error(Loc0, "invalid indices for insertvalue");
3949 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003950 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003951}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003952
3953//===----------------------------------------------------------------------===//
3954// Embedded metadata.
3955//===----------------------------------------------------------------------===//
3956
3957/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003958/// ::= Element (',' Element)*
3959/// Element
3960/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003961bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003962 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003963 // Check for an empty list.
3964 if (Lex.getKind() == lltok::rbrace)
3965 return false;
3966
Nick Lewycky21cc4462009-04-04 07:22:01 +00003967 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003968 // Null is a special case since it is typeless.
3969 if (EatIfPresent(lltok::kw_null)) {
3970 Elts.push_back(0);
3971 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003972 }
Chris Lattnera7352392009-12-30 04:42:57 +00003973
3974 Value *V = 0;
3975 PATypeHolder Ty(Type::getVoidTy(Context));
3976 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00003977 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00003978 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00003979 return true;
3980
Nick Lewyckycb337992009-05-10 20:57:05 +00003981 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003982 } while (EatIfPresent(lltok::comma));
3983
3984 return false;
3985}