blob: 4d3bd879320202539c3598842628eb1f983d3699 [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'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001202
Chris Lattner093eed12010-04-23 00:50:50 +00001203 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001204 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001205
Devang Patelf633a062009-09-17 23:04:48 +00001206 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001207}
1208
Charles Davis1e063d12010-02-12 00:31:15 +00001209/// ParseOptionalStackAlignment
1210/// ::= /* empty */
1211/// ::= 'alignstack' '(' 4 ')'
1212bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1213 Alignment = 0;
1214 if (!EatIfPresent(lltok::kw_alignstack))
1215 return false;
1216 LocTy ParenLoc = Lex.getLoc();
1217 if (!EatIfPresent(lltok::lparen))
1218 return Error(ParenLoc, "expected '('");
1219 LocTy AlignLoc = Lex.getLoc();
1220 if (ParseUInt32(Alignment)) return true;
1221 ParenLoc = Lex.getLoc();
1222 if (!EatIfPresent(lltok::rparen))
1223 return Error(ParenLoc, "expected ')'");
1224 if (!isPowerOf2_32(Alignment))
1225 return Error(AlignLoc, "stack alignment is not a power of two");
1226 return false;
1227}
Devang Patelf633a062009-09-17 23:04:48 +00001228
Chris Lattner628c13a2009-12-30 05:14:00 +00001229/// ParseIndexList - This parses the index list for an insert/extractvalue
1230/// instruction. This sets AteExtraComma in the case where we eat an extra
1231/// comma at the end of the line and find that it is followed by metadata.
1232/// Clients that don't allow metadata can call the version of this function that
1233/// only takes one argument.
1234///
Chris Lattnerdf986172009-01-02 07:01:27 +00001235/// ParseIndexList
1236/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001237///
1238bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1239 bool &AteExtraComma) {
1240 AteExtraComma = false;
1241
Chris Lattnerdf986172009-01-02 07:01:27 +00001242 if (Lex.getKind() != lltok::comma)
1243 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001244
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001245 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001246 if (Lex.getKind() == lltok::MetadataVar) {
1247 AteExtraComma = true;
1248 return false;
1249 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001250 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001251 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001252 Indices.push_back(Idx);
1253 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001254
Chris Lattnerdf986172009-01-02 07:01:27 +00001255 return false;
1256}
1257
1258//===----------------------------------------------------------------------===//
1259// Type Parsing.
1260//===----------------------------------------------------------------------===//
1261
1262/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001263bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1264 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001265 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001266
Chris Lattnerdf986172009-01-02 07:01:27 +00001267 // Verify no unresolved uprefs.
1268 if (!UpRefs.empty())
1269 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001270
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001271 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001272 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001273
Chris Lattnerdf986172009-01-02 07:01:27 +00001274 return false;
1275}
1276
1277/// HandleUpRefs - Every time we finish a new layer of types, this function is
1278/// called. It loops through the UpRefs vector, which is a list of the
1279/// currently active types. For each type, if the up-reference is contained in
1280/// the newly completed type, we decrement the level count. When the level
1281/// count reaches zero, the up-referenced type is the type that is passed in:
1282/// thus we can complete the cycle.
1283///
1284PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1285 // If Ty isn't abstract, or if there are no up-references in it, then there is
1286 // nothing to resolve here.
1287 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001288
Chris Lattnerdf986172009-01-02 07:01:27 +00001289 PATypeHolder Ty(ty);
1290#if 0
David Greene0e28d762009-12-23 23:38:28 +00001291 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001292 << "' newly formed. Resolving upreferences.\n"
1293 << UpRefs.size() << " upreferences active!\n";
1294#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001295
Chris Lattnerdf986172009-01-02 07:01:27 +00001296 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1297 // to zero), we resolve them all together before we resolve them to Ty. At
1298 // the end of the loop, if there is anything to resolve to Ty, it will be in
1299 // this variable.
1300 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001301
Chris Lattnerdf986172009-01-02 07:01:27 +00001302 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1303 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1304 bool ContainsType =
1305 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1306 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001307
Chris Lattnerdf986172009-01-02 07:01:27 +00001308#if 0
David Greene0e28d762009-12-23 23:38:28 +00001309 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001310 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1311 << (ContainsType ? "true" : "false")
1312 << " level=" << UpRefs[i].NestingLevel << "\n";
1313#endif
1314 if (!ContainsType)
1315 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001316
Chris Lattnerdf986172009-01-02 07:01:27 +00001317 // Decrement level of upreference
1318 unsigned Level = --UpRefs[i].NestingLevel;
1319 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001320
Chris Lattnerdf986172009-01-02 07:01:27 +00001321 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1322 if (Level != 0)
1323 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001324
Chris Lattnerdf986172009-01-02 07:01:27 +00001325#if 0
David Greene0e28d762009-12-23 23:38:28 +00001326 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001327#endif
1328 if (!TypeToResolve)
1329 TypeToResolve = UpRefs[i].UpRefTy;
1330 else
1331 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1332 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1333 --i; // Do not skip the next element.
1334 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001335
Chris Lattnerdf986172009-01-02 07:01:27 +00001336 if (TypeToResolve)
1337 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001338
Chris Lattnerdf986172009-01-02 07:01:27 +00001339 return Ty;
1340}
1341
1342
1343/// ParseTypeRec - The recursive function used to process the internal
1344/// implementation details of types.
1345bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1346 switch (Lex.getKind()) {
1347 default:
1348 return TokError("expected type");
1349 case lltok::Type:
1350 // TypeRec ::= 'float' | 'void' (etc)
1351 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001352 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001353 break;
1354 case lltok::kw_opaque:
1355 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001356 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001357 Lex.Lex();
1358 break;
1359 case lltok::lbrace:
1360 // TypeRec ::= '{' ... '}'
1361 if (ParseStructType(Result, false))
1362 return true;
1363 break;
1364 case lltok::lsquare:
1365 // TypeRec ::= '[' ... ']'
1366 Lex.Lex(); // eat the lsquare.
1367 if (ParseArrayVectorType(Result, false))
1368 return true;
1369 break;
1370 case lltok::less: // Either vector or packed struct.
1371 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001372 Lex.Lex();
1373 if (Lex.getKind() == lltok::lbrace) {
1374 if (ParseStructType(Result, true) ||
1375 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001376 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001377 } else if (ParseArrayVectorType(Result, true))
1378 return true;
1379 break;
1380 case lltok::LocalVar:
1381 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1382 // TypeRec ::= %foo
1383 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1384 Result = T;
1385 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001386 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001387 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1388 std::make_pair(Result,
1389 Lex.getLoc())));
1390 M->addTypeName(Lex.getStrVal(), Result.get());
1391 }
1392 Lex.Lex();
1393 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001394
Chris Lattnerdf986172009-01-02 07:01:27 +00001395 case lltok::LocalVarID:
1396 // TypeRec ::= %4
1397 if (Lex.getUIntVal() < NumberedTypes.size())
1398 Result = NumberedTypes[Lex.getUIntVal()];
1399 else {
1400 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1401 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1402 if (I != ForwardRefTypeIDs.end())
1403 Result = I->second.first;
1404 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001405 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001406 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1407 std::make_pair(Result,
1408 Lex.getLoc())));
1409 }
1410 }
1411 Lex.Lex();
1412 break;
1413 case lltok::backslash: {
1414 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001415 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001416 unsigned Val;
1417 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001418 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001419 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1420 Result = OT;
1421 break;
1422 }
1423 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001424
1425 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001426 while (1) {
1427 switch (Lex.getKind()) {
1428 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001429 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001430
1431 // TypeRec ::= TypeRec '*'
1432 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001433 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001434 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001435 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001436 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001437 if (!PointerType::isValidElementType(Result.get()))
1438 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001439 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001440 Lex.Lex();
1441 break;
1442
1443 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1444 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001445 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001446 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001447 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001448 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001449 if (!PointerType::isValidElementType(Result.get()))
1450 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001451 unsigned AddrSpace;
1452 if (ParseOptionalAddrSpace(AddrSpace) ||
1453 ParseToken(lltok::star, "expected '*' in address space"))
1454 return true;
1455
Owen Andersondebcb012009-07-29 22:17:13 +00001456 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001457 break;
1458 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001459
Chris Lattnerdf986172009-01-02 07:01:27 +00001460 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1461 case lltok::lparen:
1462 if (ParseFunctionType(Result))
1463 return true;
1464 break;
1465 }
1466 }
1467}
1468
1469/// ParseParameterList
1470/// ::= '(' ')'
1471/// ::= '(' Arg (',' Arg)* ')'
1472/// Arg
1473/// ::= Type OptionalAttributes Value OptionalAttributes
1474bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1475 PerFunctionState &PFS) {
1476 if (ParseToken(lltok::lparen, "expected '(' in call"))
1477 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001478
Chris Lattnerdf986172009-01-02 07:01:27 +00001479 while (Lex.getKind() != lltok::rparen) {
1480 // If this isn't the first argument, we need a comma.
1481 if (!ArgList.empty() &&
1482 ParseToken(lltok::comma, "expected ',' in argument list"))
1483 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001484
Chris Lattnerdf986172009-01-02 07:01:27 +00001485 // Parse the argument.
1486 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001487 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001488 unsigned ArgAttrs1 = Attribute::None;
1489 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001490 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001491 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001492 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001493
Chris Lattner287881d2009-12-30 02:11:14 +00001494 // Otherwise, handle normal operands.
1495 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1496 ParseValue(ArgTy, V, PFS) ||
1497 // FIXME: Should not allow attributes after the argument, remove this
1498 // in LLVM 3.0.
1499 ParseOptionalAttrs(ArgAttrs2, 3))
1500 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001501 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1502 }
1503
1504 Lex.Lex(); // Lex the ')'.
1505 return false;
1506}
1507
1508
1509
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001510/// ParseArgumentList - Parse the argument list for a function type or function
1511/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001512/// ::= '(' ArgTypeListI ')'
1513/// ArgTypeListI
1514/// ::= /*empty*/
1515/// ::= '...'
1516/// ::= ArgTypeList ',' '...'
1517/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001518///
Chris Lattnerdf986172009-01-02 07:01:27 +00001519bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001520 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001521 isVarArg = false;
1522 assert(Lex.getKind() == lltok::lparen);
1523 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001524
Chris Lattnerdf986172009-01-02 07:01:27 +00001525 if (Lex.getKind() == lltok::rparen) {
1526 // empty
1527 } else if (Lex.getKind() == lltok::dotdotdot) {
1528 isVarArg = true;
1529 Lex.Lex();
1530 } else {
1531 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001532 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001533 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001534 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001535
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001536 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1537 // types (such as a function returning a pointer to itself). If parsing a
1538 // function prototype, we require fully resolved types.
1539 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001540 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001541
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001542 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001543 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001544
Chris Lattnerdf986172009-01-02 07:01:27 +00001545 if (Lex.getKind() == lltok::LocalVar ||
1546 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1547 Name = Lex.getStrVal();
1548 Lex.Lex();
1549 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001550
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001551 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001552 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001553
Chris Lattnerdf986172009-01-02 07:01:27 +00001554 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001555
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001556 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001557 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001558 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001559 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001560 break;
1561 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001562
Chris Lattnerdf986172009-01-02 07:01:27 +00001563 // Otherwise must be an argument type.
1564 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001565 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001566 ParseOptionalAttrs(Attrs, 0)) return true;
1567
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001568 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001569 return Error(TypeLoc, "argument can not have void type");
1570
Chris Lattnerdf986172009-01-02 07:01:27 +00001571 if (Lex.getKind() == lltok::LocalVar ||
1572 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1573 Name = Lex.getStrVal();
1574 Lex.Lex();
1575 } else {
1576 Name = "";
1577 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001578
Duncan Sands47c51882010-02-16 14:50:09 +00001579 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001580 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001581
Chris Lattnerdf986172009-01-02 07:01:27 +00001582 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1583 }
1584 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001585
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001586 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001587}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001588
Chris Lattnerdf986172009-01-02 07:01:27 +00001589/// ParseFunctionType
1590/// ::= Type ArgumentList OptionalAttrs
1591bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1592 assert(Lex.getKind() == lltok::lparen);
1593
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001594 if (!FunctionType::isValidReturnType(Result))
1595 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001596
Chris Lattnerdf986172009-01-02 07:01:27 +00001597 std::vector<ArgInfo> ArgList;
1598 bool isVarArg;
1599 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001600 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001601 // FIXME: Allow, but ignore attributes on function types!
1602 // FIXME: Remove in LLVM 3.0
1603 ParseOptionalAttrs(Attrs, 2))
1604 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001605
Chris Lattnerdf986172009-01-02 07:01:27 +00001606 // Reject names on the arguments lists.
1607 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1608 if (!ArgList[i].Name.empty())
1609 return Error(ArgList[i].Loc, "argument name invalid in function type");
1610 if (!ArgList[i].Attrs != 0) {
1611 // Allow but ignore attributes on function types; this permits
1612 // auto-upgrade.
1613 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1614 }
1615 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001616
Chris Lattnerdf986172009-01-02 07:01:27 +00001617 std::vector<const Type*> ArgListTy;
1618 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1619 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001620
Owen Andersondebcb012009-07-29 22:17:13 +00001621 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001622 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001623 return false;
1624}
1625
1626/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1627/// TypeRec
1628/// ::= '{' '}'
1629/// ::= '{' TypeRec (',' TypeRec)* '}'
1630/// ::= '<' '{' '}' '>'
1631/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1632bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1633 assert(Lex.getKind() == lltok::lbrace);
1634 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001635
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001636 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001637 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001638 return false;
1639 }
1640
1641 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001642 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001643 if (ParseTypeRec(Result)) return true;
1644 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001645
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001646 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001647 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001648 if (!StructType::isValidElementType(Result))
1649 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001650
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001651 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001652 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001653 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001654
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001655 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001656 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001657 if (!StructType::isValidElementType(Result))
1658 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001659
Chris Lattnerdf986172009-01-02 07:01:27 +00001660 ParamsList.push_back(Result);
1661 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001662
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001663 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1664 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001665
Chris Lattnerdf986172009-01-02 07:01:27 +00001666 std::vector<const Type*> ParamsListTy;
1667 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1668 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001669 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001670 return false;
1671}
1672
1673/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1674/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001675/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001676/// ::= '[' APSINTVAL 'x' Types ']'
1677/// ::= '<' APSINTVAL 'x' Types '>'
1678bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1679 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1680 Lex.getAPSIntVal().getBitWidth() > 64)
1681 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001682
Chris Lattnerdf986172009-01-02 07:01:27 +00001683 LocTy SizeLoc = Lex.getLoc();
1684 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001685 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001686
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001687 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1688 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001689
1690 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001691 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001692 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001693
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001694 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001695 return Error(TypeLoc, "array and vector element type cannot be void");
1696
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001697 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1698 "expected end of sequential type"))
1699 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001700
Chris Lattnerdf986172009-01-02 07:01:27 +00001701 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001702 if (Size == 0)
1703 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001704 if ((unsigned)Size != Size)
1705 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001706 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001707 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001708 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001709 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001710 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001711 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001712 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001713 }
1714 return false;
1715}
1716
1717//===----------------------------------------------------------------------===//
1718// Function Semantic Analysis.
1719//===----------------------------------------------------------------------===//
1720
Chris Lattner09d9ef42009-10-28 03:39:23 +00001721LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1722 int functionNumber)
1723 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001724
1725 // Insert unnamed arguments into the NumberedVals list.
1726 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1727 AI != E; ++AI)
1728 if (!AI->hasName())
1729 NumberedVals.push_back(AI);
1730}
1731
1732LLParser::PerFunctionState::~PerFunctionState() {
1733 // If there were any forward referenced non-basicblock values, delete them.
1734 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1735 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1736 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001737 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001738 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001739 delete I->second.first;
1740 I->second.first = 0;
1741 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001742
Chris Lattnerdf986172009-01-02 07:01:27 +00001743 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1744 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1745 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001746 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001747 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001748 delete I->second.first;
1749 I->second.first = 0;
1750 }
1751}
1752
Chris Lattner09d9ef42009-10-28 03:39:23 +00001753bool LLParser::PerFunctionState::FinishFunction() {
1754 // Check to see if someone took the address of labels in this block.
1755 if (!P.ForwardRefBlockAddresses.empty()) {
1756 ValID FunctionID;
1757 if (!F.getName().empty()) {
1758 FunctionID.Kind = ValID::t_GlobalName;
1759 FunctionID.StrVal = F.getName();
1760 } else {
1761 FunctionID.Kind = ValID::t_GlobalID;
1762 FunctionID.UIntVal = FunctionNumber;
1763 }
1764
1765 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1766 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1767 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1768 // Resolve all these references.
1769 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1770 return true;
1771
1772 P.ForwardRefBlockAddresses.erase(FRBAI);
1773 }
1774 }
1775
Chris Lattnerdf986172009-01-02 07:01:27 +00001776 if (!ForwardRefVals.empty())
1777 return P.Error(ForwardRefVals.begin()->second.second,
1778 "use of undefined value '%" + ForwardRefVals.begin()->first +
1779 "'");
1780 if (!ForwardRefValIDs.empty())
1781 return P.Error(ForwardRefValIDs.begin()->second.second,
1782 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001783 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001784 return false;
1785}
1786
1787
1788/// GetVal - Get a value with the specified name or ID, creating a
1789/// forward reference record if needed. This can return null if the value
1790/// exists but does not have the right type.
1791Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1792 const Type *Ty, LocTy Loc) {
1793 // Look this name up in the normal function symbol table.
1794 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001795
Chris Lattnerdf986172009-01-02 07:01:27 +00001796 // If this is a forward reference for the value, see if we already created a
1797 // forward ref record.
1798 if (Val == 0) {
1799 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1800 I = ForwardRefVals.find(Name);
1801 if (I != ForwardRefVals.end())
1802 Val = I->second.first;
1803 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001804
Chris Lattnerdf986172009-01-02 07:01:27 +00001805 // If we have the value in the symbol table or fwd-ref table, return it.
1806 if (Val) {
1807 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001808 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001809 P.Error(Loc, "'%" + Name + "' is not a basic block");
1810 else
1811 P.Error(Loc, "'%" + Name + "' defined with type '" +
1812 Val->getType()->getDescription() + "'");
1813 return 0;
1814 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001815
Chris Lattnerdf986172009-01-02 07:01:27 +00001816 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001817 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001818 P.Error(Loc, "invalid use of a non-first-class type");
1819 return 0;
1820 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001821
Chris Lattnerdf986172009-01-02 07:01:27 +00001822 // Otherwise, create a new forward reference for this value and remember it.
1823 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001824 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001825 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001826 else
1827 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001828
Chris Lattnerdf986172009-01-02 07:01:27 +00001829 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1830 return FwdVal;
1831}
1832
1833Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1834 LocTy Loc) {
1835 // Look this name up in the normal function symbol table.
1836 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001837
Chris Lattnerdf986172009-01-02 07:01:27 +00001838 // If this is a forward reference for the value, see if we already created a
1839 // forward ref record.
1840 if (Val == 0) {
1841 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1842 I = ForwardRefValIDs.find(ID);
1843 if (I != ForwardRefValIDs.end())
1844 Val = I->second.first;
1845 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001846
Chris Lattnerdf986172009-01-02 07:01:27 +00001847 // If we have the value in the symbol table or fwd-ref table, return it.
1848 if (Val) {
1849 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001850 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001851 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001852 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001853 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001854 Val->getType()->getDescription() + "'");
1855 return 0;
1856 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001857
Duncan Sands47c51882010-02-16 14:50:09 +00001858 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001859 P.Error(Loc, "invalid use of a non-first-class type");
1860 return 0;
1861 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001862
Chris Lattnerdf986172009-01-02 07:01:27 +00001863 // Otherwise, create a new forward reference for this value and remember it.
1864 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001865 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001866 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001867 else
1868 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001869
Chris Lattnerdf986172009-01-02 07:01:27 +00001870 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1871 return FwdVal;
1872}
1873
1874/// SetInstName - After an instruction is parsed and inserted into its
1875/// basic block, this installs its name.
1876bool LLParser::PerFunctionState::SetInstName(int NameID,
1877 const std::string &NameStr,
1878 LocTy NameLoc, Instruction *Inst) {
1879 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001880 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001881 if (NameID != -1 || !NameStr.empty())
1882 return P.Error(NameLoc, "instructions returning void cannot have a name");
1883 return false;
1884 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001885
Chris Lattnerdf986172009-01-02 07:01:27 +00001886 // If this was a numbered instruction, verify that the instruction is the
1887 // expected value and resolve any forward references.
1888 if (NameStr.empty()) {
1889 // If neither a name nor an ID was specified, just use the next ID.
1890 if (NameID == -1)
1891 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001892
Chris Lattnerdf986172009-01-02 07:01:27 +00001893 if (unsigned(NameID) != NumberedVals.size())
1894 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001895 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001896
Chris Lattnerdf986172009-01-02 07:01:27 +00001897 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1898 ForwardRefValIDs.find(NameID);
1899 if (FI != ForwardRefValIDs.end()) {
1900 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001901 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001902 FI->second.first->getType()->getDescription() + "'");
1903 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001904 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001905 ForwardRefValIDs.erase(FI);
1906 }
1907
1908 NumberedVals.push_back(Inst);
1909 return false;
1910 }
1911
1912 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1913 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1914 FI = ForwardRefVals.find(NameStr);
1915 if (FI != ForwardRefVals.end()) {
1916 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001917 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001918 FI->second.first->getType()->getDescription() + "'");
1919 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001920 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001921 ForwardRefVals.erase(FI);
1922 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001923
Chris Lattnerdf986172009-01-02 07:01:27 +00001924 // Set the name on the instruction.
1925 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001926
Benjamin Krameraf812352010-10-16 11:28:23 +00001927 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001928 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001929 NameStr + "'");
1930 return false;
1931}
1932
1933/// GetBB - Get a basic block with the specified name or ID, creating a
1934/// forward reference record if needed.
1935BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1936 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001937 return cast_or_null<BasicBlock>(GetVal(Name,
1938 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001939}
1940
1941BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001942 return cast_or_null<BasicBlock>(GetVal(ID,
1943 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001944}
1945
1946/// DefineBB - Define the specified basic block, which is either named or
1947/// unnamed. If there is an error, this returns null otherwise it returns
1948/// the block being defined.
1949BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1950 LocTy Loc) {
1951 BasicBlock *BB;
1952 if (Name.empty())
1953 BB = GetBB(NumberedVals.size(), Loc);
1954 else
1955 BB = GetBB(Name, Loc);
1956 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001957
Chris Lattnerdf986172009-01-02 07:01:27 +00001958 // Move the block to the end of the function. Forward ref'd blocks are
1959 // inserted wherever they happen to be referenced.
1960 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001961
Chris Lattnerdf986172009-01-02 07:01:27 +00001962 // Remove the block from forward ref sets.
1963 if (Name.empty()) {
1964 ForwardRefValIDs.erase(NumberedVals.size());
1965 NumberedVals.push_back(BB);
1966 } else {
1967 // BB forward references are already in the function symbol table.
1968 ForwardRefVals.erase(Name);
1969 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001970
Chris Lattnerdf986172009-01-02 07:01:27 +00001971 return BB;
1972}
1973
1974//===----------------------------------------------------------------------===//
1975// Constants.
1976//===----------------------------------------------------------------------===//
1977
1978/// ParseValID - Parse an abstract value that doesn't necessarily have a
1979/// type implied. For example, if we parse "4" we don't know what integer type
1980/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001981/// sanity. PFS is used to convert function-local operands of metadata (since
1982/// metadata operands are not just parsed here but also converted to values).
1983/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001984bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001985 ID.Loc = Lex.getLoc();
1986 switch (Lex.getKind()) {
1987 default: return TokError("expected value token");
1988 case lltok::GlobalID: // @42
1989 ID.UIntVal = Lex.getUIntVal();
1990 ID.Kind = ValID::t_GlobalID;
1991 break;
1992 case lltok::GlobalVar: // @foo
1993 ID.StrVal = Lex.getStrVal();
1994 ID.Kind = ValID::t_GlobalName;
1995 break;
1996 case lltok::LocalVarID: // %42
1997 ID.UIntVal = Lex.getUIntVal();
1998 ID.Kind = ValID::t_LocalID;
1999 break;
2000 case lltok::LocalVar: // %foo
2001 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2002 ID.StrVal = Lex.getStrVal();
2003 ID.Kind = ValID::t_LocalName;
2004 break;
Dan Gohman83448032010-07-14 18:26:50 +00002005 case lltok::exclaim: // !42, !{...}, or !"foo"
2006 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002007 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002008 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002009 ID.Kind = ValID::t_APSInt;
2010 break;
2011 case lltok::APFloat:
2012 ID.APFloatVal = Lex.getAPFloatVal();
2013 ID.Kind = ValID::t_APFloat;
2014 break;
2015 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002016 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002017 ID.Kind = ValID::t_Constant;
2018 break;
2019 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002020 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002021 ID.Kind = ValID::t_Constant;
2022 break;
2023 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2024 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2025 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002026
Chris Lattnerdf986172009-01-02 07:01:27 +00002027 case lltok::lbrace: {
2028 // ValID ::= '{' ConstVector '}'
2029 Lex.Lex();
2030 SmallVector<Constant*, 16> Elts;
2031 if (ParseGlobalValueVector(Elts) ||
2032 ParseToken(lltok::rbrace, "expected end of struct constant"))
2033 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002034
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002035 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2036 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002037 ID.Kind = ValID::t_Constant;
2038 return false;
2039 }
2040 case lltok::less: {
2041 // ValID ::= '<' ConstVector '>' --> Vector.
2042 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2043 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002044 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002045
Chris Lattnerdf986172009-01-02 07:01:27 +00002046 SmallVector<Constant*, 16> Elts;
2047 LocTy FirstEltLoc = Lex.getLoc();
2048 if (ParseGlobalValueVector(Elts) ||
2049 (isPackedStruct &&
2050 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2051 ParseToken(lltok::greater, "expected end of constant"))
2052 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002053
Chris Lattnerdf986172009-01-02 07:01:27 +00002054 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002055 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002056 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002057 ID.Kind = ValID::t_Constant;
2058 return false;
2059 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002060
Chris Lattnerdf986172009-01-02 07:01:27 +00002061 if (Elts.empty())
2062 return Error(ID.Loc, "constant vector must not be empty");
2063
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002064 if (!Elts[0]->getType()->isIntegerTy() &&
2065 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002066 return Error(FirstEltLoc,
2067 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002068
Chris Lattnerdf986172009-01-02 07:01:27 +00002069 // Verify that all the vector elements have the same type.
2070 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2071 if (Elts[i]->getType() != Elts[0]->getType())
2072 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002073 "vector element #" + Twine(i) +
Chris Lattnerdf986172009-01-02 07:01:27 +00002074 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002075
Owen Andersonaf7ec972009-07-28 21:19:26 +00002076 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002077 ID.Kind = ValID::t_Constant;
2078 return false;
2079 }
2080 case lltok::lsquare: { // Array Constant
2081 Lex.Lex();
2082 SmallVector<Constant*, 16> Elts;
2083 LocTy FirstEltLoc = Lex.getLoc();
2084 if (ParseGlobalValueVector(Elts) ||
2085 ParseToken(lltok::rsquare, "expected end of array constant"))
2086 return true;
2087
2088 // Handle empty element.
2089 if (Elts.empty()) {
2090 // Use undef instead of an array because it's inconvenient to determine
2091 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002092 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002093 return false;
2094 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002095
Chris Lattnerdf986172009-01-02 07:01:27 +00002096 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002097 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002098 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002099
Owen Andersondebcb012009-07-29 22:17:13 +00002100 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002101
Chris Lattnerdf986172009-01-02 07:01:27 +00002102 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002103 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002104 if (Elts[i]->getType() != Elts[0]->getType())
2105 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002106 "array element #" + Twine(i) +
Chris Lattnerdf986172009-01-02 07:01:27 +00002107 " is not of type '" +Elts[0]->getType()->getDescription());
2108 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002109
Owen Anderson1fd70962009-07-28 18:32:17 +00002110 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002111 ID.Kind = ValID::t_Constant;
2112 return false;
2113 }
2114 case lltok::kw_c: // c "foo"
2115 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002116 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002117 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2118 ID.Kind = ValID::t_Constant;
2119 return false;
2120
2121 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002122 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2123 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002124 Lex.Lex();
2125 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002126 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002127 ParseStringConstant(ID.StrVal) ||
2128 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002129 ParseToken(lltok::StringConstant, "expected constraint string"))
2130 return true;
2131 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002132 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002133 ID.Kind = ValID::t_InlineAsm;
2134 return false;
2135 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002136
Chris Lattner09d9ef42009-10-28 03:39:23 +00002137 case lltok::kw_blockaddress: {
2138 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2139 Lex.Lex();
2140
2141 ValID Fn, Label;
2142 LocTy FnLoc, LabelLoc;
2143
2144 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2145 ParseValID(Fn) ||
2146 ParseToken(lltok::comma, "expected comma in block address expression")||
2147 ParseValID(Label) ||
2148 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2149 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002150
Chris Lattner09d9ef42009-10-28 03:39:23 +00002151 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2152 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002153 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002154 return Error(Label.Loc, "expected basic block name in blockaddress");
2155
2156 // Make a global variable as a placeholder for this reference.
2157 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2158 false, GlobalValue::InternalLinkage,
2159 0, "");
2160 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2161 ID.ConstantVal = FwdRef;
2162 ID.Kind = ValID::t_Constant;
2163 return false;
2164 }
2165
Chris Lattnerdf986172009-01-02 07:01:27 +00002166 case lltok::kw_trunc:
2167 case lltok::kw_zext:
2168 case lltok::kw_sext:
2169 case lltok::kw_fptrunc:
2170 case lltok::kw_fpext:
2171 case lltok::kw_bitcast:
2172 case lltok::kw_uitofp:
2173 case lltok::kw_sitofp:
2174 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002175 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002176 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002177 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002178 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002179 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002180 Constant *SrcVal;
2181 Lex.Lex();
2182 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2183 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002184 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002185 ParseType(DestTy) ||
2186 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2187 return true;
2188 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2189 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2190 SrcVal->getType()->getDescription() + "' to '" +
2191 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002192 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002193 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002194 ID.Kind = ValID::t_Constant;
2195 return false;
2196 }
2197 case lltok::kw_extractvalue: {
2198 Lex.Lex();
2199 Constant *Val;
2200 SmallVector<unsigned, 4> Indices;
2201 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2202 ParseGlobalTypeAndValue(Val) ||
2203 ParseIndexList(Indices) ||
2204 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2205 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002206
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002207 if (!Val->getType()->isAggregateType())
2208 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002209 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2210 Indices.end()))
2211 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002212 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002213 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002214 ID.Kind = ValID::t_Constant;
2215 return false;
2216 }
2217 case lltok::kw_insertvalue: {
2218 Lex.Lex();
2219 Constant *Val0, *Val1;
2220 SmallVector<unsigned, 4> Indices;
2221 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2222 ParseGlobalTypeAndValue(Val0) ||
2223 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2224 ParseGlobalTypeAndValue(Val1) ||
2225 ParseIndexList(Indices) ||
2226 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2227 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002228 if (!Val0->getType()->isAggregateType())
2229 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002230 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2231 Indices.end()))
2232 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002233 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002234 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002235 ID.Kind = ValID::t_Constant;
2236 return false;
2237 }
2238 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002239 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002240 unsigned PredVal, Opc = Lex.getUIntVal();
2241 Constant *Val0, *Val1;
2242 Lex.Lex();
2243 if (ParseCmpPredicate(PredVal, Opc) ||
2244 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2245 ParseGlobalTypeAndValue(Val0) ||
2246 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2247 ParseGlobalTypeAndValue(Val1) ||
2248 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2249 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002250
Chris Lattnerdf986172009-01-02 07:01:27 +00002251 if (Val0->getType() != Val1->getType())
2252 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002253
Chris Lattnerdf986172009-01-02 07:01:27 +00002254 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002255
Chris Lattnerdf986172009-01-02 07:01:27 +00002256 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002257 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002258 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002259 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002260 } else {
2261 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002262 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002263 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002264 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002265 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002266 }
2267 ID.Kind = ValID::t_Constant;
2268 return false;
2269 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002270
Chris Lattnerdf986172009-01-02 07:01:27 +00002271 // Binary Operators.
2272 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002273 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002274 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002275 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002276 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002277 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002278 case lltok::kw_udiv:
2279 case lltok::kw_sdiv:
2280 case lltok::kw_fdiv:
2281 case lltok::kw_urem:
2282 case lltok::kw_srem:
2283 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002284 bool NUW = false;
2285 bool NSW = false;
2286 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002287 unsigned Opc = Lex.getUIntVal();
2288 Constant *Val0, *Val1;
2289 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002290 LocTy ModifierLoc = Lex.getLoc();
2291 if (Opc == Instruction::Add ||
2292 Opc == Instruction::Sub ||
2293 Opc == Instruction::Mul) {
2294 if (EatIfPresent(lltok::kw_nuw))
2295 NUW = true;
2296 if (EatIfPresent(lltok::kw_nsw)) {
2297 NSW = true;
2298 if (EatIfPresent(lltok::kw_nuw))
2299 NUW = true;
2300 }
2301 } else if (Opc == Instruction::SDiv) {
2302 if (EatIfPresent(lltok::kw_exact))
2303 Exact = true;
2304 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002305 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2306 ParseGlobalTypeAndValue(Val0) ||
2307 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2308 ParseGlobalTypeAndValue(Val1) ||
2309 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2310 return true;
2311 if (Val0->getType() != Val1->getType())
2312 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002313 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002314 if (NUW)
2315 return Error(ModifierLoc, "nuw only applies to integer operations");
2316 if (NSW)
2317 return Error(ModifierLoc, "nsw only applies to integer operations");
2318 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002319 // Check that the type is valid for the operator.
2320 switch (Opc) {
2321 case Instruction::Add:
2322 case Instruction::Sub:
2323 case Instruction::Mul:
2324 case Instruction::UDiv:
2325 case Instruction::SDiv:
2326 case Instruction::URem:
2327 case Instruction::SRem:
2328 if (!Val0->getType()->isIntOrIntVectorTy())
2329 return Error(ID.Loc, "constexpr requires integer operands");
2330 break;
2331 case Instruction::FAdd:
2332 case Instruction::FSub:
2333 case Instruction::FMul:
2334 case Instruction::FDiv:
2335 case Instruction::FRem:
2336 if (!Val0->getType()->isFPOrFPVectorTy())
2337 return Error(ID.Loc, "constexpr requires fp operands");
2338 break;
2339 default: llvm_unreachable("Unknown binary operator!");
2340 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002341 unsigned Flags = 0;
2342 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2343 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2344 if (Exact) Flags |= SDivOperator::IsExact;
2345 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002346 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002347 ID.Kind = ValID::t_Constant;
2348 return false;
2349 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002350
Chris Lattnerdf986172009-01-02 07:01:27 +00002351 // Logical Operations
2352 case lltok::kw_shl:
2353 case lltok::kw_lshr:
2354 case lltok::kw_ashr:
2355 case lltok::kw_and:
2356 case lltok::kw_or:
2357 case lltok::kw_xor: {
2358 unsigned Opc = Lex.getUIntVal();
2359 Constant *Val0, *Val1;
2360 Lex.Lex();
2361 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2362 ParseGlobalTypeAndValue(Val0) ||
2363 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2364 ParseGlobalTypeAndValue(Val1) ||
2365 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2366 return true;
2367 if (Val0->getType() != Val1->getType())
2368 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002369 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002370 return Error(ID.Loc,
2371 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002372 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002373 ID.Kind = ValID::t_Constant;
2374 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002375 }
2376
Chris Lattnerdf986172009-01-02 07:01:27 +00002377 case lltok::kw_getelementptr:
2378 case lltok::kw_shufflevector:
2379 case lltok::kw_insertelement:
2380 case lltok::kw_extractelement:
2381 case lltok::kw_select: {
2382 unsigned Opc = Lex.getUIntVal();
2383 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002384 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002385 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002386 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002387 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002388 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2389 ParseGlobalValueVector(Elts) ||
2390 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2391 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002392
Chris Lattnerdf986172009-01-02 07:01:27 +00002393 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002394 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002395 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002396
Chris Lattnerdf986172009-01-02 07:01:27 +00002397 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002398 (Value**)(Elts.data() + 1),
2399 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002400 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002401 ID.ConstantVal = InBounds ?
2402 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2403 Elts.data() + 1,
2404 Elts.size() - 1) :
2405 ConstantExpr::getGetElementPtr(Elts[0],
2406 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002407 } else if (Opc == Instruction::Select) {
2408 if (Elts.size() != 3)
2409 return Error(ID.Loc, "expected three operands to select");
2410 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2411 Elts[2]))
2412 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002413 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002414 } else if (Opc == Instruction::ShuffleVector) {
2415 if (Elts.size() != 3)
2416 return Error(ID.Loc, "expected three operands to shufflevector");
2417 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2418 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002419 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002420 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002421 } else if (Opc == Instruction::ExtractElement) {
2422 if (Elts.size() != 2)
2423 return Error(ID.Loc, "expected two operands to extractelement");
2424 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2425 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002426 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002427 } else {
2428 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2429 if (Elts.size() != 3)
2430 return Error(ID.Loc, "expected three operands to insertelement");
2431 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2432 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002433 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002434 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002435 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002436
Chris Lattnerdf986172009-01-02 07:01:27 +00002437 ID.Kind = ValID::t_Constant;
2438 return false;
2439 }
2440 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002441
Chris Lattnerdf986172009-01-02 07:01:27 +00002442 Lex.Lex();
2443 return false;
2444}
2445
2446/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002447bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2448 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002449 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002450 Value *V = NULL;
2451 bool Parsed = ParseValID(ID) ||
2452 ConvertValIDToValue(Ty, ID, V, NULL);
2453 if (V && !(C = dyn_cast<Constant>(V)))
2454 return Error(ID.Loc, "global values must be constants");
2455 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002456}
2457
Victor Hernandez92f238d2010-01-11 22:31:58 +00002458bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2459 PATypeHolder Type(Type::getVoidTy(Context));
2460 return ParseType(Type) ||
2461 ParseGlobalValue(Type, V);
2462}
2463
2464/// ParseGlobalValueVector
2465/// ::= /*empty*/
2466/// ::= TypeAndValue (',' TypeAndValue)*
2467bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2468 // Empty list.
2469 if (Lex.getKind() == lltok::rbrace ||
2470 Lex.getKind() == lltok::rsquare ||
2471 Lex.getKind() == lltok::greater ||
2472 Lex.getKind() == lltok::rparen)
2473 return false;
2474
2475 Constant *C;
2476 if (ParseGlobalTypeAndValue(C)) return true;
2477 Elts.push_back(C);
2478
2479 while (EatIfPresent(lltok::comma)) {
2480 if (ParseGlobalTypeAndValue(C)) return true;
2481 Elts.push_back(C);
2482 }
2483
2484 return false;
2485}
2486
Dan Gohman309b3af2010-08-24 02:24:03 +00002487bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2488 assert(Lex.getKind() == lltok::lbrace);
2489 Lex.Lex();
2490
2491 SmallVector<Value*, 16> Elts;
2492 if (ParseMDNodeVector(Elts, PFS) ||
2493 ParseToken(lltok::rbrace, "expected end of metadata node"))
2494 return true;
2495
2496 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
2497 ID.Kind = ValID::t_MDNode;
2498 return false;
2499}
2500
Dan Gohman83448032010-07-14 18:26:50 +00002501/// ParseMetadataValue
2502/// ::= !42
2503/// ::= !{...}
2504/// ::= !"string"
2505bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2506 assert(Lex.getKind() == lltok::exclaim);
2507 Lex.Lex();
2508
2509 // MDNode:
2510 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002511 if (Lex.getKind() == lltok::lbrace)
2512 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002513
2514 // Standalone metadata reference
2515 // !42
2516 if (Lex.getKind() == lltok::APSInt) {
2517 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2518 ID.Kind = ValID::t_MDNode;
2519 return false;
2520 }
2521
2522 // MDString:
2523 // ::= '!' STRINGCONSTANT
2524 if (ParseMDString(ID.MDStringVal)) return true;
2525 ID.Kind = ValID::t_MDString;
2526 return false;
2527}
2528
Victor Hernandez92f238d2010-01-11 22:31:58 +00002529
2530//===----------------------------------------------------------------------===//
2531// Function Parsing.
2532//===----------------------------------------------------------------------===//
2533
2534bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2535 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002536 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002537 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002538
Chris Lattnerdf986172009-01-02 07:01:27 +00002539 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002540 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002541 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002542 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2543 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2544 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002545 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002546 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2547 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2548 return (V == 0);
2549 case ValID::t_InlineAsm: {
2550 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2551 const FunctionType *FTy =
2552 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2553 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2554 return Error(ID.Loc, "invalid type for inline asm constraint string");
2555 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2556 return false;
2557 }
2558 case ValID::t_MDNode:
2559 if (!Ty->isMetadataTy())
2560 return Error(ID.Loc, "metadata value must have metadata type");
2561 V = ID.MDNodeVal;
2562 return false;
2563 case ValID::t_MDString:
2564 if (!Ty->isMetadataTy())
2565 return Error(ID.Loc, "metadata value must have metadata type");
2566 V = ID.MDStringVal;
2567 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002568 case ValID::t_GlobalName:
2569 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2570 return V == 0;
2571 case ValID::t_GlobalID:
2572 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2573 return V == 0;
2574 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002575 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002576 return Error(ID.Loc, "integer constant must have integer type");
2577 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002578 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002579 return false;
2580 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002581 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002582 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2583 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002584
Chris Lattnerdf986172009-01-02 07:01:27 +00002585 // The lexer has no type info, so builds all float and double FP constants
2586 // as double. Fix this here. Long double does not need this.
2587 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002588 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002589 bool Ignored;
2590 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2591 &Ignored);
2592 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002593 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002594
Chris Lattner959873d2009-01-05 18:24:23 +00002595 if (V->getType() != Ty)
2596 return Error(ID.Loc, "floating point constant does not have type '" +
2597 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002598
Chris Lattnerdf986172009-01-02 07:01:27 +00002599 return false;
2600 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002601 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002602 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002603 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002604 return false;
2605 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002606 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002607 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002608 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002609 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002610 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002611 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002612 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002613 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002614 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002615 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002616 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002617 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002618 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002619 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002620 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002621 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002622 return false;
2623 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002624 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002625 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002626
Chris Lattnerdf986172009-01-02 07:01:27 +00002627 V = ID.ConstantVal;
2628 return false;
2629 }
2630}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002631
Chris Lattnerdf986172009-01-02 07:01:27 +00002632bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2633 V = 0;
2634 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002635 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002636 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002637}
2638
2639bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002640 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002641 return ParseType(T) ||
2642 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002643}
2644
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002645bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2646 PerFunctionState &PFS) {
2647 Value *V;
2648 Loc = Lex.getLoc();
2649 if (ParseTypeAndValue(V, PFS)) return true;
2650 if (!isa<BasicBlock>(V))
2651 return Error(Loc, "expected a basic block");
2652 BB = cast<BasicBlock>(V);
2653 return false;
2654}
2655
2656
Chris Lattnerdf986172009-01-02 07:01:27 +00002657/// FunctionHeader
2658/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2659/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2660/// OptionalAlign OptGC
2661bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2662 // Parse the linkage.
2663 LocTy LinkageLoc = Lex.getLoc();
2664 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002665
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002666 unsigned Visibility, RetAttrs;
2667 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002668 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002669 LocTy RetTypeLoc = Lex.getLoc();
2670 if (ParseOptionalLinkage(Linkage) ||
2671 ParseOptionalVisibility(Visibility) ||
2672 ParseOptionalCallingConv(CC) ||
2673 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002674 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002675 return true;
2676
2677 // Verify that the linkage is ok.
2678 switch ((GlobalValue::LinkageTypes)Linkage) {
2679 case GlobalValue::ExternalLinkage:
2680 break; // always ok.
2681 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002682 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002683 if (isDefine)
2684 return Error(LinkageLoc, "invalid linkage for function definition");
2685 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002686 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002687 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002688 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling55ae5152010-08-20 22:05:50 +00002689 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002690 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002691 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002692 case GlobalValue::LinkOnceAnyLinkage:
2693 case GlobalValue::LinkOnceODRLinkage:
2694 case GlobalValue::WeakAnyLinkage:
2695 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002696 case GlobalValue::DLLExportLinkage:
2697 if (!isDefine)
2698 return Error(LinkageLoc, "invalid linkage for function declaration");
2699 break;
2700 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002701 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002702 return Error(LinkageLoc, "invalid function linkage type");
2703 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002704
Chris Lattner99bb3152009-01-05 08:00:30 +00002705 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002706 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002707 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002708
Chris Lattnerdf986172009-01-02 07:01:27 +00002709 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002710
2711 std::string FunctionName;
2712 if (Lex.getKind() == lltok::GlobalVar) {
2713 FunctionName = Lex.getStrVal();
2714 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2715 unsigned NameID = Lex.getUIntVal();
2716
2717 if (NameID != NumberedVals.size())
2718 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002719 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002720 } else {
2721 return TokError("expected function name");
2722 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002723
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002724 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002725
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002726 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002727 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002728
Chris Lattnerdf986172009-01-02 07:01:27 +00002729 std::vector<ArgInfo> ArgList;
2730 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002731 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002732 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002733 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002734 std::string GC;
2735
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002736 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002737 ParseOptionalAttrs(FuncAttrs, 2) ||
2738 (EatIfPresent(lltok::kw_section) &&
2739 ParseStringConstant(Section)) ||
2740 ParseOptionalAlignment(Alignment) ||
2741 (EatIfPresent(lltok::kw_gc) &&
2742 ParseStringConstant(GC)))
2743 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002744
2745 // If the alignment was parsed as an attribute, move to the alignment field.
2746 if (FuncAttrs & Attribute::Alignment) {
2747 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2748 FuncAttrs &= ~Attribute::Alignment;
2749 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002750
Chris Lattnerdf986172009-01-02 07:01:27 +00002751 // Okay, if we got here, the function is syntactically valid. Convert types
2752 // and do semantic checks.
2753 std::vector<const Type*> ParamTypeList;
2754 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002755 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002756 // attributes.
2757 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2758 if (FuncAttrs & ObsoleteFuncAttrs) {
2759 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2760 FuncAttrs &= ~ObsoleteFuncAttrs;
2761 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002762
Chris Lattnerdf986172009-01-02 07:01:27 +00002763 if (RetAttrs != Attribute::None)
2764 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002765
Chris Lattnerdf986172009-01-02 07:01:27 +00002766 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2767 ParamTypeList.push_back(ArgList[i].Type);
2768 if (ArgList[i].Attrs != Attribute::None)
2769 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2770 }
2771
2772 if (FuncAttrs != Attribute::None)
2773 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2774
2775 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002776
Benjamin Kramerf0127052010-01-05 13:12:22 +00002777 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002778 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2779
Owen Andersonfba933c2009-07-01 23:57:11 +00002780 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002781 FunctionType::get(RetType, ParamTypeList, isVarArg);
2782 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002783
2784 Fn = 0;
2785 if (!FunctionName.empty()) {
2786 // If this was a definition of a forward reference, remove the definition
2787 // from the forward reference table and fill in the forward ref.
2788 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2789 ForwardRefVals.find(FunctionName);
2790 if (FRVI != ForwardRefVals.end()) {
2791 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002792 if (Fn->getType() != PFT)
2793 return Error(FRVI->second.second, "invalid forward reference to "
2794 "function '" + FunctionName + "' with wrong type!");
2795
Chris Lattnerdf986172009-01-02 07:01:27 +00002796 ForwardRefVals.erase(FRVI);
2797 } else if ((Fn = M->getFunction(FunctionName))) {
2798 // If this function already exists in the symbol table, then it is
2799 // multiply defined. We accept a few cases for old backwards compat.
2800 // FIXME: Remove this stuff for LLVM 3.0.
2801 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2802 (!Fn->isDeclaration() && isDefine)) {
2803 // If the redefinition has different type or different attributes,
2804 // reject it. If both have bodies, reject it.
2805 return Error(NameLoc, "invalid redefinition of function '" +
2806 FunctionName + "'");
2807 } else if (Fn->isDeclaration()) {
2808 // Make sure to strip off any argument names so we can't get conflicts.
2809 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2810 AI != AE; ++AI)
2811 AI->setName("");
2812 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002813 } else if (M->getNamedValue(FunctionName)) {
2814 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002815 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002816
Dan Gohman41905542009-08-29 23:37:49 +00002817 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002818 // If this is a definition of a forward referenced function, make sure the
2819 // types agree.
2820 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2821 = ForwardRefValIDs.find(NumberedVals.size());
2822 if (I != ForwardRefValIDs.end()) {
2823 Fn = cast<Function>(I->second.first);
2824 if (Fn->getType() != PFT)
2825 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002826 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002827 ForwardRefValIDs.erase(I);
2828 }
2829 }
2830
2831 if (Fn == 0)
2832 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2833 else // Move the forward-reference to the correct spot in the module.
2834 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2835
2836 if (FunctionName.empty())
2837 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002838
Chris Lattnerdf986172009-01-02 07:01:27 +00002839 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2840 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2841 Fn->setCallingConv(CC);
2842 Fn->setAttributes(PAL);
2843 Fn->setAlignment(Alignment);
2844 Fn->setSection(Section);
2845 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002846
Chris Lattnerdf986172009-01-02 07:01:27 +00002847 // Add all of the arguments we parsed to the function.
2848 Function::arg_iterator ArgIt = Fn->arg_begin();
2849 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002850 // If we run out of arguments in the Function prototype, exit early.
2851 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2852 if (ArgIt == Fn->arg_end()) break;
2853
Chris Lattnerdf986172009-01-02 07:01:27 +00002854 // If the argument has a name, insert it into the argument symbol table.
2855 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002856
Chris Lattnerdf986172009-01-02 07:01:27 +00002857 // Set the name, if it conflicted, it will be auto-renamed.
2858 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002859
Benjamin Krameraf812352010-10-16 11:28:23 +00002860 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002861 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2862 ArgList[i].Name + "'");
2863 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002864
Chris Lattnerdf986172009-01-02 07:01:27 +00002865 return false;
2866}
2867
2868
2869/// ParseFunctionBody
2870/// ::= '{' BasicBlock+ '}'
2871/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2872///
2873bool LLParser::ParseFunctionBody(Function &Fn) {
2874 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2875 return TokError("expected '{' in function body");
2876 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002877
Chris Lattner09d9ef42009-10-28 03:39:23 +00002878 int FunctionNumber = -1;
2879 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2880
2881 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002882
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002883 // We need at least one basic block.
2884 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2885 return TokError("function body requires at least one basic block");
2886
Chris Lattnerdf986172009-01-02 07:01:27 +00002887 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2888 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002889
Chris Lattnerdf986172009-01-02 07:01:27 +00002890 // Eat the }.
2891 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002892
Chris Lattnerdf986172009-01-02 07:01:27 +00002893 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002894 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002895}
2896
2897/// ParseBasicBlock
2898/// ::= LabelStr? Instruction*
2899bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2900 // If this basic block starts out with a name, remember it.
2901 std::string Name;
2902 LocTy NameLoc = Lex.getLoc();
2903 if (Lex.getKind() == lltok::LabelStr) {
2904 Name = Lex.getStrVal();
2905 Lex.Lex();
2906 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002907
Chris Lattnerdf986172009-01-02 07:01:27 +00002908 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2909 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002910
Chris Lattnerdf986172009-01-02 07:01:27 +00002911 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002912
Chris Lattnerdf986172009-01-02 07:01:27 +00002913 // Parse the instructions in this block until we get a terminator.
2914 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002915 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002916 do {
2917 // This instruction may have three possibilities for a name: a) none
2918 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2919 LocTy NameLoc = Lex.getLoc();
2920 int NameID = -1;
2921 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002922
Chris Lattnerdf986172009-01-02 07:01:27 +00002923 if (Lex.getKind() == lltok::LocalVarID) {
2924 NameID = Lex.getUIntVal();
2925 Lex.Lex();
2926 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2927 return true;
2928 } else if (Lex.getKind() == lltok::LocalVar ||
2929 // FIXME: REMOVE IN LLVM 3.0
2930 Lex.getKind() == lltok::StringConstant) {
2931 NameStr = Lex.getStrVal();
2932 Lex.Lex();
2933 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2934 return true;
2935 }
Devang Patelf633a062009-09-17 23:04:48 +00002936
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002937 switch (ParseInstruction(Inst, BB, PFS)) {
2938 default: assert(0 && "Unknown ParseInstruction result!");
2939 case InstError: return true;
2940 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002941 BB->getInstList().push_back(Inst);
2942
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002943 // With a normal result, we check to see if the instruction is followed by
2944 // a comma and metadata.
2945 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002946 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002947 return true;
2948 break;
2949 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002950 BB->getInstList().push_back(Inst);
2951
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002952 // If the instruction parser ate an extra comma at the end of it, it
2953 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002954 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002955 return true;
2956 break;
2957 }
Devang Patelf633a062009-09-17 23:04:48 +00002958
Chris Lattnerdf986172009-01-02 07:01:27 +00002959 // Set the name on the instruction.
2960 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2961 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002962
Chris Lattnerdf986172009-01-02 07:01:27 +00002963 return false;
2964}
2965
2966//===----------------------------------------------------------------------===//
2967// Instruction Parsing.
2968//===----------------------------------------------------------------------===//
2969
2970/// ParseInstruction - Parse one of the many different instructions.
2971///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002972int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2973 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002974 lltok::Kind Token = Lex.getKind();
2975 if (Token == lltok::Eof)
2976 return TokError("found end of file when expecting more instructions");
2977 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002978 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002979 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002980
Chris Lattnerdf986172009-01-02 07:01:27 +00002981 switch (Token) {
2982 default: return Error(Loc, "expected instruction opcode");
2983 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002984 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2985 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002986 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2987 case lltok::kw_br: return ParseBr(Inst, PFS);
2988 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002989 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002990 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2991 // Binary Operators.
2992 case lltok::kw_add:
2993 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002994 case lltok::kw_mul: {
2995 bool NUW = false;
2996 bool NSW = false;
2997 LocTy ModifierLoc = Lex.getLoc();
2998 if (EatIfPresent(lltok::kw_nuw))
2999 NUW = true;
3000 if (EatIfPresent(lltok::kw_nsw)) {
3001 NSW = true;
3002 if (EatIfPresent(lltok::kw_nuw))
3003 NUW = true;
3004 }
Dan Gohman1eaac532010-05-03 22:44:19 +00003005 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
Dan Gohman59858cf2009-07-27 16:11:46 +00003006 if (!Result) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003007 if (!Inst->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00003008 if (NUW)
3009 return Error(ModifierLoc, "nuw only applies to integer operations");
3010 if (NSW)
3011 return Error(ModifierLoc, "nsw only applies to integer operations");
3012 }
3013 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003014 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003015 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003016 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003017 }
3018 return Result;
3019 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003020 case lltok::kw_fadd:
3021 case lltok::kw_fsub:
3022 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3023
Dan Gohman59858cf2009-07-27 16:11:46 +00003024 case lltok::kw_sdiv: {
3025 bool Exact = false;
3026 if (EatIfPresent(lltok::kw_exact))
3027 Exact = true;
3028 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3029 if (!Result)
3030 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003031 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003032 return Result;
3033 }
3034
Chris Lattnerdf986172009-01-02 07:01:27 +00003035 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00003036 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003037 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00003038 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003039 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00003040 case lltok::kw_shl:
3041 case lltok::kw_lshr:
3042 case lltok::kw_ashr:
3043 case lltok::kw_and:
3044 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003045 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003046 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003047 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003048 // Casts.
3049 case lltok::kw_trunc:
3050 case lltok::kw_zext:
3051 case lltok::kw_sext:
3052 case lltok::kw_fptrunc:
3053 case lltok::kw_fpext:
3054 case lltok::kw_bitcast:
3055 case lltok::kw_uitofp:
3056 case lltok::kw_sitofp:
3057 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003058 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003059 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003060 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003061 // Other.
3062 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003063 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003064 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3065 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3066 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3067 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3068 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3069 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3070 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003071 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3072 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00003073 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003074 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3075 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3076 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003077 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00003078 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003079 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00003080 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003081 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003082 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003083 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3084 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3085 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3086 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3087 }
3088}
3089
3090/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3091bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003092 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003093 switch (Lex.getKind()) {
3094 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3095 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3096 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3097 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3098 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3099 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3100 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3101 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3102 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3103 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3104 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3105 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3106 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3107 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3108 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3109 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3110 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3111 }
3112 } else {
3113 switch (Lex.getKind()) {
3114 default: TokError("expected icmp predicate (e.g. 'eq')");
3115 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3116 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3117 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3118 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3119 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3120 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3121 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3122 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3123 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3124 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3125 }
3126 }
3127 Lex.Lex();
3128 return false;
3129}
3130
3131//===----------------------------------------------------------------------===//
3132// Terminator Instructions.
3133//===----------------------------------------------------------------------===//
3134
3135/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003136/// ::= 'ret' void (',' !dbg, !1)*
3137/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3138/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00003139/// [[obsolete: LLVM 3.0]]
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003140int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3141 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003142 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003143 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003144
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003145 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003146 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003147 return false;
3148 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003149
Chris Lattnerdf986172009-01-02 07:01:27 +00003150 Value *RV;
3151 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003152
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003153 bool ExtraComma = false;
Devang Patelf633a062009-09-17 23:04:48 +00003154 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003155 // Parse optional custom metadata, e.g. !dbg
Chris Lattner1d928312009-12-30 05:02:06 +00003156 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003157 ExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003158 } else {
3159 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003160 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3161 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003162 SmallVector<Value*, 8> RVs;
3163 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003164
Devang Patelf633a062009-09-17 23:04:48 +00003165 do {
Devang Patel0475c912009-09-29 00:01:14 +00003166 // If optional custom metadata, e.g. !dbg is seen then this is the
3167 // end of MRV.
Chris Lattner1d928312009-12-30 05:02:06 +00003168 if (Lex.getKind() == lltok::MetadataVar)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003169 break;
3170 if (ParseTypeAndValue(RV, PFS)) return true;
3171 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003172 } while (EatIfPresent(lltok::comma));
3173
3174 RV = UndefValue::get(PFS.getFunction().getReturnType());
3175 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003176 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3177 BB->getInstList().push_back(I);
3178 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003179 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003180 }
3181 }
Devang Patelf633a062009-09-17 23:04:48 +00003182
Owen Anderson1d0be152009-08-13 21:58:54 +00003183 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003184 return ExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003185}
3186
3187
3188/// ParseBr
3189/// ::= 'br' TypeAndValue
3190/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3191bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3192 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003193 Value *Op0;
3194 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003195 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003196
Chris Lattnerdf986172009-01-02 07:01:27 +00003197 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3198 Inst = BranchInst::Create(BB);
3199 return false;
3200 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003201
Owen Anderson1d0be152009-08-13 21:58:54 +00003202 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003203 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003204
Chris Lattnerdf986172009-01-02 07:01:27 +00003205 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003206 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003207 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003208 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003209 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003210
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003211 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003212 return false;
3213}
3214
3215/// ParseSwitch
3216/// Instruction
3217/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3218/// JumpTable
3219/// ::= (TypeAndValue ',' TypeAndValue)*
3220bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3221 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003222 Value *Cond;
3223 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003224 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3225 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003226 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003227 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3228 return true;
3229
Duncan Sands1df98592010-02-16 11:11:14 +00003230 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003231 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003232
Chris Lattnerdf986172009-01-02 07:01:27 +00003233 // Parse the jump table pairs.
3234 SmallPtrSet<Value*, 32> SeenCases;
3235 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3236 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003237 Value *Constant;
3238 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003239
Chris Lattnerdf986172009-01-02 07:01:27 +00003240 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3241 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003242 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003243 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003244
Chris Lattnerdf986172009-01-02 07:01:27 +00003245 if (!SeenCases.insert(Constant))
3246 return Error(CondLoc, "duplicate case value in switch");
3247 if (!isa<ConstantInt>(Constant))
3248 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003249
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003250 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003251 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003252
Chris Lattnerdf986172009-01-02 07:01:27 +00003253 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003254
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003255 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003256 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3257 SI->addCase(Table[i].first, Table[i].second);
3258 Inst = SI;
3259 return false;
3260}
3261
Chris Lattnerab21db72009-10-28 00:19:10 +00003262/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003263/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003264/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3265bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003266 LocTy AddrLoc;
3267 Value *Address;
3268 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003269 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3270 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003271 return true;
3272
Duncan Sands1df98592010-02-16 11:11:14 +00003273 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003274 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003275
3276 // Parse the destination list.
3277 SmallVector<BasicBlock*, 16> DestList;
3278
3279 if (Lex.getKind() != lltok::rsquare) {
3280 BasicBlock *DestBB;
3281 if (ParseTypeAndBasicBlock(DestBB, PFS))
3282 return true;
3283 DestList.push_back(DestBB);
3284
3285 while (EatIfPresent(lltok::comma)) {
3286 if (ParseTypeAndBasicBlock(DestBB, PFS))
3287 return true;
3288 DestList.push_back(DestBB);
3289 }
3290 }
3291
3292 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3293 return true;
3294
Chris Lattnerab21db72009-10-28 00:19:10 +00003295 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003296 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3297 IBI->addDestination(DestList[i]);
3298 Inst = IBI;
3299 return false;
3300}
3301
3302
Chris Lattnerdf986172009-01-02 07:01:27 +00003303/// ParseInvoke
3304/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3305/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3306bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3307 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003308 unsigned RetAttrs, FnAttrs;
3309 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003310 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003311 LocTy RetTypeLoc;
3312 ValID CalleeID;
3313 SmallVector<ParamInfo, 16> ArgList;
3314
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003315 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003316 if (ParseOptionalCallingConv(CC) ||
3317 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003318 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003319 ParseValID(CalleeID) ||
3320 ParseParameterList(ArgList, PFS) ||
3321 ParseOptionalAttrs(FnAttrs, 2) ||
3322 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003323 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003324 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003325 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003326 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003327
Chris Lattnerdf986172009-01-02 07:01:27 +00003328 // If RetType is a non-function pointer type, then this is the short syntax
3329 // for the call, which means that RetType is just the return type. Infer the
3330 // rest of the function argument types from the arguments that are present.
3331 const PointerType *PFTy = 0;
3332 const FunctionType *Ty = 0;
3333 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3334 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3335 // Pull out the types of all of the arguments...
3336 std::vector<const Type*> ParamTypes;
3337 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3338 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003339
Chris Lattnerdf986172009-01-02 07:01:27 +00003340 if (!FunctionType::isValidReturnType(RetType))
3341 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003342
Owen Andersondebcb012009-07-29 22:17:13 +00003343 Ty = FunctionType::get(RetType, ParamTypes, false);
3344 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003345 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003346
Chris Lattnerdf986172009-01-02 07:01:27 +00003347 // Look up the callee.
3348 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003349 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003350
Chris Lattnerdf986172009-01-02 07:01:27 +00003351 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3352 // function attributes.
3353 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3354 if (FnAttrs & ObsoleteFuncAttrs) {
3355 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3356 FnAttrs &= ~ObsoleteFuncAttrs;
3357 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003358
Chris Lattnerdf986172009-01-02 07:01:27 +00003359 // Set up the Attributes for the function.
3360 SmallVector<AttributeWithIndex, 8> Attrs;
3361 if (RetAttrs != Attribute::None)
3362 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003363
Chris Lattnerdf986172009-01-02 07:01:27 +00003364 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003365
Chris Lattnerdf986172009-01-02 07:01:27 +00003366 // Loop through FunctionType's arguments and ensure they are specified
3367 // correctly. Also, gather any parameter attributes.
3368 FunctionType::param_iterator I = Ty->param_begin();
3369 FunctionType::param_iterator E = Ty->param_end();
3370 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3371 const Type *ExpectedTy = 0;
3372 if (I != E) {
3373 ExpectedTy = *I++;
3374 } else if (!Ty->isVarArg()) {
3375 return Error(ArgList[i].Loc, "too many arguments specified");
3376 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003377
Chris Lattnerdf986172009-01-02 07:01:27 +00003378 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3379 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3380 ExpectedTy->getDescription() + "'");
3381 Args.push_back(ArgList[i].V);
3382 if (ArgList[i].Attrs != Attribute::None)
3383 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3384 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003385
Chris Lattnerdf986172009-01-02 07:01:27 +00003386 if (I != E)
3387 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003388
Chris Lattnerdf986172009-01-02 07:01:27 +00003389 if (FnAttrs != Attribute::None)
3390 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003391
Chris Lattnerdf986172009-01-02 07:01:27 +00003392 // Finish off the Attributes and check them
3393 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003394
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003395 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003396 Args.begin(), Args.end());
3397 II->setCallingConv(CC);
3398 II->setAttributes(PAL);
3399 Inst = II;
3400 return false;
3401}
3402
3403
3404
3405//===----------------------------------------------------------------------===//
3406// Binary Operators.
3407//===----------------------------------------------------------------------===//
3408
3409/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003410/// ::= ArithmeticOps TypeAndValue ',' Value
3411///
3412/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3413/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003414bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003415 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003416 LocTy Loc; Value *LHS, *RHS;
3417 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3418 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3419 ParseValue(LHS->getType(), RHS, PFS))
3420 return true;
3421
Chris Lattnere914b592009-01-05 08:24:46 +00003422 bool Valid;
3423 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003424 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003425 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003426 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3427 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003428 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003429 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3430 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003431 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003432
Chris Lattnere914b592009-01-05 08:24:46 +00003433 if (!Valid)
3434 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003435
Chris Lattnerdf986172009-01-02 07:01:27 +00003436 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3437 return false;
3438}
3439
3440/// ParseLogical
3441/// ::= ArithmeticOps TypeAndValue ',' Value {
3442bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3443 unsigned Opc) {
3444 LocTy Loc; Value *LHS, *RHS;
3445 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3446 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3447 ParseValue(LHS->getType(), RHS, PFS))
3448 return true;
3449
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003450 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003451 return Error(Loc,"instruction requires integer or integer vector operands");
3452
3453 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3454 return false;
3455}
3456
3457
3458/// ParseCompare
3459/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3460/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003461bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3462 unsigned Opc) {
3463 // Parse the integer/fp comparison predicate.
3464 LocTy Loc;
3465 unsigned Pred;
3466 Value *LHS, *RHS;
3467 if (ParseCmpPredicate(Pred, Opc) ||
3468 ParseTypeAndValue(LHS, Loc, PFS) ||
3469 ParseToken(lltok::comma, "expected ',' after compare value") ||
3470 ParseValue(LHS->getType(), RHS, PFS))
3471 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003472
Chris Lattnerdf986172009-01-02 07:01:27 +00003473 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003474 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003475 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003476 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003477 } else {
3478 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003479 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003480 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003481 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003482 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003483 }
3484 return false;
3485}
3486
3487//===----------------------------------------------------------------------===//
3488// Other Instructions.
3489//===----------------------------------------------------------------------===//
3490
3491
3492/// ParseCast
3493/// ::= CastOpc TypeAndValue 'to' Type
3494bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3495 unsigned Opc) {
3496 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003497 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003498 if (ParseTypeAndValue(Op, Loc, PFS) ||
3499 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3500 ParseType(DestTy))
3501 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003502
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003503 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3504 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003505 return Error(Loc, "invalid cast opcode for cast from '" +
3506 Op->getType()->getDescription() + "' to '" +
3507 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003508 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003509 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3510 return false;
3511}
3512
3513/// ParseSelect
3514/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3515bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3516 LocTy Loc;
3517 Value *Op0, *Op1, *Op2;
3518 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3519 ParseToken(lltok::comma, "expected ',' after select condition") ||
3520 ParseTypeAndValue(Op1, PFS) ||
3521 ParseToken(lltok::comma, "expected ',' after select value") ||
3522 ParseTypeAndValue(Op2, PFS))
3523 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003524
Chris Lattnerdf986172009-01-02 07:01:27 +00003525 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3526 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003527
Chris Lattnerdf986172009-01-02 07:01:27 +00003528 Inst = SelectInst::Create(Op0, Op1, Op2);
3529 return false;
3530}
3531
Chris Lattner0088a5c2009-01-05 08:18:44 +00003532/// ParseVA_Arg
3533/// ::= 'va_arg' TypeAndValue ',' Type
3534bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003535 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003536 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003537 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003538 if (ParseTypeAndValue(Op, PFS) ||
3539 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003540 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003541 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003542
Chris Lattner0088a5c2009-01-05 08:18:44 +00003543 if (!EltTy->isFirstClassType())
3544 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003545
3546 Inst = new VAArgInst(Op, EltTy);
3547 return false;
3548}
3549
3550/// ParseExtractElement
3551/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3552bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3553 LocTy Loc;
3554 Value *Op0, *Op1;
3555 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3556 ParseToken(lltok::comma, "expected ',' after extract value") ||
3557 ParseTypeAndValue(Op1, PFS))
3558 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003559
Chris Lattnerdf986172009-01-02 07:01:27 +00003560 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3561 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003562
Eric Christophera3500da2009-07-25 02:28:41 +00003563 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003564 return false;
3565}
3566
3567/// ParseInsertElement
3568/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3569bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3570 LocTy Loc;
3571 Value *Op0, *Op1, *Op2;
3572 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3573 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3574 ParseTypeAndValue(Op1, PFS) ||
3575 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3576 ParseTypeAndValue(Op2, PFS))
3577 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003578
Chris Lattnerdf986172009-01-02 07:01:27 +00003579 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003580 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003581
Chris Lattnerdf986172009-01-02 07:01:27 +00003582 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3583 return false;
3584}
3585
3586/// ParseShuffleVector
3587/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3588bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3589 LocTy Loc;
3590 Value *Op0, *Op1, *Op2;
3591 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3592 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3593 ParseTypeAndValue(Op1, PFS) ||
3594 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3595 ParseTypeAndValue(Op2, PFS))
3596 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003597
Chris Lattnerdf986172009-01-02 07:01:27 +00003598 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3599 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003600
Chris Lattnerdf986172009-01-02 07:01:27 +00003601 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3602 return false;
3603}
3604
3605/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003606/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003607int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003608 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003609 Value *Op0, *Op1;
3610 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003611
Chris Lattnerdf986172009-01-02 07:01:27 +00003612 if (ParseType(Ty) ||
3613 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3614 ParseValue(Ty, Op0, PFS) ||
3615 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003616 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003617 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3618 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003619
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003620 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003621 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3622 while (1) {
3623 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003624
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003625 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003626 break;
3627
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003628 if (Lex.getKind() == lltok::MetadataVar) {
3629 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003630 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003631 }
Devang Patela43d46f2009-10-16 18:45:49 +00003632
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003633 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003634 ParseValue(Ty, Op0, PFS) ||
3635 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003636 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003637 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3638 return true;
3639 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003640
Chris Lattnerdf986172009-01-02 07:01:27 +00003641 if (!Ty->isFirstClassType())
3642 return Error(TypeLoc, "phi node must have first class type");
3643
3644 PHINode *PN = PHINode::Create(Ty);
3645 PN->reserveOperandSpace(PHIVals.size());
3646 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3647 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3648 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003649 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003650}
3651
3652/// ParseCall
3653/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3654/// ParameterList OptionalAttrs
3655bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3656 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003657 unsigned RetAttrs, FnAttrs;
3658 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003659 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003660 LocTy RetTypeLoc;
3661 ValID CalleeID;
3662 SmallVector<ParamInfo, 16> ArgList;
3663 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003664
Chris Lattnerdf986172009-01-02 07:01:27 +00003665 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3666 ParseOptionalCallingConv(CC) ||
3667 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003668 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003669 ParseValID(CalleeID) ||
3670 ParseParameterList(ArgList, PFS) ||
3671 ParseOptionalAttrs(FnAttrs, 2))
3672 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003673
Chris Lattnerdf986172009-01-02 07:01:27 +00003674 // If RetType is a non-function pointer type, then this is the short syntax
3675 // for the call, which means that RetType is just the return type. Infer the
3676 // rest of the function argument types from the arguments that are present.
3677 const PointerType *PFTy = 0;
3678 const FunctionType *Ty = 0;
3679 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3680 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3681 // Pull out the types of all of the arguments...
3682 std::vector<const Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003683 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3684 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003685
Chris Lattnerdf986172009-01-02 07:01:27 +00003686 if (!FunctionType::isValidReturnType(RetType))
3687 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003688
Owen Andersondebcb012009-07-29 22:17:13 +00003689 Ty = FunctionType::get(RetType, ParamTypes, false);
3690 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003691 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003692
Chris Lattnerdf986172009-01-02 07:01:27 +00003693 // Look up the callee.
3694 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003695 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003696
Chris Lattnerdf986172009-01-02 07:01:27 +00003697 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3698 // function attributes.
3699 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3700 if (FnAttrs & ObsoleteFuncAttrs) {
3701 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3702 FnAttrs &= ~ObsoleteFuncAttrs;
3703 }
3704
3705 // Set up the Attributes for the function.
3706 SmallVector<AttributeWithIndex, 8> Attrs;
3707 if (RetAttrs != Attribute::None)
3708 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003709
Chris Lattnerdf986172009-01-02 07:01:27 +00003710 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003711
Chris Lattnerdf986172009-01-02 07:01:27 +00003712 // Loop through FunctionType's arguments and ensure they are specified
3713 // correctly. Also, gather any parameter attributes.
3714 FunctionType::param_iterator I = Ty->param_begin();
3715 FunctionType::param_iterator E = Ty->param_end();
3716 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3717 const Type *ExpectedTy = 0;
3718 if (I != E) {
3719 ExpectedTy = *I++;
3720 } else if (!Ty->isVarArg()) {
3721 return Error(ArgList[i].Loc, "too many arguments specified");
3722 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003723
Chris Lattnerdf986172009-01-02 07:01:27 +00003724 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3725 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3726 ExpectedTy->getDescription() + "'");
3727 Args.push_back(ArgList[i].V);
3728 if (ArgList[i].Attrs != Attribute::None)
3729 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3730 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003731
Chris Lattnerdf986172009-01-02 07:01:27 +00003732 if (I != E)
3733 return Error(CallLoc, "not enough parameters specified for call");
3734
3735 if (FnAttrs != Attribute::None)
3736 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3737
3738 // Finish off the Attributes and check them
3739 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003740
Chris Lattnerdf986172009-01-02 07:01:27 +00003741 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3742 CI->setTailCall(isTail);
3743 CI->setCallingConv(CC);
3744 CI->setAttributes(PAL);
3745 Inst = CI;
3746 return false;
3747}
3748
3749//===----------------------------------------------------------------------===//
3750// Memory Instructions.
3751//===----------------------------------------------------------------------===//
3752
3753/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003754/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3755/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003756int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3757 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003758 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003759 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003760 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003761 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003762 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003763
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003764 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003765 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003766 if (Lex.getKind() == lltok::kw_align) {
3767 if (ParseOptionalAlignment(Alignment)) return true;
3768 } else if (Lex.getKind() == lltok::MetadataVar) {
3769 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003770 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003771 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3772 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3773 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003774 }
3775 }
3776
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003777 if (Size && !Size->getType()->isIntegerTy())
3778 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003779
Victor Hernandez68afa542009-10-21 19:11:40 +00003780 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003781 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003782 return AteExtraComma ? InstExtraComma : InstNormal;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003783 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003784
3785 // Autoupgrade old malloc instruction to malloc call.
3786 // FIXME: Remove in LLVM 3.0.
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003787 if (Size && !Size->getType()->isIntegerTy(32))
3788 return Error(SizeLoc, "element count must be i32");
Victor Hernandez68afa542009-10-21 19:11:40 +00003789 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003790 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3791 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
Victor Hernandez68afa542009-10-21 19:11:40 +00003792 if (!MallocF)
3793 // Prototype malloc as "void *(int32)".
3794 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003795 MallocF = cast<Function>(
3796 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003797 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003798return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003799}
3800
3801/// ParseFree
3802/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003803bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3804 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003805 Value *Val; LocTy Loc;
3806 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003807 if (!Val->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003808 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003809 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003810 return false;
3811}
3812
3813/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003814/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003815int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3816 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003817 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003818 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003819 bool AteExtraComma = false;
3820 if (ParseTypeAndValue(Val, Loc, PFS) ||
3821 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3822 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003823
Duncan Sands1df98592010-02-16 11:11:14 +00003824 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003825 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3826 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003827
Chris Lattnerdf986172009-01-02 07:01:27 +00003828 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003829 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003830}
3831
3832/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003833/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003834int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3835 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003836 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003837 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003838 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003839 if (ParseTypeAndValue(Val, Loc, PFS) ||
3840 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003841 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3842 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003843 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003844
Duncan Sands1df98592010-02-16 11:11:14 +00003845 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003846 return Error(PtrLoc, "store operand must be a pointer");
3847 if (!Val->getType()->isFirstClassType())
3848 return Error(Loc, "store operand must be a first class value");
3849 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3850 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003851
Chris Lattnerdf986172009-01-02 07:01:27 +00003852 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003853 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003854}
3855
3856/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003857/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003858/// FIXME: Remove support for getresult in LLVM 3.0
3859bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3860 Value *Val; LocTy ValLoc, EltLoc;
3861 unsigned Element;
3862 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3863 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003864 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003865 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003866
Duncan Sands1df98592010-02-16 11:11:14 +00003867 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003868 return Error(ValLoc, "getresult inst requires an aggregate operand");
3869 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3870 return Error(EltLoc, "invalid getresult index for value");
3871 Inst = ExtractValueInst::Create(Val, Element);
3872 return false;
3873}
3874
3875/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003876/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003877int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003878 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003879
Dan Gohmandcb40a32009-07-29 15:58:36 +00003880 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003881
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003882 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003883
Duncan Sands1df98592010-02-16 11:11:14 +00003884 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003885 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003886
Chris Lattnerdf986172009-01-02 07:01:27 +00003887 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003888 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003889 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003890 if (Lex.getKind() == lltok::MetadataVar) {
3891 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003892 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003893 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003894 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003895 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003896 return Error(EltLoc, "getelementptr index must be an integer");
3897 Indices.push_back(Val);
3898 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003899
Chris Lattnerdf986172009-01-02 07:01:27 +00003900 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3901 Indices.begin(), Indices.end()))
3902 return Error(Loc, "invalid getelementptr indices");
3903 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003904 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003905 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003906 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003907}
3908
3909/// ParseExtractValue
3910/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003911int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003912 Value *Val; LocTy Loc;
3913 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003914 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003915 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003916 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003917 return true;
3918
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003919 if (!Val->getType()->isAggregateType())
3920 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003921
3922 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3923 Indices.end()))
3924 return Error(Loc, "invalid indices for extractvalue");
3925 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003926 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003927}
3928
3929/// ParseInsertValue
3930/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003931int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003932 Value *Val0, *Val1; LocTy Loc0, Loc1;
3933 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003934 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003935 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3936 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3937 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003938 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003939 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003940
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003941 if (!Val0->getType()->isAggregateType())
3942 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003943
Chris Lattnerdf986172009-01-02 07:01:27 +00003944 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3945 Indices.end()))
3946 return Error(Loc0, "invalid indices for insertvalue");
3947 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003948 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003949}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003950
3951//===----------------------------------------------------------------------===//
3952// Embedded metadata.
3953//===----------------------------------------------------------------------===//
3954
3955/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003956/// ::= Element (',' Element)*
3957/// Element
3958/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003959bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003960 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003961 // Check for an empty list.
3962 if (Lex.getKind() == lltok::rbrace)
3963 return false;
3964
Nick Lewycky21cc4462009-04-04 07:22:01 +00003965 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003966 // Null is a special case since it is typeless.
3967 if (EatIfPresent(lltok::kw_null)) {
3968 Elts.push_back(0);
3969 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003970 }
Chris Lattnera7352392009-12-30 04:42:57 +00003971
3972 Value *V = 0;
3973 PATypeHolder Ty(Type::getVoidTy(Context));
3974 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00003975 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00003976 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00003977 return true;
3978
Nick Lewyckycb337992009-05-10 20:57:05 +00003979 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003980 } while (EatIfPresent(lltok::comma));
3981
3982 return false;
3983}