blob: 403fdd4527d53ce0d7af2ffc979a21abb90260b9 [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"
Torok Edwinc25e7582009-07-11 20:10:48 +000025#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000026#include "llvm/Support/raw_ostream.h"
27using namespace llvm;
28
Chris Lattner3ed88ef2009-01-02 08:05:26 +000029/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000030bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000031 // Prime the lexer.
32 Lex.Lex();
33
Chris Lattnerad7d1e22009-01-04 20:44:11 +000034 return ParseTopLevelEntities() ||
35 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000036}
37
38/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
39/// module.
40bool LLParser::ValidateEndOfModule() {
Chris Lattner449c3102010-04-01 05:14:45 +000041 // Handle any instruction metadata forward references.
42 if (!ForwardRefInstMetadata.empty()) {
43 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
44 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
45 I != E; ++I) {
46 Instruction *Inst = I->first;
47 const std::vector<MDRef> &MDList = I->second;
48
49 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
50 unsigned SlotNo = MDList[i].MDSlot;
51
52 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
53 return Error(MDList[i].Loc, "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +000054 Twine(SlotNo) + "'");
Chris Lattner449c3102010-04-01 05:14:45 +000055 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
56 }
57 }
58 ForwardRefInstMetadata.clear();
59 }
60
61
Victor Hernandez68afa542009-10-21 19:11:40 +000062 // Update auto-upgraded malloc calls to "malloc".
Chris Lattnercf4d2f12009-10-18 05:09:15 +000063 // FIXME: Remove in LLVM 3.0.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000064 if (MallocF) {
65 MallocF->setName("malloc");
66 // If setName() does not set the name to "malloc", then there is already a
67 // declaration of "malloc". In that case, iterate over all calls to MallocF
68 // and get them to call the declared "malloc" instead.
69 if (MallocF->getName() != "malloc") {
Chris Lattner09d9ef42009-10-28 03:39:23 +000070 Constant *RealMallocF = M->getFunction("malloc");
Victor Hernandez68afa542009-10-21 19:11:40 +000071 if (RealMallocF->getType() != MallocF->getType())
72 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
73 MallocF->replaceAllUsesWith(RealMallocF);
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000074 MallocF->eraseFromParent();
75 MallocF = NULL;
76 }
77 }
Chris Lattner09d9ef42009-10-28 03:39:23 +000078
79
80 // If there are entries in ForwardRefBlockAddresses at this point, they are
81 // references after the function was defined. Resolve those now.
82 while (!ForwardRefBlockAddresses.empty()) {
83 // Okay, we are referencing an already-parsed function, resolve them now.
84 Function *TheFn = 0;
85 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
86 if (Fn.Kind == ValID::t_GlobalName)
87 TheFn = M->getFunction(Fn.StrVal);
88 else if (Fn.UIntVal < NumberedVals.size())
89 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
90
91 if (TheFn == 0)
92 return Error(Fn.Loc, "unknown function referenced by blockaddress");
93
94 // Resolve all these references.
95 if (ResolveForwardRefBlockAddresses(TheFn,
96 ForwardRefBlockAddresses.begin()->second,
97 0))
98 return true;
99
100 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
101 }
102
103
Chris Lattnerdf986172009-01-02 07:01:27 +0000104 if (!ForwardRefTypes.empty())
105 return Error(ForwardRefTypes.begin()->second.second,
106 "use of undefined type named '" +
107 ForwardRefTypes.begin()->first + "'");
108 if (!ForwardRefTypeIDs.empty())
109 return Error(ForwardRefTypeIDs.begin()->second.second,
110 "use of undefined type '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000111 Twine(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000112
Chris Lattnerdf986172009-01-02 07:01:27 +0000113 if (!ForwardRefVals.empty())
114 return Error(ForwardRefVals.begin()->second.second,
115 "use of undefined value '@" + ForwardRefVals.begin()->first +
116 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000117
Chris Lattnerdf986172009-01-02 07:01:27 +0000118 if (!ForwardRefValIDs.empty())
119 return Error(ForwardRefValIDs.begin()->second.second,
120 "use of undefined value '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000121 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000122
Devang Patel1c7eea62009-07-08 19:23:54 +0000123 if (!ForwardRefMDNodes.empty())
124 return Error(ForwardRefMDNodes.begin()->second.second,
125 "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000126 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000127
Devang Patel1c7eea62009-07-08 19:23:54 +0000128
Chris Lattnerdf986172009-01-02 07:01:27 +0000129 // Look for intrinsic functions and CallInst that need to be upgraded
130 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
131 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000132
Devang Patele4b27562009-08-28 23:24:31 +0000133 // Check debug info intrinsics.
134 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000135 return false;
136}
137
Chris Lattner09d9ef42009-10-28 03:39:23 +0000138bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
139 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
140 PerFunctionState *PFS) {
141 // Loop over all the references, resolving them.
142 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
143 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000144 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000145 if (Refs[i].first.Kind == ValID::t_LocalName)
146 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000147 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000148 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
149 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
150 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000151 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000152 } else {
153 Res = dyn_cast_or_null<BasicBlock>(
154 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
155 }
156
Chris Lattnercdfc9402009-11-01 01:27:45 +0000157 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000158 return Error(Refs[i].first.Loc,
159 "referenced value is not a basic block");
160
161 // Get the BlockAddress for this and update references to use it.
162 BlockAddress *BA = BlockAddress::get(TheFn, Res);
163 Refs[i].second->replaceAllUsesWith(BA);
164 Refs[i].second->eraseFromParent();
165 }
166 return false;
167}
168
169
Chris Lattnerdf986172009-01-02 07:01:27 +0000170//===----------------------------------------------------------------------===//
171// Top-Level Entities
172//===----------------------------------------------------------------------===//
173
174bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000175 while (1) {
176 switch (Lex.getKind()) {
177 default: return TokError("expected top-level entity");
178 case lltok::Eof: return false;
179 //case lltok::kw_define:
180 case lltok::kw_declare: if (ParseDeclare()) return true; break;
181 case lltok::kw_define: if (ParseDefine()) return true; break;
182 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
183 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
184 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
185 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000186 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000187 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
188 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000189 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000190 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000191 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000192 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000193
194 // The Global variable production with no name can have many different
195 // optional leading prefixes, the production is:
196 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
197 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000198 case lltok::kw_private: // OptionalLinkage
199 case lltok::kw_linker_private: // OptionalLinkage
200 case lltok::kw_linker_private_weak: // OptionalLinkage
Bill Wendling55ae5152010-08-20 22:05:50 +0000201 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
Bill Wendling5e721d72010-07-01 21:55:59 +0000202 case lltok::kw_internal: // OptionalLinkage
203 case lltok::kw_weak: // OptionalLinkage
204 case lltok::kw_weak_odr: // OptionalLinkage
205 case lltok::kw_linkonce: // OptionalLinkage
206 case lltok::kw_linkonce_odr: // OptionalLinkage
207 case lltok::kw_appending: // OptionalLinkage
208 case lltok::kw_dllexport: // OptionalLinkage
209 case lltok::kw_common: // OptionalLinkage
210 case lltok::kw_dllimport: // OptionalLinkage
211 case lltok::kw_extern_weak: // OptionalLinkage
212 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000213 unsigned Linkage, Visibility;
214 if (ParseOptionalLinkage(Linkage) ||
215 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000216 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000217 return true;
218 break;
219 }
220 case lltok::kw_default: // OptionalVisibility
221 case lltok::kw_hidden: // OptionalVisibility
222 case lltok::kw_protected: { // OptionalVisibility
223 unsigned Visibility;
224 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000225 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000226 return true;
227 break;
228 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000229
Chris Lattnerdf986172009-01-02 07:01:27 +0000230 case lltok::kw_thread_local: // OptionalThreadLocal
231 case lltok::kw_addrspace: // OptionalAddrSpace
232 case lltok::kw_constant: // GlobalType
233 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000234 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000235 break;
236 }
237 }
238}
239
240
241/// toplevelentity
242/// ::= 'module' 'asm' STRINGCONSTANT
243bool LLParser::ParseModuleAsm() {
244 assert(Lex.getKind() == lltok::kw_module);
245 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000246
247 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000248 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
249 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000250
Chris Lattnerdf986172009-01-02 07:01:27 +0000251 const std::string &AsmSoFar = M->getModuleInlineAsm();
252 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000253 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000254 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000255 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000256 return false;
257}
258
259/// toplevelentity
260/// ::= 'target' 'triple' '=' STRINGCONSTANT
261/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
262bool LLParser::ParseTargetDefinition() {
263 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000264 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000265 switch (Lex.Lex()) {
266 default: return TokError("unknown target property");
267 case lltok::kw_triple:
268 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000269 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
270 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000271 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000272 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000273 return false;
274 case lltok::kw_datalayout:
275 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000276 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
277 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000278 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000279 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000280 return false;
281 }
282}
283
284/// toplevelentity
285/// ::= 'deplibs' '=' '[' ']'
286/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
287bool LLParser::ParseDepLibs() {
288 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000289 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000290 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
291 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
292 return true;
293
294 if (EatIfPresent(lltok::rsquare))
295 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000296
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000297 std::string Str;
298 if (ParseStringConstant(Str)) return true;
299 M->addLibrary(Str);
300
301 while (EatIfPresent(lltok::comma)) {
302 if (ParseStringConstant(Str)) return true;
303 M->addLibrary(Str);
304 }
305
306 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000307}
308
Dan Gohman3845e502009-08-12 23:32:33 +0000309/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000310/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000311/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000312bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000313 unsigned TypeID = NumberedTypes.size();
314
315 // Handle the LocalVarID form.
316 if (Lex.getKind() == lltok::LocalVarID) {
317 if (Lex.getUIntVal() != TypeID)
318 return Error(Lex.getLoc(), "type expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000319 Twine(TypeID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000320 Lex.Lex(); // eat LocalVarID;
321
322 if (ParseToken(lltok::equal, "expected '=' after name"))
323 return true;
324 }
325
Chris Lattnerdf986172009-01-02 07:01:27 +0000326 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerf7240de2010-04-10 18:01:25 +0000327 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000328
Owen Anderson1d0be152009-08-13 21:58:54 +0000329 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000330 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000331
Chris Lattnerdf986172009-01-02 07:01:27 +0000332 // See if this type was previously referenced.
333 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
334 FI = ForwardRefTypeIDs.find(TypeID);
335 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000336 if (FI->second.first.get() == Ty)
337 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000338
Chris Lattnerdf986172009-01-02 07:01:27 +0000339 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
340 Ty = FI->second.first.get();
341 ForwardRefTypeIDs.erase(FI);
342 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000343
Chris Lattnerdf986172009-01-02 07:01:27 +0000344 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000345
Chris Lattnerdf986172009-01-02 07:01:27 +0000346 return false;
347}
348
349/// toplevelentity
350/// ::= LocalVar '=' 'type' type
351bool LLParser::ParseNamedType() {
352 std::string Name = Lex.getStrVal();
353 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000354 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000355
Owen Anderson1d0be152009-08-13 21:58:54 +0000356 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000357
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000358 if (ParseToken(lltok::equal, "expected '=' after name") ||
359 ParseToken(lltok::kw_type, "expected 'type' after name") ||
360 ParseType(Ty))
361 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000362
Chris Lattnerdf986172009-01-02 07:01:27 +0000363 // Set the type name, checking for conflicts as we do so.
364 bool AlreadyExists = M->addTypeName(Name, Ty);
365 if (!AlreadyExists) return false;
366
367 // See if this type is a forward reference. We need to eagerly resolve
368 // types to allow recursive type redefinitions below.
369 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
370 FI = ForwardRefTypes.find(Name);
371 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000372 if (FI->second.first.get() == Ty)
373 return Error(NameLoc, "self referential type is invalid");
374
Chris Lattnerdf986172009-01-02 07:01:27 +0000375 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
376 Ty = FI->second.first.get();
377 ForwardRefTypes.erase(FI);
378 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000379
Chris Lattnerdf986172009-01-02 07:01:27 +0000380 // Inserting a name that is already defined, get the existing name.
381 const Type *Existing = M->getTypeByName(Name);
382 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000383
Chris Lattnerdf986172009-01-02 07:01:27 +0000384 // Otherwise, this is an attempt to redefine a type. That's okay if
385 // the redefinition is identical to the original.
386 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
387 if (Existing == Ty) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000388
Chris Lattnerdf986172009-01-02 07:01:27 +0000389 // Any other kind of (non-equivalent) redefinition is an error.
390 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
391 Ty->getDescription() + "'");
392}
393
394
395/// toplevelentity
396/// ::= 'declare' FunctionHeader
397bool LLParser::ParseDeclare() {
398 assert(Lex.getKind() == lltok::kw_declare);
399 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000400
Chris Lattnerdf986172009-01-02 07:01:27 +0000401 Function *F;
402 return ParseFunctionHeader(F, false);
403}
404
405/// toplevelentity
406/// ::= 'define' FunctionHeader '{' ...
407bool LLParser::ParseDefine() {
408 assert(Lex.getKind() == lltok::kw_define);
409 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000410
Chris Lattnerdf986172009-01-02 07:01:27 +0000411 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000412 return ParseFunctionHeader(F, true) ||
413 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000414}
415
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000416/// ParseGlobalType
417/// ::= 'constant'
418/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000419bool LLParser::ParseGlobalType(bool &IsConstant) {
420 if (Lex.getKind() == lltok::kw_constant)
421 IsConstant = true;
422 else if (Lex.getKind() == lltok::kw_global)
423 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000424 else {
425 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000426 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000427 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000428 Lex.Lex();
429 return false;
430}
431
Dan Gohman3845e502009-08-12 23:32:33 +0000432/// ParseUnnamedGlobal:
433/// OptionalVisibility ALIAS ...
434/// OptionalLinkage OptionalVisibility ... -> global variable
435/// GlobalID '=' OptionalVisibility ALIAS ...
436/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
437bool LLParser::ParseUnnamedGlobal() {
438 unsigned VarID = NumberedVals.size();
439 std::string Name;
440 LocTy NameLoc = Lex.getLoc();
441
442 // Handle the GlobalID form.
443 if (Lex.getKind() == lltok::GlobalID) {
444 if (Lex.getUIntVal() != VarID)
445 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000446 Twine(VarID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000447 Lex.Lex(); // eat GlobalID;
448
449 if (ParseToken(lltok::equal, "expected '=' after name"))
450 return true;
451 }
452
453 bool HasLinkage;
454 unsigned Linkage, Visibility;
455 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
456 ParseOptionalVisibility(Visibility))
457 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000458
Dan Gohman3845e502009-08-12 23:32:33 +0000459 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
460 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
461 return ParseAlias(Name, NameLoc, Visibility);
462}
463
Chris Lattnerdf986172009-01-02 07:01:27 +0000464/// ParseNamedGlobal:
465/// GlobalVar '=' OptionalVisibility ALIAS ...
466/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
467bool LLParser::ParseNamedGlobal() {
468 assert(Lex.getKind() == lltok::GlobalVar);
469 LocTy NameLoc = Lex.getLoc();
470 std::string Name = Lex.getStrVal();
471 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000472
Chris Lattnerdf986172009-01-02 07:01:27 +0000473 bool HasLinkage;
474 unsigned Linkage, Visibility;
475 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
476 ParseOptionalLinkage(Linkage, HasLinkage) ||
477 ParseOptionalVisibility(Visibility))
478 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000479
Chris Lattnerdf986172009-01-02 07:01:27 +0000480 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
481 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
482 return ParseAlias(Name, NameLoc, Visibility);
483}
484
Devang Patel256be962009-07-20 19:00:08 +0000485// MDString:
486// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000487bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000488 std::string Str;
489 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000490 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000491 return false;
492}
493
494// MDNode:
495// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000496//
497/// This version of ParseMDNodeID returns the slot number and null in the case
498/// of a forward reference.
499bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
500 // !{ ..., !42, ... }
501 if (ParseUInt32(SlotNo)) return true;
502
503 // Check existing MDNode.
504 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
505 Result = NumberedMetadata[SlotNo];
506 else
507 Result = 0;
508 return false;
509}
510
Chris Lattner4a72efc2009-12-30 04:15:23 +0000511bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000512 // !{ ..., !42, ... }
513 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000514 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000515
Chris Lattner449c3102010-04-01 05:14:45 +0000516 // If not a forward reference, just return it now.
517 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000518
Chris Lattner449c3102010-04-01 05:14:45 +0000519 // Otherwise, create MDNode forward reference.
Dan Gohman489b29b2010-08-20 22:02:26 +0000520 MDNode *FwdNode = MDNode::getTemporary(Context, 0, 0);
Devang Patel256be962009-07-20 19:00:08 +0000521 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000522
523 if (NumberedMetadata.size() <= MID)
524 NumberedMetadata.resize(MID+1);
525 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000526 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000527 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000528}
Devang Patel256be962009-07-20 19:00:08 +0000529
Chris Lattner84d03b12009-12-29 22:35:39 +0000530/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000531/// !foo = !{ !1, !2 }
532bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000533 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000534 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000535 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000536
Chris Lattner84d03b12009-12-29 22:35:39 +0000537 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000538 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000539 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000540 return true;
541
Dan Gohman17aa92c2010-07-21 23:38:33 +0000542 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000543 if (Lex.getKind() != lltok::rbrace)
544 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000545 if (ParseToken(lltok::exclaim, "Expected '!' here"))
546 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000547
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000548 MDNode *N = 0;
549 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000550 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000551 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000552
553 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
554 return true;
555
Devang Pateleff2ab62009-07-29 00:34:02 +0000556 return false;
557}
558
Devang Patel923078c2009-07-01 19:21:12 +0000559/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000560/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000561bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000562 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000563 Lex.Lex();
564 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000565
566 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000567 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000568 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000569 if (ParseUInt32(MetadataID) ||
570 ParseToken(lltok::equal, "expected '=' here") ||
571 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000572 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000573 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000574 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000575 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000576 return true;
577
Owen Anderson647e3012009-07-31 21:35:40 +0000578 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000579
580 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000581 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000582 FI = ForwardRefMDNodes.find(MetadataID);
583 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000584 MDNode *Temp = FI->second.first;
585 Temp->replaceAllUsesWith(Init);
586 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000587 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000588
589 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
590 } else {
591 if (MetadataID >= NumberedMetadata.size())
592 NumberedMetadata.resize(MetadataID+1);
593
594 if (NumberedMetadata[MetadataID] != 0)
595 return TokError("Metadata id is already used");
596 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000597 }
598
Devang Patel923078c2009-07-01 19:21:12 +0000599 return false;
600}
601
Chris Lattnerdf986172009-01-02 07:01:27 +0000602/// ParseAlias:
603/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
604/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000605/// ::= TypeAndValue
606/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000607/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000608///
609/// Everything through visibility has already been parsed.
610///
611bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
612 unsigned Visibility) {
613 assert(Lex.getKind() == lltok::kw_alias);
614 Lex.Lex();
615 unsigned Linkage;
616 LocTy LinkageLoc = Lex.getLoc();
617 if (ParseOptionalLinkage(Linkage))
618 return true;
619
620 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000621 Linkage != GlobalValue::WeakAnyLinkage &&
622 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000623 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000624 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000625 Linkage != GlobalValue::LinkerPrivateLinkage &&
Bill Wendling55ae5152010-08-20 22:05:50 +0000626 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
627 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000628 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000629
Chris Lattnerdf986172009-01-02 07:01:27 +0000630 Constant *Aliasee;
631 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000632 if (Lex.getKind() != lltok::kw_bitcast &&
633 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000634 if (ParseGlobalTypeAndValue(Aliasee)) return true;
635 } else {
636 // The bitcast dest type is not present, it is implied by the dest type.
637 ValID ID;
638 if (ParseValID(ID)) return true;
639 if (ID.Kind != ValID::t_Constant)
640 return Error(AliaseeLoc, "invalid aliasee");
641 Aliasee = ID.ConstantVal;
642 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000643
Duncan Sands1df98592010-02-16 11:11:14 +0000644 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000645 return Error(AliaseeLoc, "alias must have pointer type");
646
647 // Okay, create the alias but do not insert it into the module yet.
648 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
649 (GlobalValue::LinkageTypes)Linkage, Name,
650 Aliasee);
651 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000652
Chris Lattnerdf986172009-01-02 07:01:27 +0000653 // See if this value already exists in the symbol table. If so, it is either
654 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000655 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000656 // See if this was a redefinition. If so, there is no entry in
657 // ForwardRefVals.
658 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
659 I = ForwardRefVals.find(Name);
660 if (I == ForwardRefVals.end())
661 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
662
663 // Otherwise, this was a definition of forward ref. Verify that types
664 // agree.
665 if (Val->getType() != GA->getType())
666 return Error(NameLoc,
667 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000668
Chris Lattnerdf986172009-01-02 07:01:27 +0000669 // If they agree, just RAUW the old value with the alias and remove the
670 // forward ref info.
671 Val->replaceAllUsesWith(GA);
672 Val->eraseFromParent();
673 ForwardRefVals.erase(I);
674 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000675
Chris Lattnerdf986172009-01-02 07:01:27 +0000676 // Insert into the module, we know its name won't collide now.
677 M->getAliasList().push_back(GA);
Benjamin Krameraf812352010-10-16 11:28:23 +0000678 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000679
Chris Lattnerdf986172009-01-02 07:01:27 +0000680 return false;
681}
682
683/// ParseGlobal
684/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
685/// OptionalAddrSpace GlobalType Type Const
686/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
687/// OptionalAddrSpace GlobalType Type Const
688///
689/// Everything through visibility has been parsed already.
690///
691bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
692 unsigned Linkage, bool HasLinkage,
693 unsigned Visibility) {
694 unsigned AddrSpace;
695 bool ThreadLocal, IsConstant;
696 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000697
Owen Anderson1d0be152009-08-13 21:58:54 +0000698 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000699 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
700 ParseOptionalAddrSpace(AddrSpace) ||
701 ParseGlobalType(IsConstant) ||
702 ParseType(Ty, TyLoc))
703 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000704
Chris Lattnerdf986172009-01-02 07:01:27 +0000705 // If the linkage is specified and is external, then no initializer is
706 // present.
707 Constant *Init = 0;
708 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000709 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000710 Linkage != GlobalValue::ExternalLinkage)) {
711 if (ParseGlobalValue(Ty, Init))
712 return true;
713 }
714
Duncan Sands1df98592010-02-16 11:11:14 +0000715 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000716 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000717
Chris Lattnerdf986172009-01-02 07:01:27 +0000718 GlobalVariable *GV = 0;
719
720 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000721 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000722 if (GlobalValue *GVal = M->getNamedValue(Name)) {
723 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
724 return Error(NameLoc, "redefinition of global '@" + Name + "'");
725 GV = cast<GlobalVariable>(GVal);
726 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000727 } else {
728 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
729 I = ForwardRefValIDs.find(NumberedVals.size());
730 if (I != ForwardRefValIDs.end()) {
731 GV = cast<GlobalVariable>(I->second.first);
732 ForwardRefValIDs.erase(I);
733 }
734 }
735
736 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000737 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000738 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000739 } else {
740 if (GV->getType()->getElementType() != Ty)
741 return Error(TyLoc,
742 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000743
Chris Lattnerdf986172009-01-02 07:01:27 +0000744 // Move the forward-reference to the correct spot in the module.
745 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
746 }
747
748 if (Name.empty())
749 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000750
Chris Lattnerdf986172009-01-02 07:01:27 +0000751 // Set the parsed properties on the global.
752 if (Init)
753 GV->setInitializer(Init);
754 GV->setConstant(IsConstant);
755 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
756 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
757 GV->setThreadLocal(ThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000758
Chris Lattnerdf986172009-01-02 07:01:27 +0000759 // Parse attributes on the global.
760 while (Lex.getKind() == lltok::comma) {
761 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000762
Chris Lattnerdf986172009-01-02 07:01:27 +0000763 if (Lex.getKind() == lltok::kw_section) {
764 Lex.Lex();
765 GV->setSection(Lex.getStrVal());
766 if (ParseToken(lltok::StringConstant, "expected global section string"))
767 return true;
768 } else if (Lex.getKind() == lltok::kw_align) {
769 unsigned Alignment;
770 if (ParseOptionalAlignment(Alignment)) return true;
771 GV->setAlignment(Alignment);
772 } else {
773 TokError("unknown global variable property!");
774 }
775 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000776
Chris Lattnerdf986172009-01-02 07:01:27 +0000777 return false;
778}
779
780
781//===----------------------------------------------------------------------===//
782// GlobalValue Reference/Resolution Routines.
783//===----------------------------------------------------------------------===//
784
785/// GetGlobalVal - Get a value with the specified name or ID, creating a
786/// forward reference record if needed. This can return null if the value
787/// exists but does not have the right type.
788GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
789 LocTy Loc) {
790 const PointerType *PTy = dyn_cast<PointerType>(Ty);
791 if (PTy == 0) {
792 Error(Loc, "global variable reference must have pointer type");
793 return 0;
794 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000795
Chris Lattnerdf986172009-01-02 07:01:27 +0000796 // Look this name up in the normal function symbol table.
797 GlobalValue *Val =
798 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000799
Chris Lattnerdf986172009-01-02 07:01:27 +0000800 // If this is a forward reference for the value, see if we already created a
801 // forward ref record.
802 if (Val == 0) {
803 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
804 I = ForwardRefVals.find(Name);
805 if (I != ForwardRefVals.end())
806 Val = I->second.first;
807 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000808
Chris Lattnerdf986172009-01-02 07:01:27 +0000809 // If we have the value in the symbol table or fwd-ref table, return it.
810 if (Val) {
811 if (Val->getType() == Ty) return Val;
812 Error(Loc, "'@" + Name + "' defined with type '" +
813 Val->getType()->getDescription() + "'");
814 return 0;
815 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000816
Chris Lattnerdf986172009-01-02 07:01:27 +0000817 // Otherwise, create a new forward reference for this value and remember it.
818 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000819 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
820 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000821 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner1e407c32009-01-08 19:05:36 +0000822 Error(Loc, "function may not return opaque type");
823 return 0;
824 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000825
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000826 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000827 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000828 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
829 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000830 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000831
Chris Lattnerdf986172009-01-02 07:01:27 +0000832 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
833 return FwdVal;
834}
835
836GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
837 const PointerType *PTy = dyn_cast<PointerType>(Ty);
838 if (PTy == 0) {
839 Error(Loc, "global variable reference must have pointer type");
840 return 0;
841 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000842
Chris Lattnerdf986172009-01-02 07:01:27 +0000843 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000844
Chris Lattnerdf986172009-01-02 07:01:27 +0000845 // If this is a forward reference for the value, see if we already created a
846 // forward ref record.
847 if (Val == 0) {
848 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
849 I = ForwardRefValIDs.find(ID);
850 if (I != ForwardRefValIDs.end())
851 Val = I->second.first;
852 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000853
Chris Lattnerdf986172009-01-02 07:01:27 +0000854 // If we have the value in the symbol table or fwd-ref table, return it.
855 if (Val) {
856 if (Val->getType() == Ty) return Val;
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000857 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +0000858 Val->getType()->getDescription() + "'");
859 return 0;
860 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000861
Chris Lattnerdf986172009-01-02 07:01:27 +0000862 // Otherwise, create a new forward reference for this value and remember it.
863 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000864 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
865 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000866 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000867 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000868 return 0;
869 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000870 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000871 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000872 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
873 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000874 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000875
Chris Lattnerdf986172009-01-02 07:01:27 +0000876 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
877 return FwdVal;
878}
879
880
881//===----------------------------------------------------------------------===//
882// Helper Routines.
883//===----------------------------------------------------------------------===//
884
885/// ParseToken - If the current token has the specified kind, eat it and return
886/// success. Otherwise, emit the specified error and return failure.
887bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
888 if (Lex.getKind() != T)
889 return TokError(ErrMsg);
890 Lex.Lex();
891 return false;
892}
893
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000894/// ParseStringConstant
895/// ::= StringConstant
896bool LLParser::ParseStringConstant(std::string &Result) {
897 if (Lex.getKind() != lltok::StringConstant)
898 return TokError("expected string constant");
899 Result = Lex.getStrVal();
900 Lex.Lex();
901 return false;
902}
903
904/// ParseUInt32
905/// ::= uint32
906bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000907 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
908 return TokError("expected integer");
909 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
910 if (Val64 != unsigned(Val64))
911 return TokError("expected 32-bit integer (too large)");
912 Val = Val64;
913 Lex.Lex();
914 return false;
915}
916
917
918/// ParseOptionalAddrSpace
919/// := /*empty*/
920/// := 'addrspace' '(' uint32 ')'
921bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
922 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000923 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000924 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000925 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000926 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000927 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000928}
Chris Lattnerdf986172009-01-02 07:01:27 +0000929
930/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
931/// indicates what kind of attribute list this is: 0: function arg, 1: result,
932/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000933/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000934bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
935 Attrs = Attribute::None;
936 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000937
Chris Lattnerdf986172009-01-02 07:01:27 +0000938 while (1) {
939 switch (Lex.getKind()) {
940 case lltok::kw_sext:
941 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000942 // Treat these as signext/zeroext if they occur in the argument list after
943 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
944 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
945 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000946 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000947 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000948 if (Lex.getKind() == lltok::kw_sext)
949 Attrs |= Attribute::SExt;
950 else
951 Attrs |= Attribute::ZExt;
952 break;
953 }
954 // FALL THROUGH.
955 default: // End of attributes.
956 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
957 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000958
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000959 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000960 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000961
Chris Lattnerdf986172009-01-02 07:01:27 +0000962 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000963 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
964 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
965 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
966 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
967 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
968 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
969 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
970 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000971
Devang Patel578efa92009-06-05 21:57:13 +0000972 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
973 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
974 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
975 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
976 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000977 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000978 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
979 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
980 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
981 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
982 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
983 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000984 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000985
Charles Davis1e063d12010-02-12 00:31:15 +0000986 case lltok::kw_alignstack: {
987 unsigned Alignment;
988 if (ParseOptionalStackAlignment(Alignment))
989 return true;
990 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
991 continue;
992 }
993
Chris Lattnerdf986172009-01-02 07:01:27 +0000994 case lltok::kw_align: {
995 unsigned Alignment;
996 if (ParseOptionalAlignment(Alignment))
997 return true;
998 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
999 continue;
1000 }
Charles Davis1e063d12010-02-12 00:31:15 +00001001
Chris Lattnerdf986172009-01-02 07:01:27 +00001002 }
1003 Lex.Lex();
1004 }
1005}
1006
1007/// ParseOptionalLinkage
1008/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001009/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001010/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +00001011/// ::= 'linker_private_weak'
Bill Wendling55ae5152010-08-20 22:05:50 +00001012/// ::= 'linker_private_weak_def_auto'
Chris Lattnerdf986172009-01-02 07:01:27 +00001013/// ::= 'internal'
1014/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001015/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001016/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001017/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +00001018/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +00001019/// ::= 'appending'
1020/// ::= 'dllexport'
1021/// ::= 'common'
1022/// ::= 'dllimport'
1023/// ::= 'extern_weak'
1024/// ::= 'external'
1025bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1026 HasLinkage = false;
1027 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001028 default: Res=GlobalValue::ExternalLinkage; return false;
1029 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1030 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001031 case lltok::kw_linker_private_weak:
1032 Res = GlobalValue::LinkerPrivateWeakLinkage;
1033 break;
Bill Wendling55ae5152010-08-20 22:05:50 +00001034 case lltok::kw_linker_private_weak_def_auto:
1035 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1036 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001037 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1038 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1039 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1040 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1041 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001042 case lltok::kw_available_externally:
1043 Res = GlobalValue::AvailableExternallyLinkage;
1044 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001045 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1046 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1047 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1048 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1049 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1050 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001051 }
1052 Lex.Lex();
1053 HasLinkage = true;
1054 return false;
1055}
1056
1057/// ParseOptionalVisibility
1058/// ::= /*empty*/
1059/// ::= 'default'
1060/// ::= 'hidden'
1061/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001062///
Chris Lattnerdf986172009-01-02 07:01:27 +00001063bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1064 switch (Lex.getKind()) {
1065 default: Res = GlobalValue::DefaultVisibility; return false;
1066 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1067 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1068 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1069 }
1070 Lex.Lex();
1071 return false;
1072}
1073
1074/// ParseOptionalCallingConv
1075/// ::= /*empty*/
1076/// ::= 'ccc'
1077/// ::= 'fastcc'
1078/// ::= 'coldcc'
1079/// ::= 'x86_stdcallcc'
1080/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001081/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001082/// ::= 'arm_apcscc'
1083/// ::= 'arm_aapcscc'
1084/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001085/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001086/// ::= 'ptx_kernel'
1087/// ::= 'ptx_device'
Chris Lattnerdf986172009-01-02 07:01:27 +00001088/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001089///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001090bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001091 switch (Lex.getKind()) {
1092 default: CC = CallingConv::C; return false;
1093 case lltok::kw_ccc: CC = CallingConv::C; break;
1094 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1095 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1096 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1097 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001098 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001099 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1100 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1101 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001102 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001103 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1104 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001105 case lltok::kw_cc: {
1106 unsigned ArbitraryCC;
1107 Lex.Lex();
1108 if (ParseUInt32(ArbitraryCC)) {
1109 return true;
1110 } else
1111 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1112 return false;
1113 }
1114 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001115 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001116
Chris Lattnerdf986172009-01-02 07:01:27 +00001117 Lex.Lex();
1118 return false;
1119}
1120
Chris Lattnerb8c46862009-12-30 05:31:19 +00001121/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001122/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001123bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1124 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001125 do {
1126 if (Lex.getKind() != lltok::MetadataVar)
1127 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001128
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001129 std::string Name = Lex.getStrVal();
Dan Gohman309b3af2010-08-24 02:24:03 +00001130 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001131 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001132
Chris Lattner442ffa12009-12-29 21:53:55 +00001133 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001134 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001135
1136 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001137 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001138
Dan Gohman68261142010-08-24 14:35:45 +00001139 // This code is similar to that of ParseMetadataValue, however it needs to
1140 // have special-case code for a forward reference; see the comments on
1141 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1142 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001143 if (Lex.getKind() == lltok::lbrace) {
1144 ValID ID;
1145 if (ParseMetadataListValue(ID, PFS))
1146 return true;
1147 assert(ID.Kind == ValID::t_MDNode);
1148 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001149 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001150 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001151 if (ParseMDNodeID(Node, NodeID))
1152 return true;
1153 if (Node) {
1154 // If we got the node, add it to the instruction.
1155 Inst->setMetadata(MDK, Node);
1156 } else {
1157 MDRef R = { Loc, MDK, NodeID };
1158 // Otherwise, remember that this should be resolved later.
1159 ForwardRefInstMetadata[Inst].push_back(R);
1160 }
Chris Lattner449c3102010-04-01 05:14:45 +00001161 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001162
1163 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001164 } while (EatIfPresent(lltok::comma));
1165 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001166}
1167
Chris Lattnerdf986172009-01-02 07:01:27 +00001168/// ParseOptionalAlignment
1169/// ::= /* empty */
1170/// ::= 'align' 4
1171bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1172 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001173 if (!EatIfPresent(lltok::kw_align))
1174 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001175 LocTy AlignLoc = Lex.getLoc();
1176 if (ParseUInt32(Alignment)) return true;
1177 if (!isPowerOf2_32(Alignment))
1178 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001179 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001180 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001181 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001182}
1183
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001184/// ParseOptionalCommaAlign
1185/// ::=
1186/// ::= ',' align 4
1187///
1188/// This returns with AteExtraComma set to true if it ate an excess comma at the
1189/// end.
1190bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1191 bool &AteExtraComma) {
1192 AteExtraComma = false;
1193 while (EatIfPresent(lltok::comma)) {
1194 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001195 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001196 AteExtraComma = true;
1197 return false;
1198 }
1199
Chris Lattner093eed12010-04-23 00:50:50 +00001200 if (Lex.getKind() != lltok::kw_align)
1201 return Error(Lex.getLoc(), "expected metadata or 'align'");
1202
Dan Gohman138aa2a2010-07-28 20:12:04 +00001203 LocTy AlignLoc = Lex.getLoc();
Chris Lattner093eed12010-04-23 00:50:50 +00001204 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001205 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001206
Devang Patelf633a062009-09-17 23:04:48 +00001207 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001208}
1209
Charles Davis1e063d12010-02-12 00:31:15 +00001210/// ParseOptionalStackAlignment
1211/// ::= /* empty */
1212/// ::= 'alignstack' '(' 4 ')'
1213bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1214 Alignment = 0;
1215 if (!EatIfPresent(lltok::kw_alignstack))
1216 return false;
1217 LocTy ParenLoc = Lex.getLoc();
1218 if (!EatIfPresent(lltok::lparen))
1219 return Error(ParenLoc, "expected '('");
1220 LocTy AlignLoc = Lex.getLoc();
1221 if (ParseUInt32(Alignment)) return true;
1222 ParenLoc = Lex.getLoc();
1223 if (!EatIfPresent(lltok::rparen))
1224 return Error(ParenLoc, "expected ')'");
1225 if (!isPowerOf2_32(Alignment))
1226 return Error(AlignLoc, "stack alignment is not a power of two");
1227 return false;
1228}
Devang Patelf633a062009-09-17 23:04:48 +00001229
Chris Lattner628c13a2009-12-30 05:14:00 +00001230/// ParseIndexList - This parses the index list for an insert/extractvalue
1231/// instruction. This sets AteExtraComma in the case where we eat an extra
1232/// comma at the end of the line and find that it is followed by metadata.
1233/// Clients that don't allow metadata can call the version of this function that
1234/// only takes one argument.
1235///
Chris Lattnerdf986172009-01-02 07:01:27 +00001236/// ParseIndexList
1237/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001238///
1239bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1240 bool &AteExtraComma) {
1241 AteExtraComma = false;
1242
Chris Lattnerdf986172009-01-02 07:01:27 +00001243 if (Lex.getKind() != lltok::comma)
1244 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001245
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001246 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001247 if (Lex.getKind() == lltok::MetadataVar) {
1248 AteExtraComma = true;
1249 return false;
1250 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001251 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001252 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001253 Indices.push_back(Idx);
1254 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001255
Chris Lattnerdf986172009-01-02 07:01:27 +00001256 return false;
1257}
1258
1259//===----------------------------------------------------------------------===//
1260// Type Parsing.
1261//===----------------------------------------------------------------------===//
1262
1263/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001264bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1265 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001266 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001267
Chris Lattnerdf986172009-01-02 07:01:27 +00001268 // Verify no unresolved uprefs.
1269 if (!UpRefs.empty())
1270 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001271
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001272 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001273 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001274
Chris Lattnerdf986172009-01-02 07:01:27 +00001275 return false;
1276}
1277
1278/// HandleUpRefs - Every time we finish a new layer of types, this function is
1279/// called. It loops through the UpRefs vector, which is a list of the
1280/// currently active types. For each type, if the up-reference is contained in
1281/// the newly completed type, we decrement the level count. When the level
1282/// count reaches zero, the up-referenced type is the type that is passed in:
1283/// thus we can complete the cycle.
1284///
1285PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1286 // If Ty isn't abstract, or if there are no up-references in it, then there is
1287 // nothing to resolve here.
1288 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001289
Chris Lattnerdf986172009-01-02 07:01:27 +00001290 PATypeHolder Ty(ty);
1291#if 0
David Greene0e28d762009-12-23 23:38:28 +00001292 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001293 << "' newly formed. Resolving upreferences.\n"
1294 << UpRefs.size() << " upreferences active!\n";
1295#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001296
Chris Lattnerdf986172009-01-02 07:01:27 +00001297 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1298 // to zero), we resolve them all together before we resolve them to Ty. At
1299 // the end of the loop, if there is anything to resolve to Ty, it will be in
1300 // this variable.
1301 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001302
Chris Lattnerdf986172009-01-02 07:01:27 +00001303 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1304 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1305 bool ContainsType =
1306 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1307 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001308
Chris Lattnerdf986172009-01-02 07:01:27 +00001309#if 0
David Greene0e28d762009-12-23 23:38:28 +00001310 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001311 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1312 << (ContainsType ? "true" : "false")
1313 << " level=" << UpRefs[i].NestingLevel << "\n";
1314#endif
1315 if (!ContainsType)
1316 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001317
Chris Lattnerdf986172009-01-02 07:01:27 +00001318 // Decrement level of upreference
1319 unsigned Level = --UpRefs[i].NestingLevel;
1320 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001321
Chris Lattnerdf986172009-01-02 07:01:27 +00001322 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1323 if (Level != 0)
1324 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001325
Chris Lattnerdf986172009-01-02 07:01:27 +00001326#if 0
David Greene0e28d762009-12-23 23:38:28 +00001327 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001328#endif
1329 if (!TypeToResolve)
1330 TypeToResolve = UpRefs[i].UpRefTy;
1331 else
1332 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1333 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1334 --i; // Do not skip the next element.
1335 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001336
Chris Lattnerdf986172009-01-02 07:01:27 +00001337 if (TypeToResolve)
1338 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001339
Chris Lattnerdf986172009-01-02 07:01:27 +00001340 return Ty;
1341}
1342
1343
1344/// ParseTypeRec - The recursive function used to process the internal
1345/// implementation details of types.
1346bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1347 switch (Lex.getKind()) {
1348 default:
1349 return TokError("expected type");
1350 case lltok::Type:
1351 // TypeRec ::= 'float' | 'void' (etc)
1352 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001353 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001354 break;
1355 case lltok::kw_opaque:
1356 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001357 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001358 Lex.Lex();
1359 break;
1360 case lltok::lbrace:
1361 // TypeRec ::= '{' ... '}'
1362 if (ParseStructType(Result, false))
1363 return true;
1364 break;
1365 case lltok::lsquare:
1366 // TypeRec ::= '[' ... ']'
1367 Lex.Lex(); // eat the lsquare.
1368 if (ParseArrayVectorType(Result, false))
1369 return true;
1370 break;
1371 case lltok::less: // Either vector or packed struct.
1372 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001373 Lex.Lex();
1374 if (Lex.getKind() == lltok::lbrace) {
1375 if (ParseStructType(Result, true) ||
1376 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001377 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001378 } else if (ParseArrayVectorType(Result, true))
1379 return true;
1380 break;
1381 case lltok::LocalVar:
1382 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1383 // TypeRec ::= %foo
1384 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1385 Result = T;
1386 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001387 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001388 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1389 std::make_pair(Result,
1390 Lex.getLoc())));
1391 M->addTypeName(Lex.getStrVal(), Result.get());
1392 }
1393 Lex.Lex();
1394 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001395
Chris Lattnerdf986172009-01-02 07:01:27 +00001396 case lltok::LocalVarID:
1397 // TypeRec ::= %4
1398 if (Lex.getUIntVal() < NumberedTypes.size())
1399 Result = NumberedTypes[Lex.getUIntVal()];
1400 else {
1401 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1402 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1403 if (I != ForwardRefTypeIDs.end())
1404 Result = I->second.first;
1405 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001406 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001407 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1408 std::make_pair(Result,
1409 Lex.getLoc())));
1410 }
1411 }
1412 Lex.Lex();
1413 break;
1414 case lltok::backslash: {
1415 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001416 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001417 unsigned Val;
1418 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001419 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001420 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1421 Result = OT;
1422 break;
1423 }
1424 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001425
1426 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001427 while (1) {
1428 switch (Lex.getKind()) {
1429 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001430 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001431
1432 // TypeRec ::= TypeRec '*'
1433 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001434 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001435 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001436 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001437 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001438 if (!PointerType::isValidElementType(Result.get()))
1439 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001440 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001441 Lex.Lex();
1442 break;
1443
1444 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1445 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001446 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001447 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001448 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001449 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001450 if (!PointerType::isValidElementType(Result.get()))
1451 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001452 unsigned AddrSpace;
1453 if (ParseOptionalAddrSpace(AddrSpace) ||
1454 ParseToken(lltok::star, "expected '*' in address space"))
1455 return true;
1456
Owen Andersondebcb012009-07-29 22:17:13 +00001457 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001458 break;
1459 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001460
Chris Lattnerdf986172009-01-02 07:01:27 +00001461 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1462 case lltok::lparen:
1463 if (ParseFunctionType(Result))
1464 return true;
1465 break;
1466 }
1467 }
1468}
1469
1470/// ParseParameterList
1471/// ::= '(' ')'
1472/// ::= '(' Arg (',' Arg)* ')'
1473/// Arg
1474/// ::= Type OptionalAttributes Value OptionalAttributes
1475bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1476 PerFunctionState &PFS) {
1477 if (ParseToken(lltok::lparen, "expected '(' in call"))
1478 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001479
Chris Lattnerdf986172009-01-02 07:01:27 +00001480 while (Lex.getKind() != lltok::rparen) {
1481 // If this isn't the first argument, we need a comma.
1482 if (!ArgList.empty() &&
1483 ParseToken(lltok::comma, "expected ',' in argument list"))
1484 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001485
Chris Lattnerdf986172009-01-02 07:01:27 +00001486 // Parse the argument.
1487 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001488 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001489 unsigned ArgAttrs1 = Attribute::None;
1490 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001491 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001492 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001493 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001494
Chris Lattner287881d2009-12-30 02:11:14 +00001495 // Otherwise, handle normal operands.
1496 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1497 ParseValue(ArgTy, V, PFS) ||
1498 // FIXME: Should not allow attributes after the argument, remove this
1499 // in LLVM 3.0.
1500 ParseOptionalAttrs(ArgAttrs2, 3))
1501 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001502 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1503 }
1504
1505 Lex.Lex(); // Lex the ')'.
1506 return false;
1507}
1508
1509
1510
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001511/// ParseArgumentList - Parse the argument list for a function type or function
1512/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001513/// ::= '(' ArgTypeListI ')'
1514/// ArgTypeListI
1515/// ::= /*empty*/
1516/// ::= '...'
1517/// ::= ArgTypeList ',' '...'
1518/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001519///
Chris Lattnerdf986172009-01-02 07:01:27 +00001520bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001521 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001522 isVarArg = false;
1523 assert(Lex.getKind() == lltok::lparen);
1524 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001525
Chris Lattnerdf986172009-01-02 07:01:27 +00001526 if (Lex.getKind() == lltok::rparen) {
1527 // empty
1528 } else if (Lex.getKind() == lltok::dotdotdot) {
1529 isVarArg = true;
1530 Lex.Lex();
1531 } else {
1532 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001533 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001534 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001535 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001536
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001537 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1538 // types (such as a function returning a pointer to itself). If parsing a
1539 // function prototype, we require fully resolved types.
1540 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001541 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001542
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001543 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001544 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001545
Chris Lattnerdf986172009-01-02 07:01:27 +00001546 if (Lex.getKind() == lltok::LocalVar ||
1547 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1548 Name = Lex.getStrVal();
1549 Lex.Lex();
1550 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001551
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001552 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001553 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001554
Chris Lattnerdf986172009-01-02 07:01:27 +00001555 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001556
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001557 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001558 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001559 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001560 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001561 break;
1562 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001563
Chris Lattnerdf986172009-01-02 07:01:27 +00001564 // Otherwise must be an argument type.
1565 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001566 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001567 ParseOptionalAttrs(Attrs, 0)) return true;
1568
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001569 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001570 return Error(TypeLoc, "argument can not have void type");
1571
Chris Lattnerdf986172009-01-02 07:01:27 +00001572 if (Lex.getKind() == lltok::LocalVar ||
1573 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1574 Name = Lex.getStrVal();
1575 Lex.Lex();
1576 } else {
1577 Name = "";
1578 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001579
Duncan Sands47c51882010-02-16 14:50:09 +00001580 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001581 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001582
Chris Lattnerdf986172009-01-02 07:01:27 +00001583 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1584 }
1585 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001586
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001587 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001588}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001589
Chris Lattnerdf986172009-01-02 07:01:27 +00001590/// ParseFunctionType
1591/// ::= Type ArgumentList OptionalAttrs
1592bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1593 assert(Lex.getKind() == lltok::lparen);
1594
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001595 if (!FunctionType::isValidReturnType(Result))
1596 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001597
Chris Lattnerdf986172009-01-02 07:01:27 +00001598 std::vector<ArgInfo> ArgList;
1599 bool isVarArg;
1600 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001601 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001602 // FIXME: Allow, but ignore attributes on function types!
1603 // FIXME: Remove in LLVM 3.0
1604 ParseOptionalAttrs(Attrs, 2))
1605 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001606
Chris Lattnerdf986172009-01-02 07:01:27 +00001607 // Reject names on the arguments lists.
1608 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1609 if (!ArgList[i].Name.empty())
1610 return Error(ArgList[i].Loc, "argument name invalid in function type");
1611 if (!ArgList[i].Attrs != 0) {
1612 // Allow but ignore attributes on function types; this permits
1613 // auto-upgrade.
1614 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1615 }
1616 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001617
Chris Lattnerdf986172009-01-02 07:01:27 +00001618 std::vector<const Type*> ArgListTy;
1619 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1620 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001621
Owen Andersondebcb012009-07-29 22:17:13 +00001622 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001623 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001624 return false;
1625}
1626
1627/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1628/// TypeRec
1629/// ::= '{' '}'
1630/// ::= '{' TypeRec (',' TypeRec)* '}'
1631/// ::= '<' '{' '}' '>'
1632/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1633bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1634 assert(Lex.getKind() == lltok::lbrace);
1635 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001636
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001637 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001638 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001639 return false;
1640 }
1641
1642 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001643 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001644 if (ParseTypeRec(Result)) return true;
1645 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001646
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001647 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001648 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001649 if (!StructType::isValidElementType(Result))
1650 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001651
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001652 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001653 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001654 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001655
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001656 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001657 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001658 if (!StructType::isValidElementType(Result))
1659 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001660
Chris Lattnerdf986172009-01-02 07:01:27 +00001661 ParamsList.push_back(Result);
1662 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001663
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001664 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1665 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001666
Chris Lattnerdf986172009-01-02 07:01:27 +00001667 std::vector<const Type*> ParamsListTy;
1668 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1669 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001670 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001671 return false;
1672}
1673
1674/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1675/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001676/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001677/// ::= '[' APSINTVAL 'x' Types ']'
1678/// ::= '<' APSINTVAL 'x' Types '>'
1679bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1680 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1681 Lex.getAPSIntVal().getBitWidth() > 64)
1682 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001683
Chris Lattnerdf986172009-01-02 07:01:27 +00001684 LocTy SizeLoc = Lex.getLoc();
1685 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001686 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001687
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001688 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1689 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001690
1691 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001692 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001693 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001694
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001695 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001696 return Error(TypeLoc, "array and vector element type cannot be void");
1697
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001698 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1699 "expected end of sequential type"))
1700 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001701
Chris Lattnerdf986172009-01-02 07:01:27 +00001702 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001703 if (Size == 0)
1704 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001705 if ((unsigned)Size != Size)
1706 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001707 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001708 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001709 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001710 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001711 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001712 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001713 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001714 }
1715 return false;
1716}
1717
1718//===----------------------------------------------------------------------===//
1719// Function Semantic Analysis.
1720//===----------------------------------------------------------------------===//
1721
Chris Lattner09d9ef42009-10-28 03:39:23 +00001722LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1723 int functionNumber)
1724 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001725
1726 // Insert unnamed arguments into the NumberedVals list.
1727 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1728 AI != E; ++AI)
1729 if (!AI->hasName())
1730 NumberedVals.push_back(AI);
1731}
1732
1733LLParser::PerFunctionState::~PerFunctionState() {
1734 // If there were any forward referenced non-basicblock values, delete them.
1735 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1736 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1737 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001738 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001739 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001740 delete I->second.first;
1741 I->second.first = 0;
1742 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001743
Chris Lattnerdf986172009-01-02 07:01:27 +00001744 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1745 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1746 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001747 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001748 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001749 delete I->second.first;
1750 I->second.first = 0;
1751 }
1752}
1753
Chris Lattner09d9ef42009-10-28 03:39:23 +00001754bool LLParser::PerFunctionState::FinishFunction() {
1755 // Check to see if someone took the address of labels in this block.
1756 if (!P.ForwardRefBlockAddresses.empty()) {
1757 ValID FunctionID;
1758 if (!F.getName().empty()) {
1759 FunctionID.Kind = ValID::t_GlobalName;
1760 FunctionID.StrVal = F.getName();
1761 } else {
1762 FunctionID.Kind = ValID::t_GlobalID;
1763 FunctionID.UIntVal = FunctionNumber;
1764 }
1765
1766 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1767 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1768 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1769 // Resolve all these references.
1770 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1771 return true;
1772
1773 P.ForwardRefBlockAddresses.erase(FRBAI);
1774 }
1775 }
1776
Chris Lattnerdf986172009-01-02 07:01:27 +00001777 if (!ForwardRefVals.empty())
1778 return P.Error(ForwardRefVals.begin()->second.second,
1779 "use of undefined value '%" + ForwardRefVals.begin()->first +
1780 "'");
1781 if (!ForwardRefValIDs.empty())
1782 return P.Error(ForwardRefValIDs.begin()->second.second,
1783 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001784 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001785 return false;
1786}
1787
1788
1789/// GetVal - Get a value with the specified name or ID, creating a
1790/// forward reference record if needed. This can return null if the value
1791/// exists but does not have the right type.
1792Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1793 const Type *Ty, LocTy Loc) {
1794 // Look this name up in the normal function symbol table.
1795 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001796
Chris Lattnerdf986172009-01-02 07:01:27 +00001797 // If this is a forward reference for the value, see if we already created a
1798 // forward ref record.
1799 if (Val == 0) {
1800 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1801 I = ForwardRefVals.find(Name);
1802 if (I != ForwardRefVals.end())
1803 Val = I->second.first;
1804 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001805
Chris Lattnerdf986172009-01-02 07:01:27 +00001806 // If we have the value in the symbol table or fwd-ref table, return it.
1807 if (Val) {
1808 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001809 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001810 P.Error(Loc, "'%" + Name + "' is not a basic block");
1811 else
1812 P.Error(Loc, "'%" + Name + "' defined with type '" +
1813 Val->getType()->getDescription() + "'");
1814 return 0;
1815 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001816
Chris Lattnerdf986172009-01-02 07:01:27 +00001817 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001818 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001819 P.Error(Loc, "invalid use of a non-first-class type");
1820 return 0;
1821 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001822
Chris Lattnerdf986172009-01-02 07:01:27 +00001823 // Otherwise, create a new forward reference for this value and remember it.
1824 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001825 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001826 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001827 else
1828 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001829
Chris Lattnerdf986172009-01-02 07:01:27 +00001830 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1831 return FwdVal;
1832}
1833
1834Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1835 LocTy Loc) {
1836 // Look this name up in the normal function symbol table.
1837 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001838
Chris Lattnerdf986172009-01-02 07:01:27 +00001839 // If this is a forward reference for the value, see if we already created a
1840 // forward ref record.
1841 if (Val == 0) {
1842 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1843 I = ForwardRefValIDs.find(ID);
1844 if (I != ForwardRefValIDs.end())
1845 Val = I->second.first;
1846 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001847
Chris Lattnerdf986172009-01-02 07:01:27 +00001848 // If we have the value in the symbol table or fwd-ref table, return it.
1849 if (Val) {
1850 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001851 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001852 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001853 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001854 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001855 Val->getType()->getDescription() + "'");
1856 return 0;
1857 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001858
Duncan Sands47c51882010-02-16 14:50:09 +00001859 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001860 P.Error(Loc, "invalid use of a non-first-class type");
1861 return 0;
1862 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001863
Chris Lattnerdf986172009-01-02 07:01:27 +00001864 // Otherwise, create a new forward reference for this value and remember it.
1865 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001866 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001867 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001868 else
1869 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001870
Chris Lattnerdf986172009-01-02 07:01:27 +00001871 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1872 return FwdVal;
1873}
1874
1875/// SetInstName - After an instruction is parsed and inserted into its
1876/// basic block, this installs its name.
1877bool LLParser::PerFunctionState::SetInstName(int NameID,
1878 const std::string &NameStr,
1879 LocTy NameLoc, Instruction *Inst) {
1880 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001881 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001882 if (NameID != -1 || !NameStr.empty())
1883 return P.Error(NameLoc, "instructions returning void cannot have a name");
1884 return false;
1885 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001886
Chris Lattnerdf986172009-01-02 07:01:27 +00001887 // If this was a numbered instruction, verify that the instruction is the
1888 // expected value and resolve any forward references.
1889 if (NameStr.empty()) {
1890 // If neither a name nor an ID was specified, just use the next ID.
1891 if (NameID == -1)
1892 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001893
Chris Lattnerdf986172009-01-02 07:01:27 +00001894 if (unsigned(NameID) != NumberedVals.size())
1895 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001896 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001897
Chris Lattnerdf986172009-01-02 07:01:27 +00001898 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1899 ForwardRefValIDs.find(NameID);
1900 if (FI != ForwardRefValIDs.end()) {
1901 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001902 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001903 FI->second.first->getType()->getDescription() + "'");
1904 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001905 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001906 ForwardRefValIDs.erase(FI);
1907 }
1908
1909 NumberedVals.push_back(Inst);
1910 return false;
1911 }
1912
1913 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1914 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1915 FI = ForwardRefVals.find(NameStr);
1916 if (FI != ForwardRefVals.end()) {
1917 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001918 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001919 FI->second.first->getType()->getDescription() + "'");
1920 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001921 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001922 ForwardRefVals.erase(FI);
1923 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001924
Chris Lattnerdf986172009-01-02 07:01:27 +00001925 // Set the name on the instruction.
1926 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001927
Benjamin Krameraf812352010-10-16 11:28:23 +00001928 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001929 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001930 NameStr + "'");
1931 return false;
1932}
1933
1934/// GetBB - Get a basic block with the specified name or ID, creating a
1935/// forward reference record if needed.
1936BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1937 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001938 return cast_or_null<BasicBlock>(GetVal(Name,
1939 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001940}
1941
1942BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001943 return cast_or_null<BasicBlock>(GetVal(ID,
1944 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001945}
1946
1947/// DefineBB - Define the specified basic block, which is either named or
1948/// unnamed. If there is an error, this returns null otherwise it returns
1949/// the block being defined.
1950BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1951 LocTy Loc) {
1952 BasicBlock *BB;
1953 if (Name.empty())
1954 BB = GetBB(NumberedVals.size(), Loc);
1955 else
1956 BB = GetBB(Name, Loc);
1957 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001958
Chris Lattnerdf986172009-01-02 07:01:27 +00001959 // Move the block to the end of the function. Forward ref'd blocks are
1960 // inserted wherever they happen to be referenced.
1961 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001962
Chris Lattnerdf986172009-01-02 07:01:27 +00001963 // Remove the block from forward ref sets.
1964 if (Name.empty()) {
1965 ForwardRefValIDs.erase(NumberedVals.size());
1966 NumberedVals.push_back(BB);
1967 } else {
1968 // BB forward references are already in the function symbol table.
1969 ForwardRefVals.erase(Name);
1970 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001971
Chris Lattnerdf986172009-01-02 07:01:27 +00001972 return BB;
1973}
1974
1975//===----------------------------------------------------------------------===//
1976// Constants.
1977//===----------------------------------------------------------------------===//
1978
1979/// ParseValID - Parse an abstract value that doesn't necessarily have a
1980/// type implied. For example, if we parse "4" we don't know what integer type
1981/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001982/// sanity. PFS is used to convert function-local operands of metadata (since
1983/// metadata operands are not just parsed here but also converted to values).
1984/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001985bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001986 ID.Loc = Lex.getLoc();
1987 switch (Lex.getKind()) {
1988 default: return TokError("expected value token");
1989 case lltok::GlobalID: // @42
1990 ID.UIntVal = Lex.getUIntVal();
1991 ID.Kind = ValID::t_GlobalID;
1992 break;
1993 case lltok::GlobalVar: // @foo
1994 ID.StrVal = Lex.getStrVal();
1995 ID.Kind = ValID::t_GlobalName;
1996 break;
1997 case lltok::LocalVarID: // %42
1998 ID.UIntVal = Lex.getUIntVal();
1999 ID.Kind = ValID::t_LocalID;
2000 break;
2001 case lltok::LocalVar: // %foo
2002 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2003 ID.StrVal = Lex.getStrVal();
2004 ID.Kind = ValID::t_LocalName;
2005 break;
Dan Gohman83448032010-07-14 18:26:50 +00002006 case lltok::exclaim: // !42, !{...}, or !"foo"
2007 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002008 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002009 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002010 ID.Kind = ValID::t_APSInt;
2011 break;
2012 case lltok::APFloat:
2013 ID.APFloatVal = Lex.getAPFloatVal();
2014 ID.Kind = ValID::t_APFloat;
2015 break;
2016 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002017 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002018 ID.Kind = ValID::t_Constant;
2019 break;
2020 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002021 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002022 ID.Kind = ValID::t_Constant;
2023 break;
2024 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2025 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2026 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002027
Chris Lattnerdf986172009-01-02 07:01:27 +00002028 case lltok::lbrace: {
2029 // ValID ::= '{' ConstVector '}'
2030 Lex.Lex();
2031 SmallVector<Constant*, 16> Elts;
2032 if (ParseGlobalValueVector(Elts) ||
2033 ParseToken(lltok::rbrace, "expected end of struct constant"))
2034 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002035
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002036 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2037 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002038 ID.Kind = ValID::t_Constant;
2039 return false;
2040 }
2041 case lltok::less: {
2042 // ValID ::= '<' ConstVector '>' --> Vector.
2043 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2044 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002045 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002046
Chris Lattnerdf986172009-01-02 07:01:27 +00002047 SmallVector<Constant*, 16> Elts;
2048 LocTy FirstEltLoc = Lex.getLoc();
2049 if (ParseGlobalValueVector(Elts) ||
2050 (isPackedStruct &&
2051 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2052 ParseToken(lltok::greater, "expected end of constant"))
2053 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002054
Chris Lattnerdf986172009-01-02 07:01:27 +00002055 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002056 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002057 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002058 ID.Kind = ValID::t_Constant;
2059 return false;
2060 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002061
Chris Lattnerdf986172009-01-02 07:01:27 +00002062 if (Elts.empty())
2063 return Error(ID.Loc, "constant vector must not be empty");
2064
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002065 if (!Elts[0]->getType()->isIntegerTy() &&
2066 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002067 return Error(FirstEltLoc,
2068 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002069
Chris Lattnerdf986172009-01-02 07:01:27 +00002070 // Verify that all the vector elements have the same type.
2071 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2072 if (Elts[i]->getType() != Elts[0]->getType())
2073 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002074 "vector element #" + Twine(i) +
Chris Lattnerdf986172009-01-02 07:01:27 +00002075 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002076
Owen Andersonaf7ec972009-07-28 21:19:26 +00002077 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002078 ID.Kind = ValID::t_Constant;
2079 return false;
2080 }
2081 case lltok::lsquare: { // Array Constant
2082 Lex.Lex();
2083 SmallVector<Constant*, 16> Elts;
2084 LocTy FirstEltLoc = Lex.getLoc();
2085 if (ParseGlobalValueVector(Elts) ||
2086 ParseToken(lltok::rsquare, "expected end of array constant"))
2087 return true;
2088
2089 // Handle empty element.
2090 if (Elts.empty()) {
2091 // Use undef instead of an array because it's inconvenient to determine
2092 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002093 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002094 return false;
2095 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002096
Chris Lattnerdf986172009-01-02 07:01:27 +00002097 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002098 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002099 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002100
Owen Andersondebcb012009-07-29 22:17:13 +00002101 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002102
Chris Lattnerdf986172009-01-02 07:01:27 +00002103 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002104 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002105 if (Elts[i]->getType() != Elts[0]->getType())
2106 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002107 "array element #" + Twine(i) +
Chris Lattnerdf986172009-01-02 07:01:27 +00002108 " is not of type '" +Elts[0]->getType()->getDescription());
2109 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002110
Owen Anderson1fd70962009-07-28 18:32:17 +00002111 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002112 ID.Kind = ValID::t_Constant;
2113 return false;
2114 }
2115 case lltok::kw_c: // c "foo"
2116 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002117 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002118 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2119 ID.Kind = ValID::t_Constant;
2120 return false;
2121
2122 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002123 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2124 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002125 Lex.Lex();
2126 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002127 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002128 ParseStringConstant(ID.StrVal) ||
2129 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002130 ParseToken(lltok::StringConstant, "expected constraint string"))
2131 return true;
2132 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002133 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002134 ID.Kind = ValID::t_InlineAsm;
2135 return false;
2136 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002137
Chris Lattner09d9ef42009-10-28 03:39:23 +00002138 case lltok::kw_blockaddress: {
2139 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2140 Lex.Lex();
2141
2142 ValID Fn, Label;
2143 LocTy FnLoc, LabelLoc;
2144
2145 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2146 ParseValID(Fn) ||
2147 ParseToken(lltok::comma, "expected comma in block address expression")||
2148 ParseValID(Label) ||
2149 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2150 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002151
Chris Lattner09d9ef42009-10-28 03:39:23 +00002152 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2153 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002154 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002155 return Error(Label.Loc, "expected basic block name in blockaddress");
2156
2157 // Make a global variable as a placeholder for this reference.
2158 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2159 false, GlobalValue::InternalLinkage,
2160 0, "");
2161 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2162 ID.ConstantVal = FwdRef;
2163 ID.Kind = ValID::t_Constant;
2164 return false;
2165 }
2166
Chris Lattnerdf986172009-01-02 07:01:27 +00002167 case lltok::kw_trunc:
2168 case lltok::kw_zext:
2169 case lltok::kw_sext:
2170 case lltok::kw_fptrunc:
2171 case lltok::kw_fpext:
2172 case lltok::kw_bitcast:
2173 case lltok::kw_uitofp:
2174 case lltok::kw_sitofp:
2175 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002176 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002177 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002178 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002179 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002180 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002181 Constant *SrcVal;
2182 Lex.Lex();
2183 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2184 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002185 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002186 ParseType(DestTy) ||
2187 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2188 return true;
2189 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2190 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2191 SrcVal->getType()->getDescription() + "' to '" +
2192 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002193 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002194 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002195 ID.Kind = ValID::t_Constant;
2196 return false;
2197 }
2198 case lltok::kw_extractvalue: {
2199 Lex.Lex();
2200 Constant *Val;
2201 SmallVector<unsigned, 4> Indices;
2202 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2203 ParseGlobalTypeAndValue(Val) ||
2204 ParseIndexList(Indices) ||
2205 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2206 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002207
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002208 if (!Val->getType()->isAggregateType())
2209 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002210 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2211 Indices.end()))
2212 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002213 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002214 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002215 ID.Kind = ValID::t_Constant;
2216 return false;
2217 }
2218 case lltok::kw_insertvalue: {
2219 Lex.Lex();
2220 Constant *Val0, *Val1;
2221 SmallVector<unsigned, 4> Indices;
2222 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2223 ParseGlobalTypeAndValue(Val0) ||
2224 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2225 ParseGlobalTypeAndValue(Val1) ||
2226 ParseIndexList(Indices) ||
2227 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2228 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002229 if (!Val0->getType()->isAggregateType())
2230 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002231 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2232 Indices.end()))
2233 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002234 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002235 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002236 ID.Kind = ValID::t_Constant;
2237 return false;
2238 }
2239 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002240 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002241 unsigned PredVal, Opc = Lex.getUIntVal();
2242 Constant *Val0, *Val1;
2243 Lex.Lex();
2244 if (ParseCmpPredicate(PredVal, Opc) ||
2245 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2246 ParseGlobalTypeAndValue(Val0) ||
2247 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2248 ParseGlobalTypeAndValue(Val1) ||
2249 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2250 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002251
Chris Lattnerdf986172009-01-02 07:01:27 +00002252 if (Val0->getType() != Val1->getType())
2253 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002254
Chris Lattnerdf986172009-01-02 07:01:27 +00002255 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002256
Chris Lattnerdf986172009-01-02 07:01:27 +00002257 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002258 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002259 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002260 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002261 } else {
2262 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002263 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002264 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002265 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002266 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002267 }
2268 ID.Kind = ValID::t_Constant;
2269 return false;
2270 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002271
Chris Lattnerdf986172009-01-02 07:01:27 +00002272 // Binary Operators.
2273 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002274 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002275 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002276 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002277 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002278 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002279 case lltok::kw_udiv:
2280 case lltok::kw_sdiv:
2281 case lltok::kw_fdiv:
2282 case lltok::kw_urem:
2283 case lltok::kw_srem:
2284 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002285 bool NUW = false;
2286 bool NSW = false;
2287 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002288 unsigned Opc = Lex.getUIntVal();
2289 Constant *Val0, *Val1;
2290 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002291 LocTy ModifierLoc = Lex.getLoc();
2292 if (Opc == Instruction::Add ||
2293 Opc == Instruction::Sub ||
2294 Opc == Instruction::Mul) {
2295 if (EatIfPresent(lltok::kw_nuw))
2296 NUW = true;
2297 if (EatIfPresent(lltok::kw_nsw)) {
2298 NSW = true;
2299 if (EatIfPresent(lltok::kw_nuw))
2300 NUW = true;
2301 }
2302 } else if (Opc == Instruction::SDiv) {
2303 if (EatIfPresent(lltok::kw_exact))
2304 Exact = true;
2305 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002306 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2307 ParseGlobalTypeAndValue(Val0) ||
2308 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2309 ParseGlobalTypeAndValue(Val1) ||
2310 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2311 return true;
2312 if (Val0->getType() != Val1->getType())
2313 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002314 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002315 if (NUW)
2316 return Error(ModifierLoc, "nuw only applies to integer operations");
2317 if (NSW)
2318 return Error(ModifierLoc, "nsw only applies to integer operations");
2319 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002320 // Check that the type is valid for the operator.
2321 switch (Opc) {
2322 case Instruction::Add:
2323 case Instruction::Sub:
2324 case Instruction::Mul:
2325 case Instruction::UDiv:
2326 case Instruction::SDiv:
2327 case Instruction::URem:
2328 case Instruction::SRem:
2329 if (!Val0->getType()->isIntOrIntVectorTy())
2330 return Error(ID.Loc, "constexpr requires integer operands");
2331 break;
2332 case Instruction::FAdd:
2333 case Instruction::FSub:
2334 case Instruction::FMul:
2335 case Instruction::FDiv:
2336 case Instruction::FRem:
2337 if (!Val0->getType()->isFPOrFPVectorTy())
2338 return Error(ID.Loc, "constexpr requires fp operands");
2339 break;
2340 default: llvm_unreachable("Unknown binary operator!");
2341 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002342 unsigned Flags = 0;
2343 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2344 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2345 if (Exact) Flags |= SDivOperator::IsExact;
2346 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002347 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002348 ID.Kind = ValID::t_Constant;
2349 return false;
2350 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002351
Chris Lattnerdf986172009-01-02 07:01:27 +00002352 // Logical Operations
2353 case lltok::kw_shl:
2354 case lltok::kw_lshr:
2355 case lltok::kw_ashr:
2356 case lltok::kw_and:
2357 case lltok::kw_or:
2358 case lltok::kw_xor: {
2359 unsigned Opc = Lex.getUIntVal();
2360 Constant *Val0, *Val1;
2361 Lex.Lex();
2362 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2363 ParseGlobalTypeAndValue(Val0) ||
2364 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2365 ParseGlobalTypeAndValue(Val1) ||
2366 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2367 return true;
2368 if (Val0->getType() != Val1->getType())
2369 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002370 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002371 return Error(ID.Loc,
2372 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002373 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002374 ID.Kind = ValID::t_Constant;
2375 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002376 }
2377
Chris Lattnerdf986172009-01-02 07:01:27 +00002378 case lltok::kw_getelementptr:
2379 case lltok::kw_shufflevector:
2380 case lltok::kw_insertelement:
2381 case lltok::kw_extractelement:
2382 case lltok::kw_select: {
2383 unsigned Opc = Lex.getUIntVal();
2384 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002385 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002386 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002387 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002388 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002389 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2390 ParseGlobalValueVector(Elts) ||
2391 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2392 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002393
Chris Lattnerdf986172009-01-02 07:01:27 +00002394 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002395 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002396 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002397
Chris Lattnerdf986172009-01-02 07:01:27 +00002398 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002399 (Value**)(Elts.data() + 1),
2400 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002401 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002402 ID.ConstantVal = InBounds ?
2403 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2404 Elts.data() + 1,
2405 Elts.size() - 1) :
2406 ConstantExpr::getGetElementPtr(Elts[0],
2407 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002408 } else if (Opc == Instruction::Select) {
2409 if (Elts.size() != 3)
2410 return Error(ID.Loc, "expected three operands to select");
2411 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2412 Elts[2]))
2413 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002414 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002415 } else if (Opc == Instruction::ShuffleVector) {
2416 if (Elts.size() != 3)
2417 return Error(ID.Loc, "expected three operands to shufflevector");
2418 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2419 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002420 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002421 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002422 } else if (Opc == Instruction::ExtractElement) {
2423 if (Elts.size() != 2)
2424 return Error(ID.Loc, "expected two operands to extractelement");
2425 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2426 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002427 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002428 } else {
2429 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2430 if (Elts.size() != 3)
2431 return Error(ID.Loc, "expected three operands to insertelement");
2432 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2433 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002434 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002435 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002436 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002437
Chris Lattnerdf986172009-01-02 07:01:27 +00002438 ID.Kind = ValID::t_Constant;
2439 return false;
2440 }
2441 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002442
Chris Lattnerdf986172009-01-02 07:01:27 +00002443 Lex.Lex();
2444 return false;
2445}
2446
2447/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002448bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2449 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002450 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002451 Value *V = NULL;
2452 bool Parsed = ParseValID(ID) ||
2453 ConvertValIDToValue(Ty, ID, V, NULL);
2454 if (V && !(C = dyn_cast<Constant>(V)))
2455 return Error(ID.Loc, "global values must be constants");
2456 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002457}
2458
Victor Hernandez92f238d2010-01-11 22:31:58 +00002459bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2460 PATypeHolder Type(Type::getVoidTy(Context));
2461 return ParseType(Type) ||
2462 ParseGlobalValue(Type, V);
2463}
2464
2465/// ParseGlobalValueVector
2466/// ::= /*empty*/
2467/// ::= TypeAndValue (',' TypeAndValue)*
2468bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2469 // Empty list.
2470 if (Lex.getKind() == lltok::rbrace ||
2471 Lex.getKind() == lltok::rsquare ||
2472 Lex.getKind() == lltok::greater ||
2473 Lex.getKind() == lltok::rparen)
2474 return false;
2475
2476 Constant *C;
2477 if (ParseGlobalTypeAndValue(C)) return true;
2478 Elts.push_back(C);
2479
2480 while (EatIfPresent(lltok::comma)) {
2481 if (ParseGlobalTypeAndValue(C)) return true;
2482 Elts.push_back(C);
2483 }
2484
2485 return false;
2486}
2487
Dan Gohman309b3af2010-08-24 02:24:03 +00002488bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2489 assert(Lex.getKind() == lltok::lbrace);
2490 Lex.Lex();
2491
2492 SmallVector<Value*, 16> Elts;
2493 if (ParseMDNodeVector(Elts, PFS) ||
2494 ParseToken(lltok::rbrace, "expected end of metadata node"))
2495 return true;
2496
2497 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
2498 ID.Kind = ValID::t_MDNode;
2499 return false;
2500}
2501
Dan Gohman83448032010-07-14 18:26:50 +00002502/// ParseMetadataValue
2503/// ::= !42
2504/// ::= !{...}
2505/// ::= !"string"
2506bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2507 assert(Lex.getKind() == lltok::exclaim);
2508 Lex.Lex();
2509
2510 // MDNode:
2511 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002512 if (Lex.getKind() == lltok::lbrace)
2513 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002514
2515 // Standalone metadata reference
2516 // !42
2517 if (Lex.getKind() == lltok::APSInt) {
2518 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2519 ID.Kind = ValID::t_MDNode;
2520 return false;
2521 }
2522
2523 // MDString:
2524 // ::= '!' STRINGCONSTANT
2525 if (ParseMDString(ID.MDStringVal)) return true;
2526 ID.Kind = ValID::t_MDString;
2527 return false;
2528}
2529
Victor Hernandez92f238d2010-01-11 22:31:58 +00002530
2531//===----------------------------------------------------------------------===//
2532// Function Parsing.
2533//===----------------------------------------------------------------------===//
2534
2535bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2536 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002537 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002538 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002539
Chris Lattnerdf986172009-01-02 07:01:27 +00002540 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002541 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002542 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002543 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2544 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2545 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002546 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002547 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2548 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2549 return (V == 0);
2550 case ValID::t_InlineAsm: {
2551 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2552 const FunctionType *FTy =
2553 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2554 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2555 return Error(ID.Loc, "invalid type for inline asm constraint string");
2556 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2557 return false;
2558 }
2559 case ValID::t_MDNode:
2560 if (!Ty->isMetadataTy())
2561 return Error(ID.Loc, "metadata value must have metadata type");
2562 V = ID.MDNodeVal;
2563 return false;
2564 case ValID::t_MDString:
2565 if (!Ty->isMetadataTy())
2566 return Error(ID.Loc, "metadata value must have metadata type");
2567 V = ID.MDStringVal;
2568 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002569 case ValID::t_GlobalName:
2570 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2571 return V == 0;
2572 case ValID::t_GlobalID:
2573 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2574 return V == 0;
2575 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002576 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002577 return Error(ID.Loc, "integer constant must have integer type");
2578 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002579 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002580 return false;
2581 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002582 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002583 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2584 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002585
Chris Lattnerdf986172009-01-02 07:01:27 +00002586 // The lexer has no type info, so builds all float and double FP constants
2587 // as double. Fix this here. Long double does not need this.
2588 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002589 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002590 bool Ignored;
2591 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2592 &Ignored);
2593 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002594 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002595
Chris Lattner959873d2009-01-05 18:24:23 +00002596 if (V->getType() != Ty)
2597 return Error(ID.Loc, "floating point constant does not have type '" +
2598 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002599
Chris Lattnerdf986172009-01-02 07:01:27 +00002600 return false;
2601 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002602 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002603 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002604 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002605 return false;
2606 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002607 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002608 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002609 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002610 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002611 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002612 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002613 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002614 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002615 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002616 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002617 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002618 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002619 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002620 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002621 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002622 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002623 return false;
2624 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002625 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002626 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002627
Chris Lattnerdf986172009-01-02 07:01:27 +00002628 V = ID.ConstantVal;
2629 return false;
2630 }
2631}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002632
Chris Lattnerdf986172009-01-02 07:01:27 +00002633bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2634 V = 0;
2635 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002636 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002637 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002638}
2639
2640bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002641 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002642 return ParseType(T) ||
2643 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002644}
2645
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002646bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2647 PerFunctionState &PFS) {
2648 Value *V;
2649 Loc = Lex.getLoc();
2650 if (ParseTypeAndValue(V, PFS)) return true;
2651 if (!isa<BasicBlock>(V))
2652 return Error(Loc, "expected a basic block");
2653 BB = cast<BasicBlock>(V);
2654 return false;
2655}
2656
2657
Chris Lattnerdf986172009-01-02 07:01:27 +00002658/// FunctionHeader
2659/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2660/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2661/// OptionalAlign OptGC
2662bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2663 // Parse the linkage.
2664 LocTy LinkageLoc = Lex.getLoc();
2665 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002666
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002667 unsigned Visibility, RetAttrs;
2668 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002669 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002670 LocTy RetTypeLoc = Lex.getLoc();
2671 if (ParseOptionalLinkage(Linkage) ||
2672 ParseOptionalVisibility(Visibility) ||
2673 ParseOptionalCallingConv(CC) ||
2674 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002675 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002676 return true;
2677
2678 // Verify that the linkage is ok.
2679 switch ((GlobalValue::LinkageTypes)Linkage) {
2680 case GlobalValue::ExternalLinkage:
2681 break; // always ok.
2682 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002683 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002684 if (isDefine)
2685 return Error(LinkageLoc, "invalid linkage for function definition");
2686 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002687 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002688 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002689 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling55ae5152010-08-20 22:05:50 +00002690 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002691 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002692 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002693 case GlobalValue::LinkOnceAnyLinkage:
2694 case GlobalValue::LinkOnceODRLinkage:
2695 case GlobalValue::WeakAnyLinkage:
2696 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002697 case GlobalValue::DLLExportLinkage:
2698 if (!isDefine)
2699 return Error(LinkageLoc, "invalid linkage for function declaration");
2700 break;
2701 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002702 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002703 return Error(LinkageLoc, "invalid function linkage type");
2704 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002705
Chris Lattner99bb3152009-01-05 08:00:30 +00002706 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002707 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002708 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002709
Chris Lattnerdf986172009-01-02 07:01:27 +00002710 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002711
2712 std::string FunctionName;
2713 if (Lex.getKind() == lltok::GlobalVar) {
2714 FunctionName = Lex.getStrVal();
2715 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2716 unsigned NameID = Lex.getUIntVal();
2717
2718 if (NameID != NumberedVals.size())
2719 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002720 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002721 } else {
2722 return TokError("expected function name");
2723 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002724
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002725 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002726
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002727 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002728 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002729
Chris Lattnerdf986172009-01-02 07:01:27 +00002730 std::vector<ArgInfo> ArgList;
2731 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002732 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002733 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002734 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002735 std::string GC;
2736
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002737 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002738 ParseOptionalAttrs(FuncAttrs, 2) ||
2739 (EatIfPresent(lltok::kw_section) &&
2740 ParseStringConstant(Section)) ||
2741 ParseOptionalAlignment(Alignment) ||
2742 (EatIfPresent(lltok::kw_gc) &&
2743 ParseStringConstant(GC)))
2744 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002745
2746 // If the alignment was parsed as an attribute, move to the alignment field.
2747 if (FuncAttrs & Attribute::Alignment) {
2748 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2749 FuncAttrs &= ~Attribute::Alignment;
2750 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002751
Chris Lattnerdf986172009-01-02 07:01:27 +00002752 // Okay, if we got here, the function is syntactically valid. Convert types
2753 // and do semantic checks.
2754 std::vector<const Type*> ParamTypeList;
2755 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002756 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002757 // attributes.
2758 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2759 if (FuncAttrs & ObsoleteFuncAttrs) {
2760 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2761 FuncAttrs &= ~ObsoleteFuncAttrs;
2762 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002763
Chris Lattnerdf986172009-01-02 07:01:27 +00002764 if (RetAttrs != Attribute::None)
2765 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002766
Chris Lattnerdf986172009-01-02 07:01:27 +00002767 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2768 ParamTypeList.push_back(ArgList[i].Type);
2769 if (ArgList[i].Attrs != Attribute::None)
2770 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2771 }
2772
2773 if (FuncAttrs != Attribute::None)
2774 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2775
2776 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002777
Benjamin Kramerf0127052010-01-05 13:12:22 +00002778 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002779 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2780
Owen Andersonfba933c2009-07-01 23:57:11 +00002781 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002782 FunctionType::get(RetType, ParamTypeList, isVarArg);
2783 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002784
2785 Fn = 0;
2786 if (!FunctionName.empty()) {
2787 // If this was a definition of a forward reference, remove the definition
2788 // from the forward reference table and fill in the forward ref.
2789 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2790 ForwardRefVals.find(FunctionName);
2791 if (FRVI != ForwardRefVals.end()) {
2792 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002793 if (Fn->getType() != PFT)
2794 return Error(FRVI->second.second, "invalid forward reference to "
2795 "function '" + FunctionName + "' with wrong type!");
2796
Chris Lattnerdf986172009-01-02 07:01:27 +00002797 ForwardRefVals.erase(FRVI);
2798 } else if ((Fn = M->getFunction(FunctionName))) {
2799 // If this function already exists in the symbol table, then it is
2800 // multiply defined. We accept a few cases for old backwards compat.
2801 // FIXME: Remove this stuff for LLVM 3.0.
2802 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2803 (!Fn->isDeclaration() && isDefine)) {
2804 // If the redefinition has different type or different attributes,
2805 // reject it. If both have bodies, reject it.
2806 return Error(NameLoc, "invalid redefinition of function '" +
2807 FunctionName + "'");
2808 } else if (Fn->isDeclaration()) {
2809 // Make sure to strip off any argument names so we can't get conflicts.
2810 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2811 AI != AE; ++AI)
2812 AI->setName("");
2813 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002814 } else if (M->getNamedValue(FunctionName)) {
2815 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002816 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002817
Dan Gohman41905542009-08-29 23:37:49 +00002818 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002819 // If this is a definition of a forward referenced function, make sure the
2820 // types agree.
2821 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2822 = ForwardRefValIDs.find(NumberedVals.size());
2823 if (I != ForwardRefValIDs.end()) {
2824 Fn = cast<Function>(I->second.first);
2825 if (Fn->getType() != PFT)
2826 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002827 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002828 ForwardRefValIDs.erase(I);
2829 }
2830 }
2831
2832 if (Fn == 0)
2833 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2834 else // Move the forward-reference to the correct spot in the module.
2835 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2836
2837 if (FunctionName.empty())
2838 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002839
Chris Lattnerdf986172009-01-02 07:01:27 +00002840 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2841 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2842 Fn->setCallingConv(CC);
2843 Fn->setAttributes(PAL);
2844 Fn->setAlignment(Alignment);
2845 Fn->setSection(Section);
2846 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002847
Chris Lattnerdf986172009-01-02 07:01:27 +00002848 // Add all of the arguments we parsed to the function.
2849 Function::arg_iterator ArgIt = Fn->arg_begin();
2850 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002851 // If we run out of arguments in the Function prototype, exit early.
2852 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2853 if (ArgIt == Fn->arg_end()) break;
2854
Chris Lattnerdf986172009-01-02 07:01:27 +00002855 // If the argument has a name, insert it into the argument symbol table.
2856 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002857
Chris Lattnerdf986172009-01-02 07:01:27 +00002858 // Set the name, if it conflicted, it will be auto-renamed.
2859 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002860
Benjamin Krameraf812352010-10-16 11:28:23 +00002861 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002862 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2863 ArgList[i].Name + "'");
2864 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002865
Chris Lattnerdf986172009-01-02 07:01:27 +00002866 return false;
2867}
2868
2869
2870/// ParseFunctionBody
2871/// ::= '{' BasicBlock+ '}'
2872/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2873///
2874bool LLParser::ParseFunctionBody(Function &Fn) {
2875 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2876 return TokError("expected '{' in function body");
2877 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002878
Chris Lattner09d9ef42009-10-28 03:39:23 +00002879 int FunctionNumber = -1;
2880 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2881
2882 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002883
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002884 // We need at least one basic block.
2885 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2886 return TokError("function body requires at least one basic block");
2887
Chris Lattnerdf986172009-01-02 07:01:27 +00002888 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2889 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002890
Chris Lattnerdf986172009-01-02 07:01:27 +00002891 // Eat the }.
2892 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002893
Chris Lattnerdf986172009-01-02 07:01:27 +00002894 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002895 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002896}
2897
2898/// ParseBasicBlock
2899/// ::= LabelStr? Instruction*
2900bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2901 // If this basic block starts out with a name, remember it.
2902 std::string Name;
2903 LocTy NameLoc = Lex.getLoc();
2904 if (Lex.getKind() == lltok::LabelStr) {
2905 Name = Lex.getStrVal();
2906 Lex.Lex();
2907 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002908
Chris Lattnerdf986172009-01-02 07:01:27 +00002909 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2910 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002911
Chris Lattnerdf986172009-01-02 07:01:27 +00002912 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002913
Chris Lattnerdf986172009-01-02 07:01:27 +00002914 // Parse the instructions in this block until we get a terminator.
2915 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002916 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002917 do {
2918 // This instruction may have three possibilities for a name: a) none
2919 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2920 LocTy NameLoc = Lex.getLoc();
2921 int NameID = -1;
2922 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002923
Chris Lattnerdf986172009-01-02 07:01:27 +00002924 if (Lex.getKind() == lltok::LocalVarID) {
2925 NameID = Lex.getUIntVal();
2926 Lex.Lex();
2927 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2928 return true;
2929 } else if (Lex.getKind() == lltok::LocalVar ||
2930 // FIXME: REMOVE IN LLVM 3.0
2931 Lex.getKind() == lltok::StringConstant) {
2932 NameStr = Lex.getStrVal();
2933 Lex.Lex();
2934 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2935 return true;
2936 }
Devang Patelf633a062009-09-17 23:04:48 +00002937
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002938 switch (ParseInstruction(Inst, BB, PFS)) {
2939 default: assert(0 && "Unknown ParseInstruction result!");
2940 case InstError: return true;
2941 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002942 BB->getInstList().push_back(Inst);
2943
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002944 // With a normal result, we check to see if the instruction is followed by
2945 // a comma and metadata.
2946 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002947 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002948 return true;
2949 break;
2950 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002951 BB->getInstList().push_back(Inst);
2952
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002953 // If the instruction parser ate an extra comma at the end of it, it
2954 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002955 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002956 return true;
2957 break;
2958 }
Devang Patelf633a062009-09-17 23:04:48 +00002959
Chris Lattnerdf986172009-01-02 07:01:27 +00002960 // Set the name on the instruction.
2961 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2962 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002963
Chris Lattnerdf986172009-01-02 07:01:27 +00002964 return false;
2965}
2966
2967//===----------------------------------------------------------------------===//
2968// Instruction Parsing.
2969//===----------------------------------------------------------------------===//
2970
2971/// ParseInstruction - Parse one of the many different instructions.
2972///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002973int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2974 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002975 lltok::Kind Token = Lex.getKind();
2976 if (Token == lltok::Eof)
2977 return TokError("found end of file when expecting more instructions");
2978 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002979 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002980 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002981
Chris Lattnerdf986172009-01-02 07:01:27 +00002982 switch (Token) {
2983 default: return Error(Loc, "expected instruction opcode");
2984 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002985 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2986 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002987 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2988 case lltok::kw_br: return ParseBr(Inst, PFS);
2989 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002990 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002991 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2992 // Binary Operators.
2993 case lltok::kw_add:
2994 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002995 case lltok::kw_mul: {
2996 bool NUW = false;
2997 bool NSW = false;
2998 LocTy ModifierLoc = Lex.getLoc();
2999 if (EatIfPresent(lltok::kw_nuw))
3000 NUW = true;
3001 if (EatIfPresent(lltok::kw_nsw)) {
3002 NSW = true;
3003 if (EatIfPresent(lltok::kw_nuw))
3004 NUW = true;
3005 }
Dan Gohman1eaac532010-05-03 22:44:19 +00003006 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
Dan Gohman59858cf2009-07-27 16:11:46 +00003007 if (!Result) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003008 if (!Inst->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00003009 if (NUW)
3010 return Error(ModifierLoc, "nuw only applies to integer operations");
3011 if (NSW)
3012 return Error(ModifierLoc, "nsw only applies to integer operations");
3013 }
3014 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003015 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003016 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003017 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003018 }
3019 return Result;
3020 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003021 case lltok::kw_fadd:
3022 case lltok::kw_fsub:
3023 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3024
Dan Gohman59858cf2009-07-27 16:11:46 +00003025 case lltok::kw_sdiv: {
3026 bool Exact = false;
3027 if (EatIfPresent(lltok::kw_exact))
3028 Exact = true;
3029 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3030 if (!Result)
3031 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003032 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003033 return Result;
3034 }
3035
Chris Lattnerdf986172009-01-02 07:01:27 +00003036 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00003037 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003038 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00003039 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003040 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00003041 case lltok::kw_shl:
3042 case lltok::kw_lshr:
3043 case lltok::kw_ashr:
3044 case lltok::kw_and:
3045 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003046 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003047 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003048 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003049 // Casts.
3050 case lltok::kw_trunc:
3051 case lltok::kw_zext:
3052 case lltok::kw_sext:
3053 case lltok::kw_fptrunc:
3054 case lltok::kw_fpext:
3055 case lltok::kw_bitcast:
3056 case lltok::kw_uitofp:
3057 case lltok::kw_sitofp:
3058 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003059 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003060 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003061 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003062 // Other.
3063 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003064 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003065 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3066 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3067 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3068 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3069 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3070 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3071 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003072 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3073 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00003074 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003075 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3076 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3077 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003078 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00003079 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003080 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00003081 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003082 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003083 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003084 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3085 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3086 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3087 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3088 }
3089}
3090
3091/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3092bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003093 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003094 switch (Lex.getKind()) {
3095 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3096 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3097 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3098 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3099 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3100 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3101 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3102 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3103 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3104 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3105 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3106 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3107 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3108 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3109 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3110 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3111 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3112 }
3113 } else {
3114 switch (Lex.getKind()) {
3115 default: TokError("expected icmp predicate (e.g. 'eq')");
3116 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3117 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3118 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3119 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3120 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3121 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3122 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3123 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3124 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3125 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3126 }
3127 }
3128 Lex.Lex();
3129 return false;
3130}
3131
3132//===----------------------------------------------------------------------===//
3133// Terminator Instructions.
3134//===----------------------------------------------------------------------===//
3135
3136/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003137/// ::= 'ret' void (',' !dbg, !1)*
3138/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3139/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00003140/// [[obsolete: LLVM 3.0]]
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003141int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3142 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003143 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003144 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003145
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003146 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003147 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003148 return false;
3149 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003150
Chris Lattnerdf986172009-01-02 07:01:27 +00003151 Value *RV;
3152 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003153
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003154 bool ExtraComma = false;
Devang Patelf633a062009-09-17 23:04:48 +00003155 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003156 // Parse optional custom metadata, e.g. !dbg
Chris Lattner1d928312009-12-30 05:02:06 +00003157 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003158 ExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003159 } else {
3160 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003161 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3162 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003163 SmallVector<Value*, 8> RVs;
3164 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003165
Devang Patelf633a062009-09-17 23:04:48 +00003166 do {
Devang Patel0475c912009-09-29 00:01:14 +00003167 // If optional custom metadata, e.g. !dbg is seen then this is the
3168 // end of MRV.
Chris Lattner1d928312009-12-30 05:02:06 +00003169 if (Lex.getKind() == lltok::MetadataVar)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003170 break;
3171 if (ParseTypeAndValue(RV, PFS)) return true;
3172 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003173 } while (EatIfPresent(lltok::comma));
3174
3175 RV = UndefValue::get(PFS.getFunction().getReturnType());
3176 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003177 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3178 BB->getInstList().push_back(I);
3179 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003180 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003181 }
3182 }
Devang Patelf633a062009-09-17 23:04:48 +00003183
Owen Anderson1d0be152009-08-13 21:58:54 +00003184 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003185 return ExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003186}
3187
3188
3189/// ParseBr
3190/// ::= 'br' TypeAndValue
3191/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3192bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3193 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003194 Value *Op0;
3195 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003196 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003197
Chris Lattnerdf986172009-01-02 07:01:27 +00003198 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3199 Inst = BranchInst::Create(BB);
3200 return false;
3201 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003202
Owen Anderson1d0be152009-08-13 21:58:54 +00003203 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003204 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003205
Chris Lattnerdf986172009-01-02 07:01:27 +00003206 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003207 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003208 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003209 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003210 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003211
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003212 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003213 return false;
3214}
3215
3216/// ParseSwitch
3217/// Instruction
3218/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3219/// JumpTable
3220/// ::= (TypeAndValue ',' TypeAndValue)*
3221bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3222 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003223 Value *Cond;
3224 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003225 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3226 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003227 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003228 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3229 return true;
3230
Duncan Sands1df98592010-02-16 11:11:14 +00003231 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003232 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003233
Chris Lattnerdf986172009-01-02 07:01:27 +00003234 // Parse the jump table pairs.
3235 SmallPtrSet<Value*, 32> SeenCases;
3236 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3237 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003238 Value *Constant;
3239 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003240
Chris Lattnerdf986172009-01-02 07:01:27 +00003241 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3242 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003243 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003244 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003245
Chris Lattnerdf986172009-01-02 07:01:27 +00003246 if (!SeenCases.insert(Constant))
3247 return Error(CondLoc, "duplicate case value in switch");
3248 if (!isa<ConstantInt>(Constant))
3249 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003250
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003251 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003252 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003253
Chris Lattnerdf986172009-01-02 07:01:27 +00003254 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003255
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003256 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003257 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3258 SI->addCase(Table[i].first, Table[i].second);
3259 Inst = SI;
3260 return false;
3261}
3262
Chris Lattnerab21db72009-10-28 00:19:10 +00003263/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003264/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003265/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3266bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003267 LocTy AddrLoc;
3268 Value *Address;
3269 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003270 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3271 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003272 return true;
3273
Duncan Sands1df98592010-02-16 11:11:14 +00003274 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003275 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003276
3277 // Parse the destination list.
3278 SmallVector<BasicBlock*, 16> DestList;
3279
3280 if (Lex.getKind() != lltok::rsquare) {
3281 BasicBlock *DestBB;
3282 if (ParseTypeAndBasicBlock(DestBB, PFS))
3283 return true;
3284 DestList.push_back(DestBB);
3285
3286 while (EatIfPresent(lltok::comma)) {
3287 if (ParseTypeAndBasicBlock(DestBB, PFS))
3288 return true;
3289 DestList.push_back(DestBB);
3290 }
3291 }
3292
3293 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3294 return true;
3295
Chris Lattnerab21db72009-10-28 00:19:10 +00003296 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003297 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3298 IBI->addDestination(DestList[i]);
3299 Inst = IBI;
3300 return false;
3301}
3302
3303
Chris Lattnerdf986172009-01-02 07:01:27 +00003304/// ParseInvoke
3305/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3306/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3307bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3308 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003309 unsigned RetAttrs, FnAttrs;
3310 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003311 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003312 LocTy RetTypeLoc;
3313 ValID CalleeID;
3314 SmallVector<ParamInfo, 16> ArgList;
3315
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003316 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003317 if (ParseOptionalCallingConv(CC) ||
3318 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003319 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003320 ParseValID(CalleeID) ||
3321 ParseParameterList(ArgList, PFS) ||
3322 ParseOptionalAttrs(FnAttrs, 2) ||
3323 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003324 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003325 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003326 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003327 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003328
Chris Lattnerdf986172009-01-02 07:01:27 +00003329 // If RetType is a non-function pointer type, then this is the short syntax
3330 // for the call, which means that RetType is just the return type. Infer the
3331 // rest of the function argument types from the arguments that are present.
3332 const PointerType *PFTy = 0;
3333 const FunctionType *Ty = 0;
3334 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3335 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3336 // Pull out the types of all of the arguments...
3337 std::vector<const Type*> ParamTypes;
3338 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3339 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003340
Chris Lattnerdf986172009-01-02 07:01:27 +00003341 if (!FunctionType::isValidReturnType(RetType))
3342 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003343
Owen Andersondebcb012009-07-29 22:17:13 +00003344 Ty = FunctionType::get(RetType, ParamTypes, false);
3345 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003346 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003347
Chris Lattnerdf986172009-01-02 07:01:27 +00003348 // Look up the callee.
3349 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003350 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003351
Chris Lattnerdf986172009-01-02 07:01:27 +00003352 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3353 // function attributes.
3354 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3355 if (FnAttrs & ObsoleteFuncAttrs) {
3356 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3357 FnAttrs &= ~ObsoleteFuncAttrs;
3358 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003359
Chris Lattnerdf986172009-01-02 07:01:27 +00003360 // Set up the Attributes for the function.
3361 SmallVector<AttributeWithIndex, 8> Attrs;
3362 if (RetAttrs != Attribute::None)
3363 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003364
Chris Lattnerdf986172009-01-02 07:01:27 +00003365 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003366
Chris Lattnerdf986172009-01-02 07:01:27 +00003367 // Loop through FunctionType's arguments and ensure they are specified
3368 // correctly. Also, gather any parameter attributes.
3369 FunctionType::param_iterator I = Ty->param_begin();
3370 FunctionType::param_iterator E = Ty->param_end();
3371 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3372 const Type *ExpectedTy = 0;
3373 if (I != E) {
3374 ExpectedTy = *I++;
3375 } else if (!Ty->isVarArg()) {
3376 return Error(ArgList[i].Loc, "too many arguments specified");
3377 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003378
Chris Lattnerdf986172009-01-02 07:01:27 +00003379 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3380 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3381 ExpectedTy->getDescription() + "'");
3382 Args.push_back(ArgList[i].V);
3383 if (ArgList[i].Attrs != Attribute::None)
3384 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3385 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003386
Chris Lattnerdf986172009-01-02 07:01:27 +00003387 if (I != E)
3388 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003389
Chris Lattnerdf986172009-01-02 07:01:27 +00003390 if (FnAttrs != Attribute::None)
3391 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003392
Chris Lattnerdf986172009-01-02 07:01:27 +00003393 // Finish off the Attributes and check them
3394 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003395
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003396 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003397 Args.begin(), Args.end());
3398 II->setCallingConv(CC);
3399 II->setAttributes(PAL);
3400 Inst = II;
3401 return false;
3402}
3403
3404
3405
3406//===----------------------------------------------------------------------===//
3407// Binary Operators.
3408//===----------------------------------------------------------------------===//
3409
3410/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003411/// ::= ArithmeticOps TypeAndValue ',' Value
3412///
3413/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3414/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003415bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003416 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003417 LocTy Loc; Value *LHS, *RHS;
3418 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3419 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3420 ParseValue(LHS->getType(), RHS, PFS))
3421 return true;
3422
Chris Lattnere914b592009-01-05 08:24:46 +00003423 bool Valid;
3424 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003425 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003426 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003427 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3428 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003429 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003430 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3431 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003432 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003433
Chris Lattnere914b592009-01-05 08:24:46 +00003434 if (!Valid)
3435 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003436
Chris Lattnerdf986172009-01-02 07:01:27 +00003437 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3438 return false;
3439}
3440
3441/// ParseLogical
3442/// ::= ArithmeticOps TypeAndValue ',' Value {
3443bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3444 unsigned Opc) {
3445 LocTy Loc; Value *LHS, *RHS;
3446 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3447 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3448 ParseValue(LHS->getType(), RHS, PFS))
3449 return true;
3450
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003451 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003452 return Error(Loc,"instruction requires integer or integer vector operands");
3453
3454 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3455 return false;
3456}
3457
3458
3459/// ParseCompare
3460/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3461/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003462bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3463 unsigned Opc) {
3464 // Parse the integer/fp comparison predicate.
3465 LocTy Loc;
3466 unsigned Pred;
3467 Value *LHS, *RHS;
3468 if (ParseCmpPredicate(Pred, Opc) ||
3469 ParseTypeAndValue(LHS, Loc, PFS) ||
3470 ParseToken(lltok::comma, "expected ',' after compare value") ||
3471 ParseValue(LHS->getType(), RHS, PFS))
3472 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003473
Chris Lattnerdf986172009-01-02 07:01:27 +00003474 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003475 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003476 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003477 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003478 } else {
3479 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003480 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003481 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003482 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003483 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003484 }
3485 return false;
3486}
3487
3488//===----------------------------------------------------------------------===//
3489// Other Instructions.
3490//===----------------------------------------------------------------------===//
3491
3492
3493/// ParseCast
3494/// ::= CastOpc TypeAndValue 'to' Type
3495bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3496 unsigned Opc) {
3497 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003498 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003499 if (ParseTypeAndValue(Op, Loc, PFS) ||
3500 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3501 ParseType(DestTy))
3502 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003503
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003504 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3505 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003506 return Error(Loc, "invalid cast opcode for cast from '" +
3507 Op->getType()->getDescription() + "' to '" +
3508 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003509 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003510 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3511 return false;
3512}
3513
3514/// ParseSelect
3515/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3516bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3517 LocTy Loc;
3518 Value *Op0, *Op1, *Op2;
3519 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3520 ParseToken(lltok::comma, "expected ',' after select condition") ||
3521 ParseTypeAndValue(Op1, PFS) ||
3522 ParseToken(lltok::comma, "expected ',' after select value") ||
3523 ParseTypeAndValue(Op2, PFS))
3524 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003525
Chris Lattnerdf986172009-01-02 07:01:27 +00003526 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3527 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003528
Chris Lattnerdf986172009-01-02 07:01:27 +00003529 Inst = SelectInst::Create(Op0, Op1, Op2);
3530 return false;
3531}
3532
Chris Lattner0088a5c2009-01-05 08:18:44 +00003533/// ParseVA_Arg
3534/// ::= 'va_arg' TypeAndValue ',' Type
3535bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003536 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003537 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003538 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003539 if (ParseTypeAndValue(Op, PFS) ||
3540 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003541 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003542 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003543
Chris Lattner0088a5c2009-01-05 08:18:44 +00003544 if (!EltTy->isFirstClassType())
3545 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003546
3547 Inst = new VAArgInst(Op, EltTy);
3548 return false;
3549}
3550
3551/// ParseExtractElement
3552/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3553bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3554 LocTy Loc;
3555 Value *Op0, *Op1;
3556 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3557 ParseToken(lltok::comma, "expected ',' after extract value") ||
3558 ParseTypeAndValue(Op1, PFS))
3559 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003560
Chris Lattnerdf986172009-01-02 07:01:27 +00003561 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3562 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003563
Eric Christophera3500da2009-07-25 02:28:41 +00003564 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003565 return false;
3566}
3567
3568/// ParseInsertElement
3569/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3570bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3571 LocTy Loc;
3572 Value *Op0, *Op1, *Op2;
3573 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3574 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3575 ParseTypeAndValue(Op1, PFS) ||
3576 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3577 ParseTypeAndValue(Op2, PFS))
3578 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003579
Chris Lattnerdf986172009-01-02 07:01:27 +00003580 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003581 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003582
Chris Lattnerdf986172009-01-02 07:01:27 +00003583 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3584 return false;
3585}
3586
3587/// ParseShuffleVector
3588/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3589bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3590 LocTy Loc;
3591 Value *Op0, *Op1, *Op2;
3592 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3593 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3594 ParseTypeAndValue(Op1, PFS) ||
3595 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3596 ParseTypeAndValue(Op2, PFS))
3597 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003598
Chris Lattnerdf986172009-01-02 07:01:27 +00003599 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3600 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003601
Chris Lattnerdf986172009-01-02 07:01:27 +00003602 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3603 return false;
3604}
3605
3606/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003607/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003608int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003609 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003610 Value *Op0, *Op1;
3611 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003612
Chris Lattnerdf986172009-01-02 07:01:27 +00003613 if (ParseType(Ty) ||
3614 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3615 ParseValue(Ty, Op0, PFS) ||
3616 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003617 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003618 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3619 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003620
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003621 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003622 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3623 while (1) {
3624 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003625
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003626 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003627 break;
3628
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003629 if (Lex.getKind() == lltok::MetadataVar) {
3630 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003631 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003632 }
Devang Patela43d46f2009-10-16 18:45:49 +00003633
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003634 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003635 ParseValue(Ty, Op0, PFS) ||
3636 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003637 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003638 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3639 return true;
3640 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003641
Chris Lattnerdf986172009-01-02 07:01:27 +00003642 if (!Ty->isFirstClassType())
3643 return Error(TypeLoc, "phi node must have first class type");
3644
3645 PHINode *PN = PHINode::Create(Ty);
3646 PN->reserveOperandSpace(PHIVals.size());
3647 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3648 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3649 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003650 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003651}
3652
3653/// ParseCall
3654/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3655/// ParameterList OptionalAttrs
3656bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3657 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003658 unsigned RetAttrs, FnAttrs;
3659 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003660 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003661 LocTy RetTypeLoc;
3662 ValID CalleeID;
3663 SmallVector<ParamInfo, 16> ArgList;
3664 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003665
Chris Lattnerdf986172009-01-02 07:01:27 +00003666 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3667 ParseOptionalCallingConv(CC) ||
3668 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003669 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003670 ParseValID(CalleeID) ||
3671 ParseParameterList(ArgList, PFS) ||
3672 ParseOptionalAttrs(FnAttrs, 2))
3673 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003674
Chris Lattnerdf986172009-01-02 07:01:27 +00003675 // If RetType is a non-function pointer type, then this is the short syntax
3676 // for the call, which means that RetType is just the return type. Infer the
3677 // rest of the function argument types from the arguments that are present.
3678 const PointerType *PFTy = 0;
3679 const FunctionType *Ty = 0;
3680 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3681 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3682 // Pull out the types of all of the arguments...
3683 std::vector<const Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003684 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3685 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003686
Chris Lattnerdf986172009-01-02 07:01:27 +00003687 if (!FunctionType::isValidReturnType(RetType))
3688 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003689
Owen Andersondebcb012009-07-29 22:17:13 +00003690 Ty = FunctionType::get(RetType, ParamTypes, false);
3691 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003692 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003693
Chris Lattnerdf986172009-01-02 07:01:27 +00003694 // Look up the callee.
3695 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003696 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003697
Chris Lattnerdf986172009-01-02 07:01:27 +00003698 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3699 // function attributes.
3700 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3701 if (FnAttrs & ObsoleteFuncAttrs) {
3702 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3703 FnAttrs &= ~ObsoleteFuncAttrs;
3704 }
3705
3706 // Set up the Attributes for the function.
3707 SmallVector<AttributeWithIndex, 8> Attrs;
3708 if (RetAttrs != Attribute::None)
3709 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003710
Chris Lattnerdf986172009-01-02 07:01:27 +00003711 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003712
Chris Lattnerdf986172009-01-02 07:01:27 +00003713 // Loop through FunctionType's arguments and ensure they are specified
3714 // correctly. Also, gather any parameter attributes.
3715 FunctionType::param_iterator I = Ty->param_begin();
3716 FunctionType::param_iterator E = Ty->param_end();
3717 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3718 const Type *ExpectedTy = 0;
3719 if (I != E) {
3720 ExpectedTy = *I++;
3721 } else if (!Ty->isVarArg()) {
3722 return Error(ArgList[i].Loc, "too many arguments specified");
3723 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003724
Chris Lattnerdf986172009-01-02 07:01:27 +00003725 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3726 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3727 ExpectedTy->getDescription() + "'");
3728 Args.push_back(ArgList[i].V);
3729 if (ArgList[i].Attrs != Attribute::None)
3730 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3731 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003732
Chris Lattnerdf986172009-01-02 07:01:27 +00003733 if (I != E)
3734 return Error(CallLoc, "not enough parameters specified for call");
3735
3736 if (FnAttrs != Attribute::None)
3737 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3738
3739 // Finish off the Attributes and check them
3740 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003741
Chris Lattnerdf986172009-01-02 07:01:27 +00003742 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3743 CI->setTailCall(isTail);
3744 CI->setCallingConv(CC);
3745 CI->setAttributes(PAL);
3746 Inst = CI;
3747 return false;
3748}
3749
3750//===----------------------------------------------------------------------===//
3751// Memory Instructions.
3752//===----------------------------------------------------------------------===//
3753
3754/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003755/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3756/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003757int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3758 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003759 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003760 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003761 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003762 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003763 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003764
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003765 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003766 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003767 if (Lex.getKind() == lltok::kw_align) {
3768 if (ParseOptionalAlignment(Alignment)) return true;
3769 } else if (Lex.getKind() == lltok::MetadataVar) {
3770 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003771 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003772 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3773 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3774 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003775 }
3776 }
3777
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003778 if (Size && !Size->getType()->isIntegerTy())
3779 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003780
Victor Hernandez68afa542009-10-21 19:11:40 +00003781 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003782 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003783 return AteExtraComma ? InstExtraComma : InstNormal;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003784 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003785
3786 // Autoupgrade old malloc instruction to malloc call.
3787 // FIXME: Remove in LLVM 3.0.
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003788 if (Size && !Size->getType()->isIntegerTy(32))
3789 return Error(SizeLoc, "element count must be i32");
Victor Hernandez68afa542009-10-21 19:11:40 +00003790 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003791 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3792 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
Victor Hernandez68afa542009-10-21 19:11:40 +00003793 if (!MallocF)
3794 // Prototype malloc as "void *(int32)".
3795 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003796 MallocF = cast<Function>(
3797 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003798 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003799return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003800}
3801
3802/// ParseFree
3803/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003804bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3805 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003806 Value *Val; LocTy Loc;
3807 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003808 if (!Val->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003809 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003810 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003811 return false;
3812}
3813
3814/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003815/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003816int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3817 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003818 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003819 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003820 bool AteExtraComma = false;
3821 if (ParseTypeAndValue(Val, Loc, PFS) ||
3822 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3823 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003824
Duncan Sands1df98592010-02-16 11:11:14 +00003825 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003826 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3827 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003828
Chris Lattnerdf986172009-01-02 07:01:27 +00003829 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003830 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003831}
3832
3833/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003834/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003835int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3836 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003837 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003838 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003839 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003840 if (ParseTypeAndValue(Val, Loc, PFS) ||
3841 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003842 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3843 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003844 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003845
Duncan Sands1df98592010-02-16 11:11:14 +00003846 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003847 return Error(PtrLoc, "store operand must be a pointer");
3848 if (!Val->getType()->isFirstClassType())
3849 return Error(Loc, "store operand must be a first class value");
3850 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3851 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003852
Chris Lattnerdf986172009-01-02 07:01:27 +00003853 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003854 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003855}
3856
3857/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003858/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003859/// FIXME: Remove support for getresult in LLVM 3.0
3860bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3861 Value *Val; LocTy ValLoc, EltLoc;
3862 unsigned Element;
3863 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3864 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003865 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003866 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003867
Duncan Sands1df98592010-02-16 11:11:14 +00003868 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003869 return Error(ValLoc, "getresult inst requires an aggregate operand");
3870 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3871 return Error(EltLoc, "invalid getresult index for value");
3872 Inst = ExtractValueInst::Create(Val, Element);
3873 return false;
3874}
3875
3876/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003877/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003878int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003879 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003880
Dan Gohmandcb40a32009-07-29 15:58:36 +00003881 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003882
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003883 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003884
Duncan Sands1df98592010-02-16 11:11:14 +00003885 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003886 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003887
Chris Lattnerdf986172009-01-02 07:01:27 +00003888 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003889 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003890 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003891 if (Lex.getKind() == lltok::MetadataVar) {
3892 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003893 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003894 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003895 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003896 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003897 return Error(EltLoc, "getelementptr index must be an integer");
3898 Indices.push_back(Val);
3899 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003900
Chris Lattnerdf986172009-01-02 07:01:27 +00003901 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3902 Indices.begin(), Indices.end()))
3903 return Error(Loc, "invalid getelementptr indices");
3904 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003905 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003906 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003907 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003908}
3909
3910/// ParseExtractValue
3911/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003912int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003913 Value *Val; LocTy Loc;
3914 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003915 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003916 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003917 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003918 return true;
3919
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003920 if (!Val->getType()->isAggregateType())
3921 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003922
3923 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3924 Indices.end()))
3925 return Error(Loc, "invalid indices for extractvalue");
3926 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003927 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003928}
3929
3930/// ParseInsertValue
3931/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003932int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003933 Value *Val0, *Val1; LocTy Loc0, Loc1;
3934 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003935 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003936 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3937 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3938 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003939 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003940 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003941
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003942 if (!Val0->getType()->isAggregateType())
3943 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003944
Chris Lattnerdf986172009-01-02 07:01:27 +00003945 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3946 Indices.end()))
3947 return Error(Loc0, "invalid indices for insertvalue");
3948 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003949 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003950}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003951
3952//===----------------------------------------------------------------------===//
3953// Embedded metadata.
3954//===----------------------------------------------------------------------===//
3955
3956/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003957/// ::= Element (',' Element)*
3958/// Element
3959/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003960bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003961 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003962 // Check for an empty list.
3963 if (Lex.getKind() == lltok::rbrace)
3964 return false;
3965
Nick Lewycky21cc4462009-04-04 07:22:01 +00003966 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003967 // Null is a special case since it is typeless.
3968 if (EatIfPresent(lltok::kw_null)) {
3969 Elts.push_back(0);
3970 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003971 }
Chris Lattnera7352392009-12-30 04:42:57 +00003972
3973 Value *V = 0;
3974 PATypeHolder Ty(Type::getVoidTy(Context));
3975 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00003976 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00003977 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00003978 return true;
3979
Nick Lewyckycb337992009-05-10 20:57:05 +00003980 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003981 } while (EatIfPresent(lltok::comma));
3982
3983 return false;
3984}