blob: 61b1ae5e97cc91a17d0a944518e569c50bef3129 [file] [log] [blame]
Chris Lattnerdf986172009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
15#include "llvm/AutoUpgrade.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/InlineAsm.h"
20#include "llvm/Instructions.h"
21#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000022#include "llvm/Operator.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000023#include "llvm/ValueSymbolTable.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/StringExtras.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000026#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000027#include "llvm/Support/raw_ostream.h"
28using namespace llvm;
29
Chris Lattner3ed88ef2009-01-02 08:05:26 +000030/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000031bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000032 // Prime the lexer.
33 Lex.Lex();
34
Chris Lattnerad7d1e22009-01-04 20:44:11 +000035 return ParseTopLevelEntities() ||
36 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000037}
38
39/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
40/// module.
41bool LLParser::ValidateEndOfModule() {
Chris Lattner449c3102010-04-01 05:14:45 +000042 // Handle any instruction metadata forward references.
43 if (!ForwardRefInstMetadata.empty()) {
44 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
45 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
46 I != E; ++I) {
47 Instruction *Inst = I->first;
48 const std::vector<MDRef> &MDList = I->second;
49
50 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
51 unsigned SlotNo = MDList[i].MDSlot;
52
53 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
54 return Error(MDList[i].Loc, "use of undefined metadata '!" +
55 utostr(SlotNo) + "'");
56 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
57 }
58 }
59 ForwardRefInstMetadata.clear();
60 }
61
62
Victor Hernandez68afa542009-10-21 19:11:40 +000063 // Update auto-upgraded malloc calls to "malloc".
Chris Lattnercf4d2f12009-10-18 05:09:15 +000064 // FIXME: Remove in LLVM 3.0.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000065 if (MallocF) {
66 MallocF->setName("malloc");
67 // If setName() does not set the name to "malloc", then there is already a
68 // declaration of "malloc". In that case, iterate over all calls to MallocF
69 // and get them to call the declared "malloc" instead.
70 if (MallocF->getName() != "malloc") {
Chris Lattner09d9ef42009-10-28 03:39:23 +000071 Constant *RealMallocF = M->getFunction("malloc");
Victor Hernandez68afa542009-10-21 19:11:40 +000072 if (RealMallocF->getType() != MallocF->getType())
73 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
74 MallocF->replaceAllUsesWith(RealMallocF);
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000075 MallocF->eraseFromParent();
76 MallocF = NULL;
77 }
78 }
Chris Lattner09d9ef42009-10-28 03:39:23 +000079
80
81 // If there are entries in ForwardRefBlockAddresses at this point, they are
82 // references after the function was defined. Resolve those now.
83 while (!ForwardRefBlockAddresses.empty()) {
84 // Okay, we are referencing an already-parsed function, resolve them now.
85 Function *TheFn = 0;
86 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
87 if (Fn.Kind == ValID::t_GlobalName)
88 TheFn = M->getFunction(Fn.StrVal);
89 else if (Fn.UIntVal < NumberedVals.size())
90 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
91
92 if (TheFn == 0)
93 return Error(Fn.Loc, "unknown function referenced by blockaddress");
94
95 // Resolve all these references.
96 if (ResolveForwardRefBlockAddresses(TheFn,
97 ForwardRefBlockAddresses.begin()->second,
98 0))
99 return true;
100
101 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
102 }
103
104
Chris Lattnerdf986172009-01-02 07:01:27 +0000105 if (!ForwardRefTypes.empty())
106 return Error(ForwardRefTypes.begin()->second.second,
107 "use of undefined type named '" +
108 ForwardRefTypes.begin()->first + "'");
109 if (!ForwardRefTypeIDs.empty())
110 return Error(ForwardRefTypeIDs.begin()->second.second,
111 "use of undefined type '%" +
112 utostr(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000113
Chris Lattnerdf986172009-01-02 07:01:27 +0000114 if (!ForwardRefVals.empty())
115 return Error(ForwardRefVals.begin()->second.second,
116 "use of undefined value '@" + ForwardRefVals.begin()->first +
117 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000118
Chris Lattnerdf986172009-01-02 07:01:27 +0000119 if (!ForwardRefValIDs.empty())
120 return Error(ForwardRefValIDs.begin()->second.second,
121 "use of undefined value '@" +
122 utostr(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000123
Devang Patel1c7eea62009-07-08 19:23:54 +0000124 if (!ForwardRefMDNodes.empty())
125 return Error(ForwardRefMDNodes.begin()->second.second,
126 "use of undefined metadata '!" +
127 utostr(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000128
Devang Patel1c7eea62009-07-08 19:23:54 +0000129
Chris Lattnerdf986172009-01-02 07:01:27 +0000130 // Look for intrinsic functions and CallInst that need to be upgraded
131 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
132 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000133
Devang Patele4b27562009-08-28 23:24:31 +0000134 // Check debug info intrinsics.
135 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000136 return false;
137}
138
Chris Lattner09d9ef42009-10-28 03:39:23 +0000139bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
140 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
141 PerFunctionState *PFS) {
142 // Loop over all the references, resolving them.
143 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
144 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000145 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000146 if (Refs[i].first.Kind == ValID::t_LocalName)
147 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000148 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000149 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
150 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
151 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000152 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000153 } else {
154 Res = dyn_cast_or_null<BasicBlock>(
155 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
156 }
157
Chris Lattnercdfc9402009-11-01 01:27:45 +0000158 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000159 return Error(Refs[i].first.Loc,
160 "referenced value is not a basic block");
161
162 // Get the BlockAddress for this and update references to use it.
163 BlockAddress *BA = BlockAddress::get(TheFn, Res);
164 Refs[i].second->replaceAllUsesWith(BA);
165 Refs[i].second->eraseFromParent();
166 }
167 return false;
168}
169
170
Chris Lattnerdf986172009-01-02 07:01:27 +0000171//===----------------------------------------------------------------------===//
172// Top-Level Entities
173//===----------------------------------------------------------------------===//
174
175bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000176 while (1) {
177 switch (Lex.getKind()) {
178 default: return TokError("expected top-level entity");
179 case lltok::Eof: return false;
180 //case lltok::kw_define:
181 case lltok::kw_declare: if (ParseDeclare()) return true; break;
182 case lltok::kw_define: if (ParseDefine()) return true; break;
183 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
184 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
185 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
186 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000187 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000188 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
189 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000190 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000191 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000192 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000193 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000194
195 // The Global variable production with no name can have many different
196 // optional leading prefixes, the production is:
197 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
198 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000199 case lltok::kw_private: // OptionalLinkage
200 case lltok::kw_linker_private: // OptionalLinkage
201 case lltok::kw_linker_private_weak: // OptionalLinkage
202 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 '%" +
319 utostr(TypeID) + "'");
320 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 '%" +
446 utostr(VarID) + "'");
447 Lex.Lex(); // eat GlobalID;
448
449 if (ParseToken(lltok::equal, "expected '=' after name"))
450 return true;
451 }
452
453 bool HasLinkage;
454 unsigned Linkage, Visibility;
455 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
456 ParseOptionalVisibility(Visibility))
457 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000458
Dan Gohman3845e502009-08-12 23:32:33 +0000459 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
460 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
461 return ParseAlias(Name, NameLoc, Visibility);
462}
463
Chris Lattnerdf986172009-01-02 07:01:27 +0000464/// ParseNamedGlobal:
465/// GlobalVar '=' OptionalVisibility ALIAS ...
466/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
467bool LLParser::ParseNamedGlobal() {
468 assert(Lex.getKind() == lltok::GlobalVar);
469 LocTy NameLoc = Lex.getLoc();
470 std::string Name = Lex.getStrVal();
471 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000472
Chris Lattnerdf986172009-01-02 07:01:27 +0000473 bool HasLinkage;
474 unsigned Linkage, Visibility;
475 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
476 ParseOptionalLinkage(Linkage, HasLinkage) ||
477 ParseOptionalVisibility(Visibility))
478 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000479
Chris Lattnerdf986172009-01-02 07:01:27 +0000480 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
481 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
482 return ParseAlias(Name, NameLoc, Visibility);
483}
484
Devang Patel256be962009-07-20 19:00:08 +0000485// MDString:
486// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000487bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000488 std::string Str;
489 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000490 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000491 return false;
492}
493
494// MDNode:
495// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000496//
497/// This version of ParseMDNodeID returns the slot number and null in the case
498/// of a forward reference.
499bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
500 // !{ ..., !42, ... }
501 if (ParseUInt32(SlotNo)) return true;
502
503 // Check existing MDNode.
504 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
505 Result = NumberedMetadata[SlotNo];
506 else
507 Result = 0;
508 return false;
509}
510
Chris Lattner4a72efc2009-12-30 04:15:23 +0000511bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000512 // !{ ..., !42, ... }
513 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000514 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000515
Chris Lattner449c3102010-04-01 05:14:45 +0000516 // If not a forward reference, just return it now.
517 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000518
Chris Lattner449c3102010-04-01 05:14:45 +0000519 // Otherwise, create MDNode forward reference.
Chris Lattner42991ee2009-12-29 22:01:50 +0000520
521 // FIXME: This is not unique enough!
Devang Patel256be962009-07-20 19:00:08 +0000522 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Benjamin Kramerc17300f2009-12-29 22:17:06 +0000523 Value *V = MDString::get(Context, FwdRefName);
Chris Lattner42991ee2009-12-29 22:01:50 +0000524 MDNode *FwdNode = MDNode::get(Context, &V, 1);
Devang Patel256be962009-07-20 19:00:08 +0000525 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000526
527 if (NumberedMetadata.size() <= MID)
528 NumberedMetadata.resize(MID+1);
529 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000530 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000531 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000532}
Devang Patel256be962009-07-20 19:00:08 +0000533
Chris Lattner84d03b12009-12-29 22:35:39 +0000534/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000535/// !foo = !{ !1, !2 }
536bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000537 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000538 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000539 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000540
Chris Lattner84d03b12009-12-29 22:35:39 +0000541 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000542 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000543 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000544 return true;
545
Dan Gohman17aa92c2010-07-21 23:38:33 +0000546 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000547 if (Lex.getKind() != lltok::rbrace)
548 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000549 if (ParseToken(lltok::exclaim, "Expected '!' here"))
550 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000551
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000552 MDNode *N = 0;
553 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000554 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000555 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000556
557 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
558 return true;
559
Devang Pateleff2ab62009-07-29 00:34:02 +0000560 return false;
561}
562
Devang Patel923078c2009-07-01 19:21:12 +0000563/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000564/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000565bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000566 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000567 Lex.Lex();
568 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000569
570 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000571 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000572 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000573 if (ParseUInt32(MetadataID) ||
574 ParseToken(lltok::equal, "expected '=' here") ||
575 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000576 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000577 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000578 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000579 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000580 return true;
581
Owen Anderson647e3012009-07-31 21:35:40 +0000582 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000583
584 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000585 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000586 FI = ForwardRefMDNodes.find(MetadataID);
587 if (FI != ForwardRefMDNodes.end()) {
Chris Lattnere80250e2009-12-29 21:43:58 +0000588 FI->second.first->replaceAllUsesWith(Init);
Devang Patel1c7eea62009-07-08 19:23:54 +0000589 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000590
591 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
592 } else {
593 if (MetadataID >= NumberedMetadata.size())
594 NumberedMetadata.resize(MetadataID+1);
595
596 if (NumberedMetadata[MetadataID] != 0)
597 return TokError("Metadata id is already used");
598 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000599 }
600
Devang Patel923078c2009-07-01 19:21:12 +0000601 return false;
602}
603
Chris Lattnerdf986172009-01-02 07:01:27 +0000604/// ParseAlias:
605/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
606/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000607/// ::= TypeAndValue
608/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000609/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000610///
611/// Everything through visibility has already been parsed.
612///
613bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
614 unsigned Visibility) {
615 assert(Lex.getKind() == lltok::kw_alias);
616 Lex.Lex();
617 unsigned Linkage;
618 LocTy LinkageLoc = Lex.getLoc();
619 if (ParseOptionalLinkage(Linkage))
620 return true;
621
622 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000623 Linkage != GlobalValue::WeakAnyLinkage &&
624 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000625 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000626 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000627 Linkage != GlobalValue::LinkerPrivateLinkage &&
628 Linkage != GlobalValue::LinkerPrivateWeakLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000629 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000630
Chris Lattnerdf986172009-01-02 07:01:27 +0000631 Constant *Aliasee;
632 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000633 if (Lex.getKind() != lltok::kw_bitcast &&
634 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000635 if (ParseGlobalTypeAndValue(Aliasee)) return true;
636 } else {
637 // The bitcast dest type is not present, it is implied by the dest type.
638 ValID ID;
639 if (ParseValID(ID)) return true;
640 if (ID.Kind != ValID::t_Constant)
641 return Error(AliaseeLoc, "invalid aliasee");
642 Aliasee = ID.ConstantVal;
643 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000644
Duncan Sands1df98592010-02-16 11:11:14 +0000645 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000646 return Error(AliaseeLoc, "alias must have pointer type");
647
648 // Okay, create the alias but do not insert it into the module yet.
649 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
650 (GlobalValue::LinkageTypes)Linkage, Name,
651 Aliasee);
652 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000653
Chris Lattnerdf986172009-01-02 07:01:27 +0000654 // See if this value already exists in the symbol table. If so, it is either
655 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000656 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000657 // See if this was a redefinition. If so, there is no entry in
658 // ForwardRefVals.
659 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
660 I = ForwardRefVals.find(Name);
661 if (I == ForwardRefVals.end())
662 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
663
664 // Otherwise, this was a definition of forward ref. Verify that types
665 // agree.
666 if (Val->getType() != GA->getType())
667 return Error(NameLoc,
668 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000669
Chris Lattnerdf986172009-01-02 07:01:27 +0000670 // If they agree, just RAUW the old value with the alias and remove the
671 // forward ref info.
672 Val->replaceAllUsesWith(GA);
673 Val->eraseFromParent();
674 ForwardRefVals.erase(I);
675 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000676
Chris Lattnerdf986172009-01-02 07:01:27 +0000677 // Insert into the module, we know its name won't collide now.
678 M->getAliasList().push_back(GA);
679 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000680
Chris Lattnerdf986172009-01-02 07:01:27 +0000681 return false;
682}
683
684/// ParseGlobal
685/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
686/// OptionalAddrSpace GlobalType Type Const
687/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
688/// OptionalAddrSpace GlobalType Type Const
689///
690/// Everything through visibility has been parsed already.
691///
692bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
693 unsigned Linkage, bool HasLinkage,
694 unsigned Visibility) {
695 unsigned AddrSpace;
696 bool ThreadLocal, IsConstant;
697 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000698
Owen Anderson1d0be152009-08-13 21:58:54 +0000699 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000700 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
701 ParseOptionalAddrSpace(AddrSpace) ||
702 ParseGlobalType(IsConstant) ||
703 ParseType(Ty, TyLoc))
704 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000705
Chris Lattnerdf986172009-01-02 07:01:27 +0000706 // If the linkage is specified and is external, then no initializer is
707 // present.
708 Constant *Init = 0;
709 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000710 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000711 Linkage != GlobalValue::ExternalLinkage)) {
712 if (ParseGlobalValue(Ty, Init))
713 return true;
714 }
715
Duncan Sands1df98592010-02-16 11:11:14 +0000716 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000717 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000718
Chris Lattnerdf986172009-01-02 07:01:27 +0000719 GlobalVariable *GV = 0;
720
721 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000722 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000723 if (GlobalValue *GVal = M->getNamedValue(Name)) {
724 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
725 return Error(NameLoc, "redefinition of global '@" + Name + "'");
726 GV = cast<GlobalVariable>(GVal);
727 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000728 } else {
729 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
730 I = ForwardRefValIDs.find(NumberedVals.size());
731 if (I != ForwardRefValIDs.end()) {
732 GV = cast<GlobalVariable>(I->second.first);
733 ForwardRefValIDs.erase(I);
734 }
735 }
736
737 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000738 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000739 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000740 } else {
741 if (GV->getType()->getElementType() != Ty)
742 return Error(TyLoc,
743 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000744
Chris Lattnerdf986172009-01-02 07:01:27 +0000745 // Move the forward-reference to the correct spot in the module.
746 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
747 }
748
749 if (Name.empty())
750 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000751
Chris Lattnerdf986172009-01-02 07:01:27 +0000752 // Set the parsed properties on the global.
753 if (Init)
754 GV->setInitializer(Init);
755 GV->setConstant(IsConstant);
756 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
757 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
758 GV->setThreadLocal(ThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000759
Chris Lattnerdf986172009-01-02 07:01:27 +0000760 // Parse attributes on the global.
761 while (Lex.getKind() == lltok::comma) {
762 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000763
Chris Lattnerdf986172009-01-02 07:01:27 +0000764 if (Lex.getKind() == lltok::kw_section) {
765 Lex.Lex();
766 GV->setSection(Lex.getStrVal());
767 if (ParseToken(lltok::StringConstant, "expected global section string"))
768 return true;
769 } else if (Lex.getKind() == lltok::kw_align) {
770 unsigned Alignment;
771 if (ParseOptionalAlignment(Alignment)) return true;
772 GV->setAlignment(Alignment);
773 } else {
774 TokError("unknown global variable property!");
775 }
776 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000777
Chris Lattnerdf986172009-01-02 07:01:27 +0000778 return false;
779}
780
781
782//===----------------------------------------------------------------------===//
783// GlobalValue Reference/Resolution Routines.
784//===----------------------------------------------------------------------===//
785
786/// GetGlobalVal - Get a value with the specified name or ID, creating a
787/// forward reference record if needed. This can return null if the value
788/// exists but does not have the right type.
789GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
790 LocTy Loc) {
791 const PointerType *PTy = dyn_cast<PointerType>(Ty);
792 if (PTy == 0) {
793 Error(Loc, "global variable reference must have pointer type");
794 return 0;
795 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000796
Chris Lattnerdf986172009-01-02 07:01:27 +0000797 // Look this name up in the normal function symbol table.
798 GlobalValue *Val =
799 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000800
Chris Lattnerdf986172009-01-02 07:01:27 +0000801 // If this is a forward reference for the value, see if we already created a
802 // forward ref record.
803 if (Val == 0) {
804 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
805 I = ForwardRefVals.find(Name);
806 if (I != ForwardRefVals.end())
807 Val = I->second.first;
808 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000809
Chris Lattnerdf986172009-01-02 07:01:27 +0000810 // If we have the value in the symbol table or fwd-ref table, return it.
811 if (Val) {
812 if (Val->getType() == Ty) return Val;
813 Error(Loc, "'@" + Name + "' defined with type '" +
814 Val->getType()->getDescription() + "'");
815 return 0;
816 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000817
Chris Lattnerdf986172009-01-02 07:01:27 +0000818 // Otherwise, create a new forward reference for this value and remember it.
819 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000820 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
821 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000822 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner1e407c32009-01-08 19:05:36 +0000823 Error(Loc, "function may not return opaque type");
824 return 0;
825 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000826
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000827 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000828 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000829 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
830 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000831 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000832
Chris Lattnerdf986172009-01-02 07:01:27 +0000833 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
834 return FwdVal;
835}
836
837GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
838 const PointerType *PTy = dyn_cast<PointerType>(Ty);
839 if (PTy == 0) {
840 Error(Loc, "global variable reference must have pointer type");
841 return 0;
842 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000843
Chris Lattnerdf986172009-01-02 07:01:27 +0000844 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000845
Chris Lattnerdf986172009-01-02 07:01:27 +0000846 // If this is a forward reference for the value, see if we already created a
847 // forward ref record.
848 if (Val == 0) {
849 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
850 I = ForwardRefValIDs.find(ID);
851 if (I != ForwardRefValIDs.end())
852 Val = I->second.first;
853 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000854
Chris Lattnerdf986172009-01-02 07:01:27 +0000855 // If we have the value in the symbol table or fwd-ref table, return it.
856 if (Val) {
857 if (Val->getType() == Ty) return Val;
858 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
859 Val->getType()->getDescription() + "'");
860 return 0;
861 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000862
Chris Lattnerdf986172009-01-02 07:01:27 +0000863 // Otherwise, create a new forward reference for this value and remember it.
864 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000865 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
866 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000867 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000868 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000869 return 0;
870 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000871 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000872 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000873 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
874 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000875 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000876
Chris Lattnerdf986172009-01-02 07:01:27 +0000877 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
878 return FwdVal;
879}
880
881
882//===----------------------------------------------------------------------===//
883// Helper Routines.
884//===----------------------------------------------------------------------===//
885
886/// ParseToken - If the current token has the specified kind, eat it and return
887/// success. Otherwise, emit the specified error and return failure.
888bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
889 if (Lex.getKind() != T)
890 return TokError(ErrMsg);
891 Lex.Lex();
892 return false;
893}
894
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000895/// ParseStringConstant
896/// ::= StringConstant
897bool LLParser::ParseStringConstant(std::string &Result) {
898 if (Lex.getKind() != lltok::StringConstant)
899 return TokError("expected string constant");
900 Result = Lex.getStrVal();
901 Lex.Lex();
902 return false;
903}
904
905/// ParseUInt32
906/// ::= uint32
907bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000908 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
909 return TokError("expected integer");
910 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
911 if (Val64 != unsigned(Val64))
912 return TokError("expected 32-bit integer (too large)");
913 Val = Val64;
914 Lex.Lex();
915 return false;
916}
917
918
919/// ParseOptionalAddrSpace
920/// := /*empty*/
921/// := 'addrspace' '(' uint32 ')'
922bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
923 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000924 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000925 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000926 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000927 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000928 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000929}
Chris Lattnerdf986172009-01-02 07:01:27 +0000930
931/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
932/// indicates what kind of attribute list this is: 0: function arg, 1: result,
933/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000934/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000935bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
936 Attrs = Attribute::None;
937 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000938
Chris Lattnerdf986172009-01-02 07:01:27 +0000939 while (1) {
940 switch (Lex.getKind()) {
941 case lltok::kw_sext:
942 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000943 // Treat these as signext/zeroext if they occur in the argument list after
944 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
945 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
946 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000947 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000948 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000949 if (Lex.getKind() == lltok::kw_sext)
950 Attrs |= Attribute::SExt;
951 else
952 Attrs |= Attribute::ZExt;
953 break;
954 }
955 // FALL THROUGH.
956 default: // End of attributes.
957 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
958 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000959
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000960 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000961 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000962
Chris Lattnerdf986172009-01-02 07:01:27 +0000963 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000964 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
965 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
966 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
967 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
968 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
969 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
970 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
971 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000972
Devang Patel578efa92009-06-05 21:57:13 +0000973 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
974 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
975 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
976 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
977 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000978 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000979 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
980 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
981 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
982 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
983 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
984 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000985 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000986
Charles Davis1e063d12010-02-12 00:31:15 +0000987 case lltok::kw_alignstack: {
988 unsigned Alignment;
989 if (ParseOptionalStackAlignment(Alignment))
990 return true;
991 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
992 continue;
993 }
994
Chris Lattnerdf986172009-01-02 07:01:27 +0000995 case lltok::kw_align: {
996 unsigned Alignment;
997 if (ParseOptionalAlignment(Alignment))
998 return true;
999 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
1000 continue;
1001 }
Charles Davis1e063d12010-02-12 00:31:15 +00001002
Chris Lattnerdf986172009-01-02 07:01:27 +00001003 }
1004 Lex.Lex();
1005 }
1006}
1007
1008/// ParseOptionalLinkage
1009/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001010/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001011/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +00001012/// ::= 'linker_private_weak'
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 Wendling3d10a5a2009-07-20 01:03:30 +00001034 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1035 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1036 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1037 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1038 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001039 case lltok::kw_available_externally:
1040 Res = GlobalValue::AvailableExternallyLinkage;
1041 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001042 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1043 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1044 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1045 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1046 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1047 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001048 }
1049 Lex.Lex();
1050 HasLinkage = true;
1051 return false;
1052}
1053
1054/// ParseOptionalVisibility
1055/// ::= /*empty*/
1056/// ::= 'default'
1057/// ::= 'hidden'
1058/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001059///
Chris Lattnerdf986172009-01-02 07:01:27 +00001060bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1061 switch (Lex.getKind()) {
1062 default: Res = GlobalValue::DefaultVisibility; return false;
1063 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1064 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1065 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1066 }
1067 Lex.Lex();
1068 return false;
1069}
1070
1071/// ParseOptionalCallingConv
1072/// ::= /*empty*/
1073/// ::= 'ccc'
1074/// ::= 'fastcc'
1075/// ::= 'coldcc'
1076/// ::= 'x86_stdcallcc'
1077/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001078/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001079/// ::= 'arm_apcscc'
1080/// ::= 'arm_aapcscc'
1081/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001082/// ::= 'msp430_intrcc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001083/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001084///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001085bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001086 switch (Lex.getKind()) {
1087 default: CC = CallingConv::C; return false;
1088 case lltok::kw_ccc: CC = CallingConv::C; break;
1089 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1090 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1091 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1092 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001093 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001094 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1095 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1096 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001097 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001098 case lltok::kw_cc: {
1099 unsigned ArbitraryCC;
1100 Lex.Lex();
1101 if (ParseUInt32(ArbitraryCC)) {
1102 return true;
1103 } else
1104 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1105 return false;
1106 }
1107 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001108 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001109
Chris Lattnerdf986172009-01-02 07:01:27 +00001110 Lex.Lex();
1111 return false;
1112}
1113
Chris Lattnerb8c46862009-12-30 05:31:19 +00001114/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001115/// ::= !dbg !42 (',' !dbg !57)*
Chris Lattnerfe805242010-04-01 04:51:13 +00001116bool LLParser::ParseInstructionMetadata(Instruction *Inst) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001117 do {
1118 if (Lex.getKind() != lltok::MetadataVar)
1119 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001120
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001121 std::string Name = Lex.getStrVal();
1122 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001123
Chris Lattner442ffa12009-12-29 21:53:55 +00001124 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001125 unsigned NodeID;
1126 SMLoc Loc = Lex.getLoc();
Chris Lattnere434d272009-12-30 04:56:59 +00001127 if (ParseToken(lltok::exclaim, "expected '!' here") ||
Chris Lattner449c3102010-04-01 05:14:45 +00001128 ParseMDNodeID(Node, NodeID))
Chris Lattnere434d272009-12-30 04:56:59 +00001129 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001130
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001131 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner449c3102010-04-01 05:14:45 +00001132 if (Node) {
1133 // If we got the node, add it to the instruction.
1134 Inst->setMetadata(MDK, Node);
1135 } else {
1136 MDRef R = { Loc, MDK, NodeID };
1137 // Otherwise, remember that this should be resolved later.
1138 ForwardRefInstMetadata[Inst].push_back(R);
1139 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001140
1141 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001142 } while (EatIfPresent(lltok::comma));
1143 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001144}
1145
Chris Lattnerdf986172009-01-02 07:01:27 +00001146/// ParseOptionalAlignment
1147/// ::= /* empty */
1148/// ::= 'align' 4
1149bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1150 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001151 if (!EatIfPresent(lltok::kw_align))
1152 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001153 LocTy AlignLoc = Lex.getLoc();
1154 if (ParseUInt32(Alignment)) return true;
1155 if (!isPowerOf2_32(Alignment))
1156 return Error(AlignLoc, "alignment is not a power of two");
1157 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001158}
1159
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001160/// ParseOptionalCommaAlign
1161/// ::=
1162/// ::= ',' align 4
1163///
1164/// This returns with AteExtraComma set to true if it ate an excess comma at the
1165/// end.
1166bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1167 bool &AteExtraComma) {
1168 AteExtraComma = false;
1169 while (EatIfPresent(lltok::comma)) {
1170 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001171 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001172 AteExtraComma = true;
1173 return false;
1174 }
1175
Chris Lattner093eed12010-04-23 00:50:50 +00001176 if (Lex.getKind() != lltok::kw_align)
1177 return Error(Lex.getLoc(), "expected metadata or 'align'");
1178
1179 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001180 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001181
Devang Patelf633a062009-09-17 23:04:48 +00001182 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001183}
1184
Charles Davis1e063d12010-02-12 00:31:15 +00001185/// ParseOptionalStackAlignment
1186/// ::= /* empty */
1187/// ::= 'alignstack' '(' 4 ')'
1188bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1189 Alignment = 0;
1190 if (!EatIfPresent(lltok::kw_alignstack))
1191 return false;
1192 LocTy ParenLoc = Lex.getLoc();
1193 if (!EatIfPresent(lltok::lparen))
1194 return Error(ParenLoc, "expected '('");
1195 LocTy AlignLoc = Lex.getLoc();
1196 if (ParseUInt32(Alignment)) return true;
1197 ParenLoc = Lex.getLoc();
1198 if (!EatIfPresent(lltok::rparen))
1199 return Error(ParenLoc, "expected ')'");
1200 if (!isPowerOf2_32(Alignment))
1201 return Error(AlignLoc, "stack alignment is not a power of two");
1202 return false;
1203}
Devang Patelf633a062009-09-17 23:04:48 +00001204
Chris Lattner628c13a2009-12-30 05:14:00 +00001205/// ParseIndexList - This parses the index list for an insert/extractvalue
1206/// instruction. This sets AteExtraComma in the case where we eat an extra
1207/// comma at the end of the line and find that it is followed by metadata.
1208/// Clients that don't allow metadata can call the version of this function that
1209/// only takes one argument.
1210///
Chris Lattnerdf986172009-01-02 07:01:27 +00001211/// ParseIndexList
1212/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001213///
1214bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1215 bool &AteExtraComma) {
1216 AteExtraComma = false;
1217
Chris Lattnerdf986172009-01-02 07:01:27 +00001218 if (Lex.getKind() != lltok::comma)
1219 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001220
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001221 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001222 if (Lex.getKind() == lltok::MetadataVar) {
1223 AteExtraComma = true;
1224 return false;
1225 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001226 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001227 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001228 Indices.push_back(Idx);
1229 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001230
Chris Lattnerdf986172009-01-02 07:01:27 +00001231 return false;
1232}
1233
1234//===----------------------------------------------------------------------===//
1235// Type Parsing.
1236//===----------------------------------------------------------------------===//
1237
1238/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001239bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1240 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001241 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001242
Chris Lattnerdf986172009-01-02 07:01:27 +00001243 // Verify no unresolved uprefs.
1244 if (!UpRefs.empty())
1245 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001246
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001247 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001248 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001249
Chris Lattnerdf986172009-01-02 07:01:27 +00001250 return false;
1251}
1252
1253/// HandleUpRefs - Every time we finish a new layer of types, this function is
1254/// called. It loops through the UpRefs vector, which is a list of the
1255/// currently active types. For each type, if the up-reference is contained in
1256/// the newly completed type, we decrement the level count. When the level
1257/// count reaches zero, the up-referenced type is the type that is passed in:
1258/// thus we can complete the cycle.
1259///
1260PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1261 // If Ty isn't abstract, or if there are no up-references in it, then there is
1262 // nothing to resolve here.
1263 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001264
Chris Lattnerdf986172009-01-02 07:01:27 +00001265 PATypeHolder Ty(ty);
1266#if 0
David Greene0e28d762009-12-23 23:38:28 +00001267 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001268 << "' newly formed. Resolving upreferences.\n"
1269 << UpRefs.size() << " upreferences active!\n";
1270#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001271
Chris Lattnerdf986172009-01-02 07:01:27 +00001272 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1273 // to zero), we resolve them all together before we resolve them to Ty. At
1274 // the end of the loop, if there is anything to resolve to Ty, it will be in
1275 // this variable.
1276 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001277
Chris Lattnerdf986172009-01-02 07:01:27 +00001278 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1279 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1280 bool ContainsType =
1281 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1282 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001283
Chris Lattnerdf986172009-01-02 07:01:27 +00001284#if 0
David Greene0e28d762009-12-23 23:38:28 +00001285 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001286 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1287 << (ContainsType ? "true" : "false")
1288 << " level=" << UpRefs[i].NestingLevel << "\n";
1289#endif
1290 if (!ContainsType)
1291 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001292
Chris Lattnerdf986172009-01-02 07:01:27 +00001293 // Decrement level of upreference
1294 unsigned Level = --UpRefs[i].NestingLevel;
1295 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001296
Chris Lattnerdf986172009-01-02 07:01:27 +00001297 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1298 if (Level != 0)
1299 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001300
Chris Lattnerdf986172009-01-02 07:01:27 +00001301#if 0
David Greene0e28d762009-12-23 23:38:28 +00001302 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001303#endif
1304 if (!TypeToResolve)
1305 TypeToResolve = UpRefs[i].UpRefTy;
1306 else
1307 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1308 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1309 --i; // Do not skip the next element.
1310 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001311
Chris Lattnerdf986172009-01-02 07:01:27 +00001312 if (TypeToResolve)
1313 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001314
Chris Lattnerdf986172009-01-02 07:01:27 +00001315 return Ty;
1316}
1317
1318
1319/// ParseTypeRec - The recursive function used to process the internal
1320/// implementation details of types.
1321bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1322 switch (Lex.getKind()) {
1323 default:
1324 return TokError("expected type");
1325 case lltok::Type:
1326 // TypeRec ::= 'float' | 'void' (etc)
1327 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001328 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001329 break;
1330 case lltok::kw_opaque:
1331 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001332 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001333 Lex.Lex();
1334 break;
1335 case lltok::lbrace:
1336 // TypeRec ::= '{' ... '}'
1337 if (ParseStructType(Result, false))
1338 return true;
1339 break;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00001340 case lltok::kw_union:
1341 // TypeRec ::= 'union' '{' ... '}'
1342 if (ParseUnionType(Result))
1343 return true;
1344 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001345 case lltok::lsquare:
1346 // TypeRec ::= '[' ... ']'
1347 Lex.Lex(); // eat the lsquare.
1348 if (ParseArrayVectorType(Result, false))
1349 return true;
1350 break;
1351 case lltok::less: // Either vector or packed struct.
1352 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001353 Lex.Lex();
1354 if (Lex.getKind() == lltok::lbrace) {
1355 if (ParseStructType(Result, true) ||
1356 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001357 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001358 } else if (ParseArrayVectorType(Result, true))
1359 return true;
1360 break;
1361 case lltok::LocalVar:
1362 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1363 // TypeRec ::= %foo
1364 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1365 Result = T;
1366 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001367 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001368 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1369 std::make_pair(Result,
1370 Lex.getLoc())));
1371 M->addTypeName(Lex.getStrVal(), Result.get());
1372 }
1373 Lex.Lex();
1374 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001375
Chris Lattnerdf986172009-01-02 07:01:27 +00001376 case lltok::LocalVarID:
1377 // TypeRec ::= %4
1378 if (Lex.getUIntVal() < NumberedTypes.size())
1379 Result = NumberedTypes[Lex.getUIntVal()];
1380 else {
1381 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1382 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1383 if (I != ForwardRefTypeIDs.end())
1384 Result = I->second.first;
1385 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001386 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001387 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1388 std::make_pair(Result,
1389 Lex.getLoc())));
1390 }
1391 }
1392 Lex.Lex();
1393 break;
1394 case lltok::backslash: {
1395 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001396 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001397 unsigned Val;
1398 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001399 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001400 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1401 Result = OT;
1402 break;
1403 }
1404 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001405
1406 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001407 while (1) {
1408 switch (Lex.getKind()) {
1409 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001410 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001411
1412 // TypeRec ::= TypeRec '*'
1413 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001414 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001415 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001416 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001417 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001418 if (!PointerType::isValidElementType(Result.get()))
1419 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001420 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001421 Lex.Lex();
1422 break;
1423
1424 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1425 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001426 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001427 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001428 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001429 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001430 if (!PointerType::isValidElementType(Result.get()))
1431 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001432 unsigned AddrSpace;
1433 if (ParseOptionalAddrSpace(AddrSpace) ||
1434 ParseToken(lltok::star, "expected '*' in address space"))
1435 return true;
1436
Owen Andersondebcb012009-07-29 22:17:13 +00001437 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001438 break;
1439 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001440
Chris Lattnerdf986172009-01-02 07:01:27 +00001441 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1442 case lltok::lparen:
1443 if (ParseFunctionType(Result))
1444 return true;
1445 break;
1446 }
1447 }
1448}
1449
1450/// ParseParameterList
1451/// ::= '(' ')'
1452/// ::= '(' Arg (',' Arg)* ')'
1453/// Arg
1454/// ::= Type OptionalAttributes Value OptionalAttributes
1455bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1456 PerFunctionState &PFS) {
1457 if (ParseToken(lltok::lparen, "expected '(' in call"))
1458 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001459
Chris Lattnerdf986172009-01-02 07:01:27 +00001460 while (Lex.getKind() != lltok::rparen) {
1461 // If this isn't the first argument, we need a comma.
1462 if (!ArgList.empty() &&
1463 ParseToken(lltok::comma, "expected ',' in argument list"))
1464 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001465
Chris Lattnerdf986172009-01-02 07:01:27 +00001466 // Parse the argument.
1467 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001468 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001469 unsigned ArgAttrs1 = Attribute::None;
1470 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001471 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001472 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001473 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001474
Chris Lattner287881d2009-12-30 02:11:14 +00001475 // Otherwise, handle normal operands.
1476 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1477 ParseValue(ArgTy, V, PFS) ||
1478 // FIXME: Should not allow attributes after the argument, remove this
1479 // in LLVM 3.0.
1480 ParseOptionalAttrs(ArgAttrs2, 3))
1481 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001482 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1483 }
1484
1485 Lex.Lex(); // Lex the ')'.
1486 return false;
1487}
1488
1489
1490
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001491/// ParseArgumentList - Parse the argument list for a function type or function
1492/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001493/// ::= '(' ArgTypeListI ')'
1494/// ArgTypeListI
1495/// ::= /*empty*/
1496/// ::= '...'
1497/// ::= ArgTypeList ',' '...'
1498/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001499///
Chris Lattnerdf986172009-01-02 07:01:27 +00001500bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001501 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001502 isVarArg = false;
1503 assert(Lex.getKind() == lltok::lparen);
1504 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001505
Chris Lattnerdf986172009-01-02 07:01:27 +00001506 if (Lex.getKind() == lltok::rparen) {
1507 // empty
1508 } else if (Lex.getKind() == lltok::dotdotdot) {
1509 isVarArg = true;
1510 Lex.Lex();
1511 } else {
1512 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001513 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001514 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001515 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001516
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001517 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1518 // types (such as a function returning a pointer to itself). If parsing a
1519 // function prototype, we require fully resolved types.
1520 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001521 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001522
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001523 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001524 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001525
Chris Lattnerdf986172009-01-02 07:01:27 +00001526 if (Lex.getKind() == lltok::LocalVar ||
1527 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1528 Name = Lex.getStrVal();
1529 Lex.Lex();
1530 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001531
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001532 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001533 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001534
Chris Lattnerdf986172009-01-02 07:01:27 +00001535 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001536
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001537 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001538 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001539 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001540 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001541 break;
1542 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001543
Chris Lattnerdf986172009-01-02 07:01:27 +00001544 // Otherwise must be an argument type.
1545 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001546 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001547 ParseOptionalAttrs(Attrs, 0)) return true;
1548
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001549 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001550 return Error(TypeLoc, "argument can not have void type");
1551
Chris Lattnerdf986172009-01-02 07:01:27 +00001552 if (Lex.getKind() == lltok::LocalVar ||
1553 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1554 Name = Lex.getStrVal();
1555 Lex.Lex();
1556 } else {
1557 Name = "";
1558 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001559
Duncan Sands47c51882010-02-16 14:50:09 +00001560 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001561 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001562
Chris Lattnerdf986172009-01-02 07:01:27 +00001563 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1564 }
1565 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001566
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001567 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001568}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001569
Chris Lattnerdf986172009-01-02 07:01:27 +00001570/// ParseFunctionType
1571/// ::= Type ArgumentList OptionalAttrs
1572bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1573 assert(Lex.getKind() == lltok::lparen);
1574
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001575 if (!FunctionType::isValidReturnType(Result))
1576 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001577
Chris Lattnerdf986172009-01-02 07:01:27 +00001578 std::vector<ArgInfo> ArgList;
1579 bool isVarArg;
1580 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001581 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001582 // FIXME: Allow, but ignore attributes on function types!
1583 // FIXME: Remove in LLVM 3.0
1584 ParseOptionalAttrs(Attrs, 2))
1585 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001586
Chris Lattnerdf986172009-01-02 07:01:27 +00001587 // Reject names on the arguments lists.
1588 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1589 if (!ArgList[i].Name.empty())
1590 return Error(ArgList[i].Loc, "argument name invalid in function type");
1591 if (!ArgList[i].Attrs != 0) {
1592 // Allow but ignore attributes on function types; this permits
1593 // auto-upgrade.
1594 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1595 }
1596 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001597
Chris Lattnerdf986172009-01-02 07:01:27 +00001598 std::vector<const Type*> ArgListTy;
1599 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1600 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001601
Owen Andersondebcb012009-07-29 22:17:13 +00001602 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001603 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001604 return false;
1605}
1606
1607/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1608/// TypeRec
1609/// ::= '{' '}'
1610/// ::= '{' TypeRec (',' TypeRec)* '}'
1611/// ::= '<' '{' '}' '>'
1612/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1613bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1614 assert(Lex.getKind() == lltok::lbrace);
1615 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001616
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001617 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001618 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001619 return false;
1620 }
1621
1622 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001623 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001624 if (ParseTypeRec(Result)) return true;
1625 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001626
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001627 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001628 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001629 if (!StructType::isValidElementType(Result))
1630 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001631
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001632 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001633 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001634 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001635
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001636 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001637 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001638 if (!StructType::isValidElementType(Result))
1639 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001640
Chris Lattnerdf986172009-01-02 07:01:27 +00001641 ParamsList.push_back(Result);
1642 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001643
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001644 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1645 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001646
Chris Lattnerdf986172009-01-02 07:01:27 +00001647 std::vector<const Type*> ParamsListTy;
1648 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1649 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001650 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001651 return false;
1652}
1653
Chris Lattnerfdfeb692010-02-12 20:49:41 +00001654/// ParseUnionType
1655/// TypeRec
1656/// ::= 'union' '{' TypeRec (',' TypeRec)* '}'
1657bool LLParser::ParseUnionType(PATypeHolder &Result) {
1658 assert(Lex.getKind() == lltok::kw_union);
1659 Lex.Lex(); // Consume the 'union'
1660
1661 if (ParseToken(lltok::lbrace, "'{' expected after 'union'")) return true;
1662
1663 SmallVector<PATypeHolder, 8> ParamsList;
1664 do {
1665 LocTy EltTyLoc = Lex.getLoc();
1666 if (ParseTypeRec(Result)) return true;
1667 ParamsList.push_back(Result);
1668
1669 if (Result->isVoidTy())
1670 return Error(EltTyLoc, "union element can not have void type");
1671 if (!UnionType::isValidElementType(Result))
1672 return Error(EltTyLoc, "invalid element type for union");
1673
1674 } while (EatIfPresent(lltok::comma)) ;
1675
1676 if (ParseToken(lltok::rbrace, "expected '}' at end of union"))
1677 return true;
1678
1679 SmallVector<const Type*, 8> ParamsListTy;
1680 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1681 ParamsListTy.push_back(ParamsList[i].get());
1682 Result = HandleUpRefs(UnionType::get(&ParamsListTy[0], ParamsListTy.size()));
1683 return false;
1684}
1685
Chris Lattnerdf986172009-01-02 07:01:27 +00001686/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1687/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001688/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001689/// ::= '[' APSINTVAL 'x' Types ']'
1690/// ::= '<' APSINTVAL 'x' Types '>'
1691bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1692 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1693 Lex.getAPSIntVal().getBitWidth() > 64)
1694 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001695
Chris Lattnerdf986172009-01-02 07:01:27 +00001696 LocTy SizeLoc = Lex.getLoc();
1697 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001698 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001699
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001700 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1701 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001702
1703 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001704 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001705 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001706
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001707 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001708 return Error(TypeLoc, "array and vector element type cannot be void");
1709
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001710 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1711 "expected end of sequential type"))
1712 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001713
Chris Lattnerdf986172009-01-02 07:01:27 +00001714 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001715 if (Size == 0)
1716 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001717 if ((unsigned)Size != Size)
1718 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001719 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001720 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001721 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001722 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001723 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001724 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001725 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001726 }
1727 return false;
1728}
1729
1730//===----------------------------------------------------------------------===//
1731// Function Semantic Analysis.
1732//===----------------------------------------------------------------------===//
1733
Chris Lattner09d9ef42009-10-28 03:39:23 +00001734LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1735 int functionNumber)
1736 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001737
1738 // Insert unnamed arguments into the NumberedVals list.
1739 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1740 AI != E; ++AI)
1741 if (!AI->hasName())
1742 NumberedVals.push_back(AI);
1743}
1744
1745LLParser::PerFunctionState::~PerFunctionState() {
1746 // If there were any forward referenced non-basicblock values, delete them.
1747 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1748 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1749 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001750 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001751 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001752 delete I->second.first;
1753 I->second.first = 0;
1754 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001755
Chris Lattnerdf986172009-01-02 07:01:27 +00001756 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1757 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1758 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001759 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001760 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001761 delete I->second.first;
1762 I->second.first = 0;
1763 }
1764}
1765
Chris Lattner09d9ef42009-10-28 03:39:23 +00001766bool LLParser::PerFunctionState::FinishFunction() {
1767 // Check to see if someone took the address of labels in this block.
1768 if (!P.ForwardRefBlockAddresses.empty()) {
1769 ValID FunctionID;
1770 if (!F.getName().empty()) {
1771 FunctionID.Kind = ValID::t_GlobalName;
1772 FunctionID.StrVal = F.getName();
1773 } else {
1774 FunctionID.Kind = ValID::t_GlobalID;
1775 FunctionID.UIntVal = FunctionNumber;
1776 }
1777
1778 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1779 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1780 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1781 // Resolve all these references.
1782 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1783 return true;
1784
1785 P.ForwardRefBlockAddresses.erase(FRBAI);
1786 }
1787 }
1788
Chris Lattnerdf986172009-01-02 07:01:27 +00001789 if (!ForwardRefVals.empty())
1790 return P.Error(ForwardRefVals.begin()->second.second,
1791 "use of undefined value '%" + ForwardRefVals.begin()->first +
1792 "'");
1793 if (!ForwardRefValIDs.empty())
1794 return P.Error(ForwardRefValIDs.begin()->second.second,
1795 "use of undefined value '%" +
1796 utostr(ForwardRefValIDs.begin()->first) + "'");
1797 return false;
1798}
1799
1800
1801/// GetVal - Get a value with the specified name or ID, creating a
1802/// forward reference record if needed. This can return null if the value
1803/// exists but does not have the right type.
1804Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1805 const Type *Ty, LocTy Loc) {
1806 // Look this name up in the normal function symbol table.
1807 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001808
Chris Lattnerdf986172009-01-02 07:01:27 +00001809 // If this is a forward reference for the value, see if we already created a
1810 // forward ref record.
1811 if (Val == 0) {
1812 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1813 I = ForwardRefVals.find(Name);
1814 if (I != ForwardRefVals.end())
1815 Val = I->second.first;
1816 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001817
Chris Lattnerdf986172009-01-02 07:01:27 +00001818 // If we have the value in the symbol table or fwd-ref table, return it.
1819 if (Val) {
1820 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001821 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001822 P.Error(Loc, "'%" + Name + "' is not a basic block");
1823 else
1824 P.Error(Loc, "'%" + Name + "' defined with type '" +
1825 Val->getType()->getDescription() + "'");
1826 return 0;
1827 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001828
Chris Lattnerdf986172009-01-02 07:01:27 +00001829 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001830 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001831 P.Error(Loc, "invalid use of a non-first-class type");
1832 return 0;
1833 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001834
Chris Lattnerdf986172009-01-02 07:01:27 +00001835 // Otherwise, create a new forward reference for this value and remember it.
1836 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001837 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001838 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001839 else
1840 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001841
Chris Lattnerdf986172009-01-02 07:01:27 +00001842 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1843 return FwdVal;
1844}
1845
1846Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1847 LocTy Loc) {
1848 // Look this name up in the normal function symbol table.
1849 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001850
Chris Lattnerdf986172009-01-02 07:01:27 +00001851 // If this is a forward reference for the value, see if we already created a
1852 // forward ref record.
1853 if (Val == 0) {
1854 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1855 I = ForwardRefValIDs.find(ID);
1856 if (I != ForwardRefValIDs.end())
1857 Val = I->second.first;
1858 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001859
Chris Lattnerdf986172009-01-02 07:01:27 +00001860 // If we have the value in the symbol table or fwd-ref table, return it.
1861 if (Val) {
1862 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001863 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001864 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1865 else
1866 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1867 Val->getType()->getDescription() + "'");
1868 return 0;
1869 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001870
Duncan Sands47c51882010-02-16 14:50:09 +00001871 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001872 P.Error(Loc, "invalid use of a non-first-class type");
1873 return 0;
1874 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001875
Chris Lattnerdf986172009-01-02 07:01:27 +00001876 // Otherwise, create a new forward reference for this value and remember it.
1877 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001878 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001879 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001880 else
1881 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001882
Chris Lattnerdf986172009-01-02 07:01:27 +00001883 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1884 return FwdVal;
1885}
1886
1887/// SetInstName - After an instruction is parsed and inserted into its
1888/// basic block, this installs its name.
1889bool LLParser::PerFunctionState::SetInstName(int NameID,
1890 const std::string &NameStr,
1891 LocTy NameLoc, Instruction *Inst) {
1892 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001893 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001894 if (NameID != -1 || !NameStr.empty())
1895 return P.Error(NameLoc, "instructions returning void cannot have a name");
1896 return false;
1897 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001898
Chris Lattnerdf986172009-01-02 07:01:27 +00001899 // If this was a numbered instruction, verify that the instruction is the
1900 // expected value and resolve any forward references.
1901 if (NameStr.empty()) {
1902 // If neither a name nor an ID was specified, just use the next ID.
1903 if (NameID == -1)
1904 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001905
Chris Lattnerdf986172009-01-02 07:01:27 +00001906 if (unsigned(NameID) != NumberedVals.size())
1907 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1908 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001909
Chris Lattnerdf986172009-01-02 07:01:27 +00001910 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1911 ForwardRefValIDs.find(NameID);
1912 if (FI != ForwardRefValIDs.end()) {
1913 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001914 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001915 FI->second.first->getType()->getDescription() + "'");
1916 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001917 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001918 ForwardRefValIDs.erase(FI);
1919 }
1920
1921 NumberedVals.push_back(Inst);
1922 return false;
1923 }
1924
1925 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1926 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1927 FI = ForwardRefVals.find(NameStr);
1928 if (FI != ForwardRefVals.end()) {
1929 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001930 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001931 FI->second.first->getType()->getDescription() + "'");
1932 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001933 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001934 ForwardRefVals.erase(FI);
1935 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001936
Chris Lattnerdf986172009-01-02 07:01:27 +00001937 // Set the name on the instruction.
1938 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001939
Chris Lattnerdf986172009-01-02 07:01:27 +00001940 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001941 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001942 NameStr + "'");
1943 return false;
1944}
1945
1946/// GetBB - Get a basic block with the specified name or ID, creating a
1947/// forward reference record if needed.
1948BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1949 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001950 return cast_or_null<BasicBlock>(GetVal(Name,
1951 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001952}
1953
1954BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001955 return cast_or_null<BasicBlock>(GetVal(ID,
1956 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001957}
1958
1959/// DefineBB - Define the specified basic block, which is either named or
1960/// unnamed. If there is an error, this returns null otherwise it returns
1961/// the block being defined.
1962BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1963 LocTy Loc) {
1964 BasicBlock *BB;
1965 if (Name.empty())
1966 BB = GetBB(NumberedVals.size(), Loc);
1967 else
1968 BB = GetBB(Name, Loc);
1969 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001970
Chris Lattnerdf986172009-01-02 07:01:27 +00001971 // Move the block to the end of the function. Forward ref'd blocks are
1972 // inserted wherever they happen to be referenced.
1973 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001974
Chris Lattnerdf986172009-01-02 07:01:27 +00001975 // Remove the block from forward ref sets.
1976 if (Name.empty()) {
1977 ForwardRefValIDs.erase(NumberedVals.size());
1978 NumberedVals.push_back(BB);
1979 } else {
1980 // BB forward references are already in the function symbol table.
1981 ForwardRefVals.erase(Name);
1982 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001983
Chris Lattnerdf986172009-01-02 07:01:27 +00001984 return BB;
1985}
1986
1987//===----------------------------------------------------------------------===//
1988// Constants.
1989//===----------------------------------------------------------------------===//
1990
1991/// ParseValID - Parse an abstract value that doesn't necessarily have a
1992/// type implied. For example, if we parse "4" we don't know what integer type
1993/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001994/// sanity. PFS is used to convert function-local operands of metadata (since
1995/// metadata operands are not just parsed here but also converted to values).
1996/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001997bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001998 ID.Loc = Lex.getLoc();
1999 switch (Lex.getKind()) {
2000 default: return TokError("expected value token");
2001 case lltok::GlobalID: // @42
2002 ID.UIntVal = Lex.getUIntVal();
2003 ID.Kind = ValID::t_GlobalID;
2004 break;
2005 case lltok::GlobalVar: // @foo
2006 ID.StrVal = Lex.getStrVal();
2007 ID.Kind = ValID::t_GlobalName;
2008 break;
2009 case lltok::LocalVarID: // %42
2010 ID.UIntVal = Lex.getUIntVal();
2011 ID.Kind = ValID::t_LocalID;
2012 break;
2013 case lltok::LocalVar: // %foo
2014 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2015 ID.StrVal = Lex.getStrVal();
2016 ID.Kind = ValID::t_LocalName;
2017 break;
Dan Gohman83448032010-07-14 18:26:50 +00002018 case lltok::exclaim: // !42, !{...}, or !"foo"
2019 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002020 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002021 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002022 ID.Kind = ValID::t_APSInt;
2023 break;
2024 case lltok::APFloat:
2025 ID.APFloatVal = Lex.getAPFloatVal();
2026 ID.Kind = ValID::t_APFloat;
2027 break;
2028 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002029 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002030 ID.Kind = ValID::t_Constant;
2031 break;
2032 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002033 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002034 ID.Kind = ValID::t_Constant;
2035 break;
2036 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2037 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2038 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002039
Chris Lattnerdf986172009-01-02 07:01:27 +00002040 case lltok::lbrace: {
2041 // ValID ::= '{' ConstVector '}'
2042 Lex.Lex();
2043 SmallVector<Constant*, 16> Elts;
2044 if (ParseGlobalValueVector(Elts) ||
2045 ParseToken(lltok::rbrace, "expected end of struct constant"))
2046 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002047
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002048 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2049 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002050 ID.Kind = ValID::t_Constant;
2051 return false;
2052 }
2053 case lltok::less: {
2054 // ValID ::= '<' ConstVector '>' --> Vector.
2055 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2056 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002057 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002058
Chris Lattnerdf986172009-01-02 07:01:27 +00002059 SmallVector<Constant*, 16> Elts;
2060 LocTy FirstEltLoc = Lex.getLoc();
2061 if (ParseGlobalValueVector(Elts) ||
2062 (isPackedStruct &&
2063 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2064 ParseToken(lltok::greater, "expected end of constant"))
2065 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002066
Chris Lattnerdf986172009-01-02 07:01:27 +00002067 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002068 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002069 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002070 ID.Kind = ValID::t_Constant;
2071 return false;
2072 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002073
Chris Lattnerdf986172009-01-02 07:01:27 +00002074 if (Elts.empty())
2075 return Error(ID.Loc, "constant vector must not be empty");
2076
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002077 if (!Elts[0]->getType()->isIntegerTy() &&
2078 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002079 return Error(FirstEltLoc,
2080 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002081
Chris Lattnerdf986172009-01-02 07:01:27 +00002082 // Verify that all the vector elements have the same type.
2083 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2084 if (Elts[i]->getType() != Elts[0]->getType())
2085 return Error(FirstEltLoc,
2086 "vector element #" + utostr(i) +
2087 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002088
Owen Andersonaf7ec972009-07-28 21:19:26 +00002089 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002090 ID.Kind = ValID::t_Constant;
2091 return false;
2092 }
2093 case lltok::lsquare: { // Array Constant
2094 Lex.Lex();
2095 SmallVector<Constant*, 16> Elts;
2096 LocTy FirstEltLoc = Lex.getLoc();
2097 if (ParseGlobalValueVector(Elts) ||
2098 ParseToken(lltok::rsquare, "expected end of array constant"))
2099 return true;
2100
2101 // Handle empty element.
2102 if (Elts.empty()) {
2103 // Use undef instead of an array because it's inconvenient to determine
2104 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002105 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002106 return false;
2107 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002108
Chris Lattnerdf986172009-01-02 07:01:27 +00002109 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002110 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002111 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002112
Owen Andersondebcb012009-07-29 22:17:13 +00002113 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002114
Chris Lattnerdf986172009-01-02 07:01:27 +00002115 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002116 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002117 if (Elts[i]->getType() != Elts[0]->getType())
2118 return Error(FirstEltLoc,
2119 "array element #" + utostr(i) +
2120 " is not of type '" +Elts[0]->getType()->getDescription());
2121 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002122
Owen Anderson1fd70962009-07-28 18:32:17 +00002123 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002124 ID.Kind = ValID::t_Constant;
2125 return false;
2126 }
2127 case lltok::kw_c: // c "foo"
2128 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002129 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002130 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2131 ID.Kind = ValID::t_Constant;
2132 return false;
2133
2134 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002135 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2136 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002137 Lex.Lex();
2138 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002139 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002140 ParseStringConstant(ID.StrVal) ||
2141 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002142 ParseToken(lltok::StringConstant, "expected constraint string"))
2143 return true;
2144 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002145 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002146 ID.Kind = ValID::t_InlineAsm;
2147 return false;
2148 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002149
Chris Lattner09d9ef42009-10-28 03:39:23 +00002150 case lltok::kw_blockaddress: {
2151 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2152 Lex.Lex();
2153
2154 ValID Fn, Label;
2155 LocTy FnLoc, LabelLoc;
2156
2157 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2158 ParseValID(Fn) ||
2159 ParseToken(lltok::comma, "expected comma in block address expression")||
2160 ParseValID(Label) ||
2161 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2162 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002163
Chris Lattner09d9ef42009-10-28 03:39:23 +00002164 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2165 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002166 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002167 return Error(Label.Loc, "expected basic block name in blockaddress");
2168
2169 // Make a global variable as a placeholder for this reference.
2170 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2171 false, GlobalValue::InternalLinkage,
2172 0, "");
2173 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2174 ID.ConstantVal = FwdRef;
2175 ID.Kind = ValID::t_Constant;
2176 return false;
2177 }
2178
Chris Lattnerdf986172009-01-02 07:01:27 +00002179 case lltok::kw_trunc:
2180 case lltok::kw_zext:
2181 case lltok::kw_sext:
2182 case lltok::kw_fptrunc:
2183 case lltok::kw_fpext:
2184 case lltok::kw_bitcast:
2185 case lltok::kw_uitofp:
2186 case lltok::kw_sitofp:
2187 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002188 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002189 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002190 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002191 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002192 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002193 Constant *SrcVal;
2194 Lex.Lex();
2195 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2196 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002197 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002198 ParseType(DestTy) ||
2199 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2200 return true;
2201 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2202 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2203 SrcVal->getType()->getDescription() + "' to '" +
2204 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002205 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002206 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002207 ID.Kind = ValID::t_Constant;
2208 return false;
2209 }
2210 case lltok::kw_extractvalue: {
2211 Lex.Lex();
2212 Constant *Val;
2213 SmallVector<unsigned, 4> Indices;
2214 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2215 ParseGlobalTypeAndValue(Val) ||
2216 ParseIndexList(Indices) ||
2217 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2218 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002219
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002220 if (!Val->getType()->isAggregateType())
2221 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002222 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2223 Indices.end()))
2224 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002225 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002226 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002227 ID.Kind = ValID::t_Constant;
2228 return false;
2229 }
2230 case lltok::kw_insertvalue: {
2231 Lex.Lex();
2232 Constant *Val0, *Val1;
2233 SmallVector<unsigned, 4> Indices;
2234 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2235 ParseGlobalTypeAndValue(Val0) ||
2236 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2237 ParseGlobalTypeAndValue(Val1) ||
2238 ParseIndexList(Indices) ||
2239 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2240 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002241 if (!Val0->getType()->isAggregateType())
2242 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002243 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2244 Indices.end()))
2245 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002246 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002247 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002248 ID.Kind = ValID::t_Constant;
2249 return false;
2250 }
2251 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002252 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002253 unsigned PredVal, Opc = Lex.getUIntVal();
2254 Constant *Val0, *Val1;
2255 Lex.Lex();
2256 if (ParseCmpPredicate(PredVal, Opc) ||
2257 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2258 ParseGlobalTypeAndValue(Val0) ||
2259 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2260 ParseGlobalTypeAndValue(Val1) ||
2261 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2262 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002263
Chris Lattnerdf986172009-01-02 07:01:27 +00002264 if (Val0->getType() != Val1->getType())
2265 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002266
Chris Lattnerdf986172009-01-02 07:01:27 +00002267 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002268
Chris Lattnerdf986172009-01-02 07:01:27 +00002269 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002270 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002271 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002272 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002273 } else {
2274 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002275 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002276 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002277 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002278 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002279 }
2280 ID.Kind = ValID::t_Constant;
2281 return false;
2282 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002283
Chris Lattnerdf986172009-01-02 07:01:27 +00002284 // Binary Operators.
2285 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002286 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002287 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002288 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002289 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002290 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002291 case lltok::kw_udiv:
2292 case lltok::kw_sdiv:
2293 case lltok::kw_fdiv:
2294 case lltok::kw_urem:
2295 case lltok::kw_srem:
2296 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002297 bool NUW = false;
2298 bool NSW = false;
2299 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002300 unsigned Opc = Lex.getUIntVal();
2301 Constant *Val0, *Val1;
2302 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002303 LocTy ModifierLoc = Lex.getLoc();
2304 if (Opc == Instruction::Add ||
2305 Opc == Instruction::Sub ||
2306 Opc == Instruction::Mul) {
2307 if (EatIfPresent(lltok::kw_nuw))
2308 NUW = true;
2309 if (EatIfPresent(lltok::kw_nsw)) {
2310 NSW = true;
2311 if (EatIfPresent(lltok::kw_nuw))
2312 NUW = true;
2313 }
2314 } else if (Opc == Instruction::SDiv) {
2315 if (EatIfPresent(lltok::kw_exact))
2316 Exact = true;
2317 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002318 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2319 ParseGlobalTypeAndValue(Val0) ||
2320 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2321 ParseGlobalTypeAndValue(Val1) ||
2322 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2323 return true;
2324 if (Val0->getType() != Val1->getType())
2325 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002326 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002327 if (NUW)
2328 return Error(ModifierLoc, "nuw only applies to integer operations");
2329 if (NSW)
2330 return Error(ModifierLoc, "nsw only applies to integer operations");
2331 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002332 // Check that the type is valid for the operator.
2333 switch (Opc) {
2334 case Instruction::Add:
2335 case Instruction::Sub:
2336 case Instruction::Mul:
2337 case Instruction::UDiv:
2338 case Instruction::SDiv:
2339 case Instruction::URem:
2340 case Instruction::SRem:
2341 if (!Val0->getType()->isIntOrIntVectorTy())
2342 return Error(ID.Loc, "constexpr requires integer operands");
2343 break;
2344 case Instruction::FAdd:
2345 case Instruction::FSub:
2346 case Instruction::FMul:
2347 case Instruction::FDiv:
2348 case Instruction::FRem:
2349 if (!Val0->getType()->isFPOrFPVectorTy())
2350 return Error(ID.Loc, "constexpr requires fp operands");
2351 break;
2352 default: llvm_unreachable("Unknown binary operator!");
2353 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002354 unsigned Flags = 0;
2355 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2356 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2357 if (Exact) Flags |= SDivOperator::IsExact;
2358 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002359 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002360 ID.Kind = ValID::t_Constant;
2361 return false;
2362 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002363
Chris Lattnerdf986172009-01-02 07:01:27 +00002364 // Logical Operations
2365 case lltok::kw_shl:
2366 case lltok::kw_lshr:
2367 case lltok::kw_ashr:
2368 case lltok::kw_and:
2369 case lltok::kw_or:
2370 case lltok::kw_xor: {
2371 unsigned Opc = Lex.getUIntVal();
2372 Constant *Val0, *Val1;
2373 Lex.Lex();
2374 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2375 ParseGlobalTypeAndValue(Val0) ||
2376 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2377 ParseGlobalTypeAndValue(Val1) ||
2378 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2379 return true;
2380 if (Val0->getType() != Val1->getType())
2381 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002382 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002383 return Error(ID.Loc,
2384 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002385 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002386 ID.Kind = ValID::t_Constant;
2387 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002388 }
2389
Chris Lattnerdf986172009-01-02 07:01:27 +00002390 case lltok::kw_getelementptr:
2391 case lltok::kw_shufflevector:
2392 case lltok::kw_insertelement:
2393 case lltok::kw_extractelement:
2394 case lltok::kw_select: {
2395 unsigned Opc = Lex.getUIntVal();
2396 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002397 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002398 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002399 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002400 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002401 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2402 ParseGlobalValueVector(Elts) ||
2403 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2404 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002405
Chris Lattnerdf986172009-01-02 07:01:27 +00002406 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002407 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002408 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002409
Chris Lattnerdf986172009-01-02 07:01:27 +00002410 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002411 (Value**)(Elts.data() + 1),
2412 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002413 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002414 ID.ConstantVal = InBounds ?
2415 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2416 Elts.data() + 1,
2417 Elts.size() - 1) :
2418 ConstantExpr::getGetElementPtr(Elts[0],
2419 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002420 } else if (Opc == Instruction::Select) {
2421 if (Elts.size() != 3)
2422 return Error(ID.Loc, "expected three operands to select");
2423 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2424 Elts[2]))
2425 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002426 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002427 } else if (Opc == Instruction::ShuffleVector) {
2428 if (Elts.size() != 3)
2429 return Error(ID.Loc, "expected three operands to shufflevector");
2430 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2431 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002432 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002433 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002434 } else if (Opc == Instruction::ExtractElement) {
2435 if (Elts.size() != 2)
2436 return Error(ID.Loc, "expected two operands to extractelement");
2437 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2438 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002439 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002440 } else {
2441 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2442 if (Elts.size() != 3)
2443 return Error(ID.Loc, "expected three operands to insertelement");
2444 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2445 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002446 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002447 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002448 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002449
Chris Lattnerdf986172009-01-02 07:01:27 +00002450 ID.Kind = ValID::t_Constant;
2451 return false;
2452 }
2453 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002454
Chris Lattnerdf986172009-01-02 07:01:27 +00002455 Lex.Lex();
2456 return false;
2457}
2458
2459/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002460bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2461 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002462 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002463 Value *V = NULL;
2464 bool Parsed = ParseValID(ID) ||
2465 ConvertValIDToValue(Ty, ID, V, NULL);
2466 if (V && !(C = dyn_cast<Constant>(V)))
2467 return Error(ID.Loc, "global values must be constants");
2468 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002469}
2470
Victor Hernandez92f238d2010-01-11 22:31:58 +00002471bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2472 PATypeHolder Type(Type::getVoidTy(Context));
2473 return ParseType(Type) ||
2474 ParseGlobalValue(Type, V);
2475}
2476
2477/// ParseGlobalValueVector
2478/// ::= /*empty*/
2479/// ::= TypeAndValue (',' TypeAndValue)*
2480bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2481 // Empty list.
2482 if (Lex.getKind() == lltok::rbrace ||
2483 Lex.getKind() == lltok::rsquare ||
2484 Lex.getKind() == lltok::greater ||
2485 Lex.getKind() == lltok::rparen)
2486 return false;
2487
2488 Constant *C;
2489 if (ParseGlobalTypeAndValue(C)) return true;
2490 Elts.push_back(C);
2491
2492 while (EatIfPresent(lltok::comma)) {
2493 if (ParseGlobalTypeAndValue(C)) return true;
2494 Elts.push_back(C);
2495 }
2496
2497 return false;
2498}
2499
Dan Gohman83448032010-07-14 18:26:50 +00002500/// ParseMetadataValue
2501/// ::= !42
2502/// ::= !{...}
2503/// ::= !"string"
2504bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2505 assert(Lex.getKind() == lltok::exclaim);
2506 Lex.Lex();
2507
2508 // MDNode:
2509 // !{ ... }
2510 if (EatIfPresent(lltok::lbrace)) {
2511 SmallVector<Value*, 16> Elts;
2512 if (ParseMDNodeVector(Elts, PFS) ||
2513 ParseToken(lltok::rbrace, "expected end of metadata node"))
2514 return true;
2515
2516 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
2517 ID.Kind = ValID::t_MDNode;
2518 return false;
2519 }
2520
2521 // Standalone metadata reference
2522 // !42
2523 if (Lex.getKind() == lltok::APSInt) {
2524 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2525 ID.Kind = ValID::t_MDNode;
2526 return false;
2527 }
2528
2529 // MDString:
2530 // ::= '!' STRINGCONSTANT
2531 if (ParseMDString(ID.MDStringVal)) return true;
2532 ID.Kind = ValID::t_MDString;
2533 return false;
2534}
2535
Victor Hernandez92f238d2010-01-11 22:31:58 +00002536
2537//===----------------------------------------------------------------------===//
2538// Function Parsing.
2539//===----------------------------------------------------------------------===//
2540
2541bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2542 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002543 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002544 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002545
Chris Lattnerdf986172009-01-02 07:01:27 +00002546 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002547 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002548 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002549 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2550 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2551 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002552 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002553 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2554 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2555 return (V == 0);
2556 case ValID::t_InlineAsm: {
2557 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2558 const FunctionType *FTy =
2559 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2560 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2561 return Error(ID.Loc, "invalid type for inline asm constraint string");
2562 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2563 return false;
2564 }
2565 case ValID::t_MDNode:
2566 if (!Ty->isMetadataTy())
2567 return Error(ID.Loc, "metadata value must have metadata type");
2568 V = ID.MDNodeVal;
2569 return false;
2570 case ValID::t_MDString:
2571 if (!Ty->isMetadataTy())
2572 return Error(ID.Loc, "metadata value must have metadata type");
2573 V = ID.MDStringVal;
2574 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002575 case ValID::t_GlobalName:
2576 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2577 return V == 0;
2578 case ValID::t_GlobalID:
2579 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2580 return V == 0;
2581 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002582 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002583 return Error(ID.Loc, "integer constant must have integer type");
2584 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002585 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002586 return false;
2587 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002588 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002589 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2590 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002591
Chris Lattnerdf986172009-01-02 07:01:27 +00002592 // The lexer has no type info, so builds all float and double FP constants
2593 // as double. Fix this here. Long double does not need this.
2594 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002595 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002596 bool Ignored;
2597 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2598 &Ignored);
2599 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002600 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002601
Chris Lattner959873d2009-01-05 18:24:23 +00002602 if (V->getType() != Ty)
2603 return Error(ID.Loc, "floating point constant does not have type '" +
2604 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002605
Chris Lattnerdf986172009-01-02 07:01:27 +00002606 return false;
2607 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002608 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002609 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002610 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002611 return false;
2612 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002613 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002614 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002615 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002616 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002617 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002618 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002619 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002620 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002621 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002622 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002623 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002624 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002625 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002626 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002627 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002628 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002629 return false;
2630 case ValID::t_Constant:
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002631 if (ID.ConstantVal->getType() != Ty) {
2632 // Allow a constant struct with a single member to be converted
2633 // to a union, if the union has a member which is the same type
2634 // as the struct member.
2635 if (const UnionType* utype = dyn_cast<UnionType>(Ty)) {
2636 return ParseUnionValue(utype, ID, V);
2637 }
2638
Chris Lattnerdf986172009-01-02 07:01:27 +00002639 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002640 }
2641
Chris Lattnerdf986172009-01-02 07:01:27 +00002642 V = ID.ConstantVal;
2643 return false;
2644 }
2645}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002646
Chris Lattnerdf986172009-01-02 07:01:27 +00002647bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2648 V = 0;
2649 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002650 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002651 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002652}
2653
2654bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002655 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002656 return ParseType(T) ||
2657 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002658}
2659
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002660bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2661 PerFunctionState &PFS) {
2662 Value *V;
2663 Loc = Lex.getLoc();
2664 if (ParseTypeAndValue(V, PFS)) return true;
2665 if (!isa<BasicBlock>(V))
2666 return Error(Loc, "expected a basic block");
2667 BB = cast<BasicBlock>(V);
2668 return false;
2669}
2670
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002671bool LLParser::ParseUnionValue(const UnionType* utype, ValID &ID, Value *&V) {
2672 if (const StructType* stype = dyn_cast<StructType>(ID.ConstantVal->getType())) {
2673 if (stype->getNumContainedTypes() != 1)
2674 return Error(ID.Loc, "constant expression type mismatch");
2675 int index = utype->getElementTypeIndex(stype->getContainedType(0));
2676 if (index < 0)
2677 return Error(ID.Loc, "initializer type is not a member of the union");
2678
2679 V = ConstantUnion::get(
2680 utype, cast<Constant>(ID.ConstantVal->getOperand(0)));
2681 return false;
2682 }
2683
2684 return Error(ID.Loc, "constant expression type mismatch");
2685}
2686
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002687
Chris Lattnerdf986172009-01-02 07:01:27 +00002688/// FunctionHeader
2689/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2690/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2691/// OptionalAlign OptGC
2692bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2693 // Parse the linkage.
2694 LocTy LinkageLoc = Lex.getLoc();
2695 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002696
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002697 unsigned Visibility, RetAttrs;
2698 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002699 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002700 LocTy RetTypeLoc = Lex.getLoc();
2701 if (ParseOptionalLinkage(Linkage) ||
2702 ParseOptionalVisibility(Visibility) ||
2703 ParseOptionalCallingConv(CC) ||
2704 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002705 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002706 return true;
2707
2708 // Verify that the linkage is ok.
2709 switch ((GlobalValue::LinkageTypes)Linkage) {
2710 case GlobalValue::ExternalLinkage:
2711 break; // always ok.
2712 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002713 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002714 if (isDefine)
2715 return Error(LinkageLoc, "invalid linkage for function definition");
2716 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002717 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002718 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002719 case GlobalValue::LinkerPrivateWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002720 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002721 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002722 case GlobalValue::LinkOnceAnyLinkage:
2723 case GlobalValue::LinkOnceODRLinkage:
2724 case GlobalValue::WeakAnyLinkage:
2725 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002726 case GlobalValue::DLLExportLinkage:
2727 if (!isDefine)
2728 return Error(LinkageLoc, "invalid linkage for function declaration");
2729 break;
2730 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002731 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002732 return Error(LinkageLoc, "invalid function linkage type");
2733 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002734
Chris Lattner99bb3152009-01-05 08:00:30 +00002735 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002736 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002737 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002738
Chris Lattnerdf986172009-01-02 07:01:27 +00002739 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002740
2741 std::string FunctionName;
2742 if (Lex.getKind() == lltok::GlobalVar) {
2743 FunctionName = Lex.getStrVal();
2744 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2745 unsigned NameID = Lex.getUIntVal();
2746
2747 if (NameID != NumberedVals.size())
2748 return TokError("function expected to be numbered '%" +
2749 utostr(NumberedVals.size()) + "'");
2750 } else {
2751 return TokError("expected function name");
2752 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002753
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002754 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002755
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002756 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002757 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002758
Chris Lattnerdf986172009-01-02 07:01:27 +00002759 std::vector<ArgInfo> ArgList;
2760 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002761 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002762 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002763 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002764 std::string GC;
2765
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002766 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002767 ParseOptionalAttrs(FuncAttrs, 2) ||
2768 (EatIfPresent(lltok::kw_section) &&
2769 ParseStringConstant(Section)) ||
2770 ParseOptionalAlignment(Alignment) ||
2771 (EatIfPresent(lltok::kw_gc) &&
2772 ParseStringConstant(GC)))
2773 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002774
2775 // If the alignment was parsed as an attribute, move to the alignment field.
2776 if (FuncAttrs & Attribute::Alignment) {
2777 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2778 FuncAttrs &= ~Attribute::Alignment;
2779 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002780
Chris Lattnerdf986172009-01-02 07:01:27 +00002781 // Okay, if we got here, the function is syntactically valid. Convert types
2782 // and do semantic checks.
2783 std::vector<const Type*> ParamTypeList;
2784 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002785 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002786 // attributes.
2787 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2788 if (FuncAttrs & ObsoleteFuncAttrs) {
2789 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2790 FuncAttrs &= ~ObsoleteFuncAttrs;
2791 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002792
Chris Lattnerdf986172009-01-02 07:01:27 +00002793 if (RetAttrs != Attribute::None)
2794 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002795
Chris Lattnerdf986172009-01-02 07:01:27 +00002796 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2797 ParamTypeList.push_back(ArgList[i].Type);
2798 if (ArgList[i].Attrs != Attribute::None)
2799 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2800 }
2801
2802 if (FuncAttrs != Attribute::None)
2803 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2804
2805 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002806
Benjamin Kramerf0127052010-01-05 13:12:22 +00002807 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002808 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2809
Owen Andersonfba933c2009-07-01 23:57:11 +00002810 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002811 FunctionType::get(RetType, ParamTypeList, isVarArg);
2812 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002813
2814 Fn = 0;
2815 if (!FunctionName.empty()) {
2816 // If this was a definition of a forward reference, remove the definition
2817 // from the forward reference table and fill in the forward ref.
2818 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2819 ForwardRefVals.find(FunctionName);
2820 if (FRVI != ForwardRefVals.end()) {
2821 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002822 if (Fn->getType() != PFT)
2823 return Error(FRVI->second.second, "invalid forward reference to "
2824 "function '" + FunctionName + "' with wrong type!");
2825
Chris Lattnerdf986172009-01-02 07:01:27 +00002826 ForwardRefVals.erase(FRVI);
2827 } else if ((Fn = M->getFunction(FunctionName))) {
2828 // If this function already exists in the symbol table, then it is
2829 // multiply defined. We accept a few cases for old backwards compat.
2830 // FIXME: Remove this stuff for LLVM 3.0.
2831 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2832 (!Fn->isDeclaration() && isDefine)) {
2833 // If the redefinition has different type or different attributes,
2834 // reject it. If both have bodies, reject it.
2835 return Error(NameLoc, "invalid redefinition of function '" +
2836 FunctionName + "'");
2837 } else if (Fn->isDeclaration()) {
2838 // Make sure to strip off any argument names so we can't get conflicts.
2839 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2840 AI != AE; ++AI)
2841 AI->setName("");
2842 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002843 } else if (M->getNamedValue(FunctionName)) {
2844 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002845 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002846
Dan Gohman41905542009-08-29 23:37:49 +00002847 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002848 // If this is a definition of a forward referenced function, make sure the
2849 // types agree.
2850 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2851 = ForwardRefValIDs.find(NumberedVals.size());
2852 if (I != ForwardRefValIDs.end()) {
2853 Fn = cast<Function>(I->second.first);
2854 if (Fn->getType() != PFT)
2855 return Error(NameLoc, "type of definition and forward reference of '@" +
2856 utostr(NumberedVals.size()) +"' disagree");
2857 ForwardRefValIDs.erase(I);
2858 }
2859 }
2860
2861 if (Fn == 0)
2862 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2863 else // Move the forward-reference to the correct spot in the module.
2864 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2865
2866 if (FunctionName.empty())
2867 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002868
Chris Lattnerdf986172009-01-02 07:01:27 +00002869 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2870 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2871 Fn->setCallingConv(CC);
2872 Fn->setAttributes(PAL);
2873 Fn->setAlignment(Alignment);
2874 Fn->setSection(Section);
2875 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002876
Chris Lattnerdf986172009-01-02 07:01:27 +00002877 // Add all of the arguments we parsed to the function.
2878 Function::arg_iterator ArgIt = Fn->arg_begin();
2879 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002880 // If we run out of arguments in the Function prototype, exit early.
2881 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2882 if (ArgIt == Fn->arg_end()) break;
2883
Chris Lattnerdf986172009-01-02 07:01:27 +00002884 // If the argument has a name, insert it into the argument symbol table.
2885 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002886
Chris Lattnerdf986172009-01-02 07:01:27 +00002887 // Set the name, if it conflicted, it will be auto-renamed.
2888 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002889
Chris Lattnerdf986172009-01-02 07:01:27 +00002890 if (ArgIt->getNameStr() != ArgList[i].Name)
2891 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2892 ArgList[i].Name + "'");
2893 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002894
Chris Lattnerdf986172009-01-02 07:01:27 +00002895 return false;
2896}
2897
2898
2899/// ParseFunctionBody
2900/// ::= '{' BasicBlock+ '}'
2901/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2902///
2903bool LLParser::ParseFunctionBody(Function &Fn) {
2904 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2905 return TokError("expected '{' in function body");
2906 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002907
Chris Lattner09d9ef42009-10-28 03:39:23 +00002908 int FunctionNumber = -1;
2909 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2910
2911 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002912
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002913 // We need at least one basic block.
2914 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2915 return TokError("function body requires at least one basic block");
2916
Chris Lattnerdf986172009-01-02 07:01:27 +00002917 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2918 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002919
Chris Lattnerdf986172009-01-02 07:01:27 +00002920 // Eat the }.
2921 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002922
Chris Lattnerdf986172009-01-02 07:01:27 +00002923 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002924 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002925}
2926
2927/// ParseBasicBlock
2928/// ::= LabelStr? Instruction*
2929bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2930 // If this basic block starts out with a name, remember it.
2931 std::string Name;
2932 LocTy NameLoc = Lex.getLoc();
2933 if (Lex.getKind() == lltok::LabelStr) {
2934 Name = Lex.getStrVal();
2935 Lex.Lex();
2936 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002937
Chris Lattnerdf986172009-01-02 07:01:27 +00002938 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2939 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002940
Chris Lattnerdf986172009-01-02 07:01:27 +00002941 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002942
Chris Lattnerdf986172009-01-02 07:01:27 +00002943 // Parse the instructions in this block until we get a terminator.
2944 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002945 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002946 do {
2947 // This instruction may have three possibilities for a name: a) none
2948 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2949 LocTy NameLoc = Lex.getLoc();
2950 int NameID = -1;
2951 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002952
Chris Lattnerdf986172009-01-02 07:01:27 +00002953 if (Lex.getKind() == lltok::LocalVarID) {
2954 NameID = Lex.getUIntVal();
2955 Lex.Lex();
2956 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2957 return true;
2958 } else if (Lex.getKind() == lltok::LocalVar ||
2959 // FIXME: REMOVE IN LLVM 3.0
2960 Lex.getKind() == lltok::StringConstant) {
2961 NameStr = Lex.getStrVal();
2962 Lex.Lex();
2963 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2964 return true;
2965 }
Devang Patelf633a062009-09-17 23:04:48 +00002966
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002967 switch (ParseInstruction(Inst, BB, PFS)) {
2968 default: assert(0 && "Unknown ParseInstruction result!");
2969 case InstError: return true;
2970 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002971 BB->getInstList().push_back(Inst);
2972
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002973 // With a normal result, we check to see if the instruction is followed by
2974 // a comma and metadata.
2975 if (EatIfPresent(lltok::comma))
Chris Lattnerfe805242010-04-01 04:51:13 +00002976 if (ParseInstructionMetadata(Inst))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002977 return true;
2978 break;
2979 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002980 BB->getInstList().push_back(Inst);
2981
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002982 // If the instruction parser ate an extra comma at the end of it, it
2983 // *must* be followed by metadata.
Chris Lattnerfe805242010-04-01 04:51:13 +00002984 if (ParseInstructionMetadata(Inst))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002985 return true;
2986 break;
2987 }
Devang Patelf633a062009-09-17 23:04:48 +00002988
Chris Lattnerdf986172009-01-02 07:01:27 +00002989 // Set the name on the instruction.
2990 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2991 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002992
Chris Lattnerdf986172009-01-02 07:01:27 +00002993 return false;
2994}
2995
2996//===----------------------------------------------------------------------===//
2997// Instruction Parsing.
2998//===----------------------------------------------------------------------===//
2999
3000/// ParseInstruction - Parse one of the many different instructions.
3001///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003002int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3003 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003004 lltok::Kind Token = Lex.getKind();
3005 if (Token == lltok::Eof)
3006 return TokError("found end of file when expecting more instructions");
3007 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003008 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00003009 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003010
Chris Lattnerdf986172009-01-02 07:01:27 +00003011 switch (Token) {
3012 default: return Error(Loc, "expected instruction opcode");
3013 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00003014 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
3015 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003016 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3017 case lltok::kw_br: return ParseBr(Inst, PFS);
3018 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00003019 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003020 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3021 // Binary Operators.
3022 case lltok::kw_add:
3023 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00003024 case lltok::kw_mul: {
3025 bool NUW = false;
3026 bool NSW = false;
3027 LocTy ModifierLoc = Lex.getLoc();
3028 if (EatIfPresent(lltok::kw_nuw))
3029 NUW = true;
3030 if (EatIfPresent(lltok::kw_nsw)) {
3031 NSW = true;
3032 if (EatIfPresent(lltok::kw_nuw))
3033 NUW = true;
3034 }
Dan Gohman1eaac532010-05-03 22:44:19 +00003035 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
Dan Gohman59858cf2009-07-27 16:11:46 +00003036 if (!Result) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003037 if (!Inst->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00003038 if (NUW)
3039 return Error(ModifierLoc, "nuw only applies to integer operations");
3040 if (NSW)
3041 return Error(ModifierLoc, "nsw only applies to integer operations");
3042 }
3043 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003044 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003045 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003046 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003047 }
3048 return Result;
3049 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003050 case lltok::kw_fadd:
3051 case lltok::kw_fsub:
3052 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3053
Dan Gohman59858cf2009-07-27 16:11:46 +00003054 case lltok::kw_sdiv: {
3055 bool Exact = false;
3056 if (EatIfPresent(lltok::kw_exact))
3057 Exact = true;
3058 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3059 if (!Result)
3060 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003061 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003062 return Result;
3063 }
3064
Chris Lattnerdf986172009-01-02 07:01:27 +00003065 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00003066 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003067 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00003068 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003069 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00003070 case lltok::kw_shl:
3071 case lltok::kw_lshr:
3072 case lltok::kw_ashr:
3073 case lltok::kw_and:
3074 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003075 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003076 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003077 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003078 // Casts.
3079 case lltok::kw_trunc:
3080 case lltok::kw_zext:
3081 case lltok::kw_sext:
3082 case lltok::kw_fptrunc:
3083 case lltok::kw_fpext:
3084 case lltok::kw_bitcast:
3085 case lltok::kw_uitofp:
3086 case lltok::kw_sitofp:
3087 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003088 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003089 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003090 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003091 // Other.
3092 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003093 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003094 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3095 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3096 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3097 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3098 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3099 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3100 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003101 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3102 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00003103 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003104 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3105 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3106 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003107 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00003108 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003109 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00003110 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003111 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003112 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003113 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3114 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3115 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3116 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3117 }
3118}
3119
3120/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3121bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003122 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003123 switch (Lex.getKind()) {
3124 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3125 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3126 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3127 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3128 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3129 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3130 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3131 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3132 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3133 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3134 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3135 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3136 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3137 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3138 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3139 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3140 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3141 }
3142 } else {
3143 switch (Lex.getKind()) {
3144 default: TokError("expected icmp predicate (e.g. 'eq')");
3145 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3146 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3147 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3148 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3149 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3150 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3151 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3152 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3153 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3154 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3155 }
3156 }
3157 Lex.Lex();
3158 return false;
3159}
3160
3161//===----------------------------------------------------------------------===//
3162// Terminator Instructions.
3163//===----------------------------------------------------------------------===//
3164
3165/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003166/// ::= 'ret' void (',' !dbg, !1)*
3167/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3168/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00003169/// [[obsolete: LLVM 3.0]]
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003170int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3171 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003172 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003173 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003174
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003175 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003176 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003177 return false;
3178 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003179
Chris Lattnerdf986172009-01-02 07:01:27 +00003180 Value *RV;
3181 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003182
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003183 bool ExtraComma = false;
Devang Patelf633a062009-09-17 23:04:48 +00003184 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003185 // Parse optional custom metadata, e.g. !dbg
Chris Lattner1d928312009-12-30 05:02:06 +00003186 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003187 ExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003188 } else {
3189 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003190 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3191 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003192 SmallVector<Value*, 8> RVs;
3193 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003194
Devang Patelf633a062009-09-17 23:04:48 +00003195 do {
Devang Patel0475c912009-09-29 00:01:14 +00003196 // If optional custom metadata, e.g. !dbg is seen then this is the
3197 // end of MRV.
Chris Lattner1d928312009-12-30 05:02:06 +00003198 if (Lex.getKind() == lltok::MetadataVar)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003199 break;
3200 if (ParseTypeAndValue(RV, PFS)) return true;
3201 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003202 } while (EatIfPresent(lltok::comma));
3203
3204 RV = UndefValue::get(PFS.getFunction().getReturnType());
3205 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003206 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3207 BB->getInstList().push_back(I);
3208 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003209 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003210 }
3211 }
Devang Patelf633a062009-09-17 23:04:48 +00003212
Owen Anderson1d0be152009-08-13 21:58:54 +00003213 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003214 return ExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003215}
3216
3217
3218/// ParseBr
3219/// ::= 'br' TypeAndValue
3220/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3221bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3222 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003223 Value *Op0;
3224 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003225 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003226
Chris Lattnerdf986172009-01-02 07:01:27 +00003227 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3228 Inst = BranchInst::Create(BB);
3229 return false;
3230 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003231
Owen Anderson1d0be152009-08-13 21:58:54 +00003232 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003233 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003234
Chris Lattnerdf986172009-01-02 07:01:27 +00003235 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003236 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003237 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003238 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003239 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003240
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003241 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003242 return false;
3243}
3244
3245/// ParseSwitch
3246/// Instruction
3247/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3248/// JumpTable
3249/// ::= (TypeAndValue ',' TypeAndValue)*
3250bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3251 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003252 Value *Cond;
3253 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003254 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3255 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003256 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003257 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3258 return true;
3259
Duncan Sands1df98592010-02-16 11:11:14 +00003260 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003261 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003262
Chris Lattnerdf986172009-01-02 07:01:27 +00003263 // Parse the jump table pairs.
3264 SmallPtrSet<Value*, 32> SeenCases;
3265 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3266 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003267 Value *Constant;
3268 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003269
Chris Lattnerdf986172009-01-02 07:01:27 +00003270 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3271 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003272 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003273 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003274
Chris Lattnerdf986172009-01-02 07:01:27 +00003275 if (!SeenCases.insert(Constant))
3276 return Error(CondLoc, "duplicate case value in switch");
3277 if (!isa<ConstantInt>(Constant))
3278 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003279
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003280 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003281 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003282
Chris Lattnerdf986172009-01-02 07:01:27 +00003283 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003284
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003285 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003286 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3287 SI->addCase(Table[i].first, Table[i].second);
3288 Inst = SI;
3289 return false;
3290}
3291
Chris Lattnerab21db72009-10-28 00:19:10 +00003292/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003293/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003294/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3295bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003296 LocTy AddrLoc;
3297 Value *Address;
3298 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003299 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3300 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003301 return true;
3302
Duncan Sands1df98592010-02-16 11:11:14 +00003303 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003304 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003305
3306 // Parse the destination list.
3307 SmallVector<BasicBlock*, 16> DestList;
3308
3309 if (Lex.getKind() != lltok::rsquare) {
3310 BasicBlock *DestBB;
3311 if (ParseTypeAndBasicBlock(DestBB, PFS))
3312 return true;
3313 DestList.push_back(DestBB);
3314
3315 while (EatIfPresent(lltok::comma)) {
3316 if (ParseTypeAndBasicBlock(DestBB, PFS))
3317 return true;
3318 DestList.push_back(DestBB);
3319 }
3320 }
3321
3322 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3323 return true;
3324
Chris Lattnerab21db72009-10-28 00:19:10 +00003325 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003326 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3327 IBI->addDestination(DestList[i]);
3328 Inst = IBI;
3329 return false;
3330}
3331
3332
Chris Lattnerdf986172009-01-02 07:01:27 +00003333/// ParseInvoke
3334/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3335/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3336bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3337 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003338 unsigned RetAttrs, FnAttrs;
3339 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003340 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003341 LocTy RetTypeLoc;
3342 ValID CalleeID;
3343 SmallVector<ParamInfo, 16> ArgList;
3344
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003345 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003346 if (ParseOptionalCallingConv(CC) ||
3347 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003348 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003349 ParseValID(CalleeID) ||
3350 ParseParameterList(ArgList, PFS) ||
3351 ParseOptionalAttrs(FnAttrs, 2) ||
3352 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003353 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003354 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003355 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003356 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003357
Chris Lattnerdf986172009-01-02 07:01:27 +00003358 // If RetType is a non-function pointer type, then this is the short syntax
3359 // for the call, which means that RetType is just the return type. Infer the
3360 // rest of the function argument types from the arguments that are present.
3361 const PointerType *PFTy = 0;
3362 const FunctionType *Ty = 0;
3363 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3364 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3365 // Pull out the types of all of the arguments...
3366 std::vector<const Type*> ParamTypes;
3367 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3368 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003369
Chris Lattnerdf986172009-01-02 07:01:27 +00003370 if (!FunctionType::isValidReturnType(RetType))
3371 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003372
Owen Andersondebcb012009-07-29 22:17:13 +00003373 Ty = FunctionType::get(RetType, ParamTypes, false);
3374 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003375 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003376
Chris Lattnerdf986172009-01-02 07:01:27 +00003377 // Look up the callee.
3378 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003379 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003380
Chris Lattnerdf986172009-01-02 07:01:27 +00003381 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3382 // function attributes.
3383 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3384 if (FnAttrs & ObsoleteFuncAttrs) {
3385 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3386 FnAttrs &= ~ObsoleteFuncAttrs;
3387 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003388
Chris Lattnerdf986172009-01-02 07:01:27 +00003389 // Set up the Attributes for the function.
3390 SmallVector<AttributeWithIndex, 8> Attrs;
3391 if (RetAttrs != Attribute::None)
3392 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003393
Chris Lattnerdf986172009-01-02 07:01:27 +00003394 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003395
Chris Lattnerdf986172009-01-02 07:01:27 +00003396 // Loop through FunctionType's arguments and ensure they are specified
3397 // correctly. Also, gather any parameter attributes.
3398 FunctionType::param_iterator I = Ty->param_begin();
3399 FunctionType::param_iterator E = Ty->param_end();
3400 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3401 const Type *ExpectedTy = 0;
3402 if (I != E) {
3403 ExpectedTy = *I++;
3404 } else if (!Ty->isVarArg()) {
3405 return Error(ArgList[i].Loc, "too many arguments specified");
3406 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003407
Chris Lattnerdf986172009-01-02 07:01:27 +00003408 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3409 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3410 ExpectedTy->getDescription() + "'");
3411 Args.push_back(ArgList[i].V);
3412 if (ArgList[i].Attrs != Attribute::None)
3413 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3414 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003415
Chris Lattnerdf986172009-01-02 07:01:27 +00003416 if (I != E)
3417 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003418
Chris Lattnerdf986172009-01-02 07:01:27 +00003419 if (FnAttrs != Attribute::None)
3420 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003421
Chris Lattnerdf986172009-01-02 07:01:27 +00003422 // Finish off the Attributes and check them
3423 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003424
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003425 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003426 Args.begin(), Args.end());
3427 II->setCallingConv(CC);
3428 II->setAttributes(PAL);
3429 Inst = II;
3430 return false;
3431}
3432
3433
3434
3435//===----------------------------------------------------------------------===//
3436// Binary Operators.
3437//===----------------------------------------------------------------------===//
3438
3439/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003440/// ::= ArithmeticOps TypeAndValue ',' Value
3441///
3442/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3443/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003444bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003445 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003446 LocTy Loc; Value *LHS, *RHS;
3447 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3448 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3449 ParseValue(LHS->getType(), RHS, PFS))
3450 return true;
3451
Chris Lattnere914b592009-01-05 08:24:46 +00003452 bool Valid;
3453 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003454 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003455 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003456 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3457 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003458 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003459 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3460 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003461 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003462
Chris Lattnere914b592009-01-05 08:24:46 +00003463 if (!Valid)
3464 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003465
Chris Lattnerdf986172009-01-02 07:01:27 +00003466 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3467 return false;
3468}
3469
3470/// ParseLogical
3471/// ::= ArithmeticOps TypeAndValue ',' Value {
3472bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3473 unsigned Opc) {
3474 LocTy Loc; Value *LHS, *RHS;
3475 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3476 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3477 ParseValue(LHS->getType(), RHS, PFS))
3478 return true;
3479
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003480 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003481 return Error(Loc,"instruction requires integer or integer vector operands");
3482
3483 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3484 return false;
3485}
3486
3487
3488/// ParseCompare
3489/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3490/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003491bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3492 unsigned Opc) {
3493 // Parse the integer/fp comparison predicate.
3494 LocTy Loc;
3495 unsigned Pred;
3496 Value *LHS, *RHS;
3497 if (ParseCmpPredicate(Pred, Opc) ||
3498 ParseTypeAndValue(LHS, Loc, PFS) ||
3499 ParseToken(lltok::comma, "expected ',' after compare value") ||
3500 ParseValue(LHS->getType(), RHS, PFS))
3501 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003502
Chris Lattnerdf986172009-01-02 07:01:27 +00003503 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003504 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003505 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003506 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003507 } else {
3508 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003509 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003510 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003511 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003512 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003513 }
3514 return false;
3515}
3516
3517//===----------------------------------------------------------------------===//
3518// Other Instructions.
3519//===----------------------------------------------------------------------===//
3520
3521
3522/// ParseCast
3523/// ::= CastOpc TypeAndValue 'to' Type
3524bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3525 unsigned Opc) {
3526 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003527 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003528 if (ParseTypeAndValue(Op, Loc, PFS) ||
3529 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3530 ParseType(DestTy))
3531 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003532
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003533 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3534 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003535 return Error(Loc, "invalid cast opcode for cast from '" +
3536 Op->getType()->getDescription() + "' to '" +
3537 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003538 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003539 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3540 return false;
3541}
3542
3543/// ParseSelect
3544/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3545bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3546 LocTy Loc;
3547 Value *Op0, *Op1, *Op2;
3548 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3549 ParseToken(lltok::comma, "expected ',' after select condition") ||
3550 ParseTypeAndValue(Op1, PFS) ||
3551 ParseToken(lltok::comma, "expected ',' after select value") ||
3552 ParseTypeAndValue(Op2, PFS))
3553 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003554
Chris Lattnerdf986172009-01-02 07:01:27 +00003555 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3556 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003557
Chris Lattnerdf986172009-01-02 07:01:27 +00003558 Inst = SelectInst::Create(Op0, Op1, Op2);
3559 return false;
3560}
3561
Chris Lattner0088a5c2009-01-05 08:18:44 +00003562/// ParseVA_Arg
3563/// ::= 'va_arg' TypeAndValue ',' Type
3564bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003565 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003566 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003567 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003568 if (ParseTypeAndValue(Op, PFS) ||
3569 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003570 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003571 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003572
Chris Lattner0088a5c2009-01-05 08:18:44 +00003573 if (!EltTy->isFirstClassType())
3574 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003575
3576 Inst = new VAArgInst(Op, EltTy);
3577 return false;
3578}
3579
3580/// ParseExtractElement
3581/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3582bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3583 LocTy Loc;
3584 Value *Op0, *Op1;
3585 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3586 ParseToken(lltok::comma, "expected ',' after extract value") ||
3587 ParseTypeAndValue(Op1, PFS))
3588 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003589
Chris Lattnerdf986172009-01-02 07:01:27 +00003590 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3591 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003592
Eric Christophera3500da2009-07-25 02:28:41 +00003593 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003594 return false;
3595}
3596
3597/// ParseInsertElement
3598/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3599bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3600 LocTy Loc;
3601 Value *Op0, *Op1, *Op2;
3602 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3603 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3604 ParseTypeAndValue(Op1, PFS) ||
3605 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3606 ParseTypeAndValue(Op2, PFS))
3607 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003608
Chris Lattnerdf986172009-01-02 07:01:27 +00003609 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003610 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003611
Chris Lattnerdf986172009-01-02 07:01:27 +00003612 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3613 return false;
3614}
3615
3616/// ParseShuffleVector
3617/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3618bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3619 LocTy Loc;
3620 Value *Op0, *Op1, *Op2;
3621 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3622 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3623 ParseTypeAndValue(Op1, PFS) ||
3624 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3625 ParseTypeAndValue(Op2, PFS))
3626 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003627
Chris Lattnerdf986172009-01-02 07:01:27 +00003628 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3629 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003630
Chris Lattnerdf986172009-01-02 07:01:27 +00003631 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3632 return false;
3633}
3634
3635/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003636/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003637int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003638 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003639 Value *Op0, *Op1;
3640 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003641
Chris Lattnerdf986172009-01-02 07:01:27 +00003642 if (ParseType(Ty) ||
3643 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3644 ParseValue(Ty, Op0, PFS) ||
3645 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003646 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003647 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3648 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003649
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003650 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003651 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3652 while (1) {
3653 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003654
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003655 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003656 break;
3657
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003658 if (Lex.getKind() == lltok::MetadataVar) {
3659 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003660 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003661 }
Devang Patela43d46f2009-10-16 18:45:49 +00003662
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003663 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003664 ParseValue(Ty, Op0, PFS) ||
3665 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003666 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003667 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3668 return true;
3669 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003670
Chris Lattnerdf986172009-01-02 07:01:27 +00003671 if (!Ty->isFirstClassType())
3672 return Error(TypeLoc, "phi node must have first class type");
3673
3674 PHINode *PN = PHINode::Create(Ty);
3675 PN->reserveOperandSpace(PHIVals.size());
3676 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3677 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3678 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003679 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003680}
3681
3682/// ParseCall
3683/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3684/// ParameterList OptionalAttrs
3685bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3686 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003687 unsigned RetAttrs, FnAttrs;
3688 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003689 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003690 LocTy RetTypeLoc;
3691 ValID CalleeID;
3692 SmallVector<ParamInfo, 16> ArgList;
3693 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003694
Chris Lattnerdf986172009-01-02 07:01:27 +00003695 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3696 ParseOptionalCallingConv(CC) ||
3697 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003698 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003699 ParseValID(CalleeID) ||
3700 ParseParameterList(ArgList, PFS) ||
3701 ParseOptionalAttrs(FnAttrs, 2))
3702 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003703
Chris Lattnerdf986172009-01-02 07:01:27 +00003704 // If RetType is a non-function pointer type, then this is the short syntax
3705 // for the call, which means that RetType is just the return type. Infer the
3706 // rest of the function argument types from the arguments that are present.
3707 const PointerType *PFTy = 0;
3708 const FunctionType *Ty = 0;
3709 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3710 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3711 // Pull out the types of all of the arguments...
3712 std::vector<const Type*> ParamTypes;
3713 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3714 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003715
Chris Lattnerdf986172009-01-02 07:01:27 +00003716 if (!FunctionType::isValidReturnType(RetType))
3717 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003718
Owen Andersondebcb012009-07-29 22:17:13 +00003719 Ty = FunctionType::get(RetType, ParamTypes, false);
3720 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003721 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003722
Chris Lattnerdf986172009-01-02 07:01:27 +00003723 // Look up the callee.
3724 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003725 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003726
Chris Lattnerdf986172009-01-02 07:01:27 +00003727 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3728 // function attributes.
3729 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3730 if (FnAttrs & ObsoleteFuncAttrs) {
3731 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3732 FnAttrs &= ~ObsoleteFuncAttrs;
3733 }
3734
3735 // Set up the Attributes for the function.
3736 SmallVector<AttributeWithIndex, 8> Attrs;
3737 if (RetAttrs != Attribute::None)
3738 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003739
Chris Lattnerdf986172009-01-02 07:01:27 +00003740 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003741
Chris Lattnerdf986172009-01-02 07:01:27 +00003742 // Loop through FunctionType's arguments and ensure they are specified
3743 // correctly. Also, gather any parameter attributes.
3744 FunctionType::param_iterator I = Ty->param_begin();
3745 FunctionType::param_iterator E = Ty->param_end();
3746 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3747 const Type *ExpectedTy = 0;
3748 if (I != E) {
3749 ExpectedTy = *I++;
3750 } else if (!Ty->isVarArg()) {
3751 return Error(ArgList[i].Loc, "too many arguments specified");
3752 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003753
Chris Lattnerdf986172009-01-02 07:01:27 +00003754 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3755 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3756 ExpectedTy->getDescription() + "'");
3757 Args.push_back(ArgList[i].V);
3758 if (ArgList[i].Attrs != Attribute::None)
3759 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3760 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003761
Chris Lattnerdf986172009-01-02 07:01:27 +00003762 if (I != E)
3763 return Error(CallLoc, "not enough parameters specified for call");
3764
3765 if (FnAttrs != Attribute::None)
3766 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3767
3768 // Finish off the Attributes and check them
3769 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003770
Chris Lattnerdf986172009-01-02 07:01:27 +00003771 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3772 CI->setTailCall(isTail);
3773 CI->setCallingConv(CC);
3774 CI->setAttributes(PAL);
3775 Inst = CI;
3776 return false;
3777}
3778
3779//===----------------------------------------------------------------------===//
3780// Memory Instructions.
3781//===----------------------------------------------------------------------===//
3782
3783/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003784/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3785/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003786int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3787 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003788 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003789 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003790 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003791 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003792 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003793
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003794 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003795 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003796 if (Lex.getKind() == lltok::kw_align) {
3797 if (ParseOptionalAlignment(Alignment)) return true;
3798 } else if (Lex.getKind() == lltok::MetadataVar) {
3799 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003800 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003801 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3802 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3803 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003804 }
3805 }
3806
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003807 if (Size && !Size->getType()->isIntegerTy())
3808 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003809
Victor Hernandez68afa542009-10-21 19:11:40 +00003810 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003811 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003812 return AteExtraComma ? InstExtraComma : InstNormal;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003813 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003814
3815 // Autoupgrade old malloc instruction to malloc call.
3816 // FIXME: Remove in LLVM 3.0.
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003817 if (Size && !Size->getType()->isIntegerTy(32))
3818 return Error(SizeLoc, "element count must be i32");
Victor Hernandez68afa542009-10-21 19:11:40 +00003819 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003820 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3821 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
Victor Hernandez68afa542009-10-21 19:11:40 +00003822 if (!MallocF)
3823 // Prototype malloc as "void *(int32)".
3824 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003825 MallocF = cast<Function>(
3826 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003827 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003828return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003829}
3830
3831/// ParseFree
3832/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003833bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3834 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003835 Value *Val; LocTy Loc;
3836 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003837 if (!Val->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003838 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003839 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003840 return false;
3841}
3842
3843/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003844/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003845int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3846 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003847 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003848 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003849 bool AteExtraComma = false;
3850 if (ParseTypeAndValue(Val, Loc, PFS) ||
3851 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3852 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003853
Duncan Sands1df98592010-02-16 11:11:14 +00003854 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003855 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3856 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003857
Chris Lattnerdf986172009-01-02 07:01:27 +00003858 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003859 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003860}
3861
3862/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003863/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003864int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3865 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003866 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003867 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003868 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003869 if (ParseTypeAndValue(Val, Loc, PFS) ||
3870 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003871 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3872 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003873 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003874
Duncan Sands1df98592010-02-16 11:11:14 +00003875 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003876 return Error(PtrLoc, "store operand must be a pointer");
3877 if (!Val->getType()->isFirstClassType())
3878 return Error(Loc, "store operand must be a first class value");
3879 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3880 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003881
Chris Lattnerdf986172009-01-02 07:01:27 +00003882 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003883 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003884}
3885
3886/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003887/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003888/// FIXME: Remove support for getresult in LLVM 3.0
3889bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3890 Value *Val; LocTy ValLoc, EltLoc;
3891 unsigned Element;
3892 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3893 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003894 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003895 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003896
Duncan Sands1df98592010-02-16 11:11:14 +00003897 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003898 return Error(ValLoc, "getresult inst requires an aggregate operand");
3899 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3900 return Error(EltLoc, "invalid getresult index for value");
3901 Inst = ExtractValueInst::Create(Val, Element);
3902 return false;
3903}
3904
3905/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003906/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003907int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003908 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003909
Dan Gohmandcb40a32009-07-29 15:58:36 +00003910 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003911
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003912 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003913
Duncan Sands1df98592010-02-16 11:11:14 +00003914 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003915 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003916
Chris Lattnerdf986172009-01-02 07:01:27 +00003917 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003918 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003919 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003920 if (Lex.getKind() == lltok::MetadataVar) {
3921 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003922 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003923 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003924 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003925 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003926 return Error(EltLoc, "getelementptr index must be an integer");
3927 Indices.push_back(Val);
3928 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003929
Chris Lattnerdf986172009-01-02 07:01:27 +00003930 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3931 Indices.begin(), Indices.end()))
3932 return Error(Loc, "invalid getelementptr indices");
3933 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003934 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003935 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003936 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003937}
3938
3939/// ParseExtractValue
3940/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003941int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003942 Value *Val; LocTy Loc;
3943 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003944 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003945 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003946 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003947 return true;
3948
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003949 if (!Val->getType()->isAggregateType())
3950 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003951
3952 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3953 Indices.end()))
3954 return Error(Loc, "invalid indices for extractvalue");
3955 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003956 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003957}
3958
3959/// ParseInsertValue
3960/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003961int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003962 Value *Val0, *Val1; LocTy Loc0, Loc1;
3963 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003964 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003965 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3966 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3967 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003968 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003969 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003970
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003971 if (!Val0->getType()->isAggregateType())
3972 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003973
Chris Lattnerdf986172009-01-02 07:01:27 +00003974 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3975 Indices.end()))
3976 return Error(Loc0, "invalid indices for insertvalue");
3977 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003978 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003979}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003980
3981//===----------------------------------------------------------------------===//
3982// Embedded metadata.
3983//===----------------------------------------------------------------------===//
3984
3985/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003986/// ::= Element (',' Element)*
3987/// Element
3988/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003989bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003990 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003991 // Check for an empty list.
3992 if (Lex.getKind() == lltok::rbrace)
3993 return false;
3994
Nick Lewycky21cc4462009-04-04 07:22:01 +00003995 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003996 // Null is a special case since it is typeless.
3997 if (EatIfPresent(lltok::kw_null)) {
3998 Elts.push_back(0);
3999 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00004000 }
Chris Lattnera7352392009-12-30 04:42:57 +00004001
4002 Value *V = 0;
4003 PATypeHolder Ty(Type::getVoidTy(Context));
4004 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00004005 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00004006 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00004007 return true;
4008
Nick Lewyckycb337992009-05-10 20:57:05 +00004009 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00004010 } while (EatIfPresent(lltok::comma));
4011
4012 return false;
4013}