blob: 9a9bd122692b5f7390f56b92d1e29998957aecf1 [file] [log] [blame]
Chris Lattner103ff152009-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 Gohman799a8c82009-07-20 21:19:07 +000022#include "llvm/Operator.h"
Chris Lattner103ff152009-01-02 07:01:27 +000023#include "llvm/ValueSymbolTable.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/StringExtras.h"
Edwin Török675d5622009-07-11 20:10:48 +000026#include "llvm/Support/ErrorHandling.h"
Chris Lattner103ff152009-01-02 07:01:27 +000027#include "llvm/Support/raw_ostream.h"
28using namespace llvm;
29
Chris Lattner6226fd22009-01-02 08:05:26 +000030/// Run: module ::= toplevelentity*
Chris Lattner9df8a4a2009-01-04 20:44:11 +000031bool LLParser::Run() {
Chris Lattner6226fd22009-01-02 08:05:26 +000032 // Prime the lexer.
33 Lex.Lex();
34
Chris Lattner9df8a4a2009-01-04 20:44:11 +000035 return ParseTopLevelEntities() ||
36 ValidateEndOfModule();
Chris Lattner103ff152009-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 Lattner8919f2e2010-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 Hernandez67439f02009-10-21 19:11:40 +000063 // Update auto-upgraded malloc calls to "malloc".
Chris Lattner708770b2009-10-18 05:09:15 +000064 // FIXME: Remove in LLVM 3.0.
Victor Hernandez6203d9d2009-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 Lattner5bb63f12009-10-28 03:39:23 +000071 Constant *RealMallocF = M->getFunction("malloc");
Victor Hernandez67439f02009-10-21 19:11:40 +000072 if (RealMallocF->getType() != MallocF->getType())
73 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
74 MallocF->replaceAllUsesWith(RealMallocF);
Victor Hernandez6203d9d2009-10-17 00:00:19 +000075 MallocF->eraseFromParent();
76 MallocF = NULL;
77 }
78 }
Chris Lattner5bb63f12009-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 Lattner103ff152009-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 Dunbar3be44e62009-09-20 02:20:51 +0000113
Chris Lattner103ff152009-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 Dunbar3be44e62009-09-20 02:20:51 +0000118
Chris Lattner103ff152009-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 Dunbar3be44e62009-09-20 02:20:51 +0000123
Devang Patelef716812009-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 Dunbar3be44e62009-09-20 02:20:51 +0000128
Devang Patelef716812009-07-08 19:23:54 +0000129
Chris Lattner103ff152009-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 Dunbar3be44e62009-09-20 02:20:51 +0000133
Devang Patel15e723d2009-08-28 23:24:31 +0000134 // Check debug info intrinsics.
135 CheckDebugInfoIntrinsics(M);
Chris Lattner103ff152009-01-02 07:01:27 +0000136 return false;
137}
138
Chris Lattner5bb63f12009-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 Lattner620cead2009-11-01 01:27:45 +0000145 if (PFS) {
Chris Lattner5bb63f12009-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 Lattner620cead2009-11-01 01:27:45 +0000148 else
Chris Lattner5bb63f12009-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 Lattner76356bc2009-11-02 18:28:45 +0000152 "cannot take address of numeric label after the function is defined");
Chris Lattner5bb63f12009-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 Lattner620cead2009-11-01 01:27:45 +0000158 if (Res == 0)
Chris Lattner5bb63f12009-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 Lattner103ff152009-01-02 07:01:27 +0000171//===----------------------------------------------------------------------===//
172// Top-Level Entities
173//===----------------------------------------------------------------------===//
174
175bool LLParser::ParseTopLevelEntities() {
Chris Lattner103ff152009-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 Gohman39c2d2f2009-08-12 23:32:33 +0000187 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattner103ff152009-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 Gohman39c2d2f2009-08-12 23:32:33 +0000190 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattner103ff152009-01-02 07:01:27 +0000191 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnerf39c84f2009-12-30 04:56:59 +0000192 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner7e4b4aa2009-12-30 05:02:06 +0000193 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattner103ff152009-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 Wendling41a07852009-07-20 01:03:30 +0000199 case lltok::kw_private : // OptionalLinkage
200 case lltok::kw_linker_private: // OptionalLinkage
Bill Wendlingf8b61372010-06-29 21:24:00 +0000201 case lltok::kw_linker_weak: // OptionalLinkage
Bill Wendling41a07852009-07-20 01:03:30 +0000202 case lltok::kw_internal: // OptionalLinkage
203 case lltok::kw_weak: // OptionalLinkage
204 case lltok::kw_weak_odr: // OptionalLinkage
205 case lltok::kw_linkonce: // OptionalLinkage
206 case lltok::kw_linkonce_odr: // OptionalLinkage
207 case lltok::kw_appending: // OptionalLinkage
208 case lltok::kw_dllexport: // OptionalLinkage
209 case lltok::kw_common: // OptionalLinkage
210 case lltok::kw_dllimport: // OptionalLinkage
211 case lltok::kw_extern_weak: // OptionalLinkage
212 case lltok::kw_external: { // OptionalLinkage
Chris Lattner103ff152009-01-02 07:01:27 +0000213 unsigned Linkage, Visibility;
214 if (ParseOptionalLinkage(Linkage) ||
215 ParseOptionalVisibility(Visibility) ||
Chris Lattner0ffa08f2009-07-02 23:08:13 +0000216 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattner103ff152009-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 Lattner0ffa08f2009-07-02 23:08:13 +0000225 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattner103ff152009-01-02 07:01:27 +0000226 return true;
227 break;
228 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000229
Chris Lattner103ff152009-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 Lattner0ffa08f2009-07-02 23:08:13 +0000234 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattner103ff152009-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 Dunbar3be44e62009-09-20 02:20:51 +0000246
247 std::string AsmStr;
Chris Lattner6226fd22009-01-02 08:05:26 +0000248 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
249 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000250
Chris Lattner103ff152009-01-02 07:01:27 +0000251 const std::string &AsmSoFar = M->getModuleInlineAsm();
252 if (AsmSoFar.empty())
Chris Lattner6226fd22009-01-02 08:05:26 +0000253 M->setModuleInlineAsm(AsmStr);
Chris Lattner103ff152009-01-02 07:01:27 +0000254 else
Chris Lattner6226fd22009-01-02 08:05:26 +0000255 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattner103ff152009-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 Lattner6226fd22009-01-02 08:05:26 +0000264 std::string Str;
Chris Lattner103ff152009-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 Lattner6226fd22009-01-02 08:05:26 +0000269 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
270 ParseStringConstant(Str))
Chris Lattner103ff152009-01-02 07:01:27 +0000271 return true;
Chris Lattner6226fd22009-01-02 08:05:26 +0000272 M->setTargetTriple(Str);
Chris Lattner103ff152009-01-02 07:01:27 +0000273 return false;
274 case lltok::kw_datalayout:
275 Lex.Lex();
Chris Lattner6226fd22009-01-02 08:05:26 +0000276 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
277 ParseStringConstant(Str))
Chris Lattner103ff152009-01-02 07:01:27 +0000278 return true;
Chris Lattner6226fd22009-01-02 08:05:26 +0000279 M->setDataLayout(Str);
Chris Lattner103ff152009-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 Lattner103ff152009-01-02 07:01:27 +0000289 Lex.Lex();
Chris Lattner6226fd22009-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 Dunbar3be44e62009-09-20 02:20:51 +0000296
Chris Lattner6226fd22009-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 Lattner103ff152009-01-02 07:01:27 +0000307}
308
Dan Gohman39c2d2f2009-08-12 23:32:33 +0000309/// ParseUnnamedType:
Chris Lattner103ff152009-01-02 07:01:27 +0000310/// ::= 'type' type
Dan Gohman39c2d2f2009-08-12 23:32:33 +0000311/// ::= LocalVarID '=' 'type' type
Chris Lattner103ff152009-01-02 07:01:27 +0000312bool LLParser::ParseUnnamedType() {
Dan Gohman39c2d2f2009-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 Lattner103ff152009-01-02 07:01:27 +0000326 LocTy TypeLoc = Lex.getLoc();
Chris Lattner9576acc2010-04-10 18:01:25 +0000327 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
Chris Lattner103ff152009-01-02 07:01:27 +0000328
Owen Anderson35b47072009-08-13 21:58:54 +0000329 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattner103ff152009-01-02 07:01:27 +0000330 if (ParseType(Ty)) return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000331
Chris Lattner103ff152009-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 Lattnerdd9f7c92009-01-05 18:19:46 +0000336 if (FI->second.first.get() == Ty)
337 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000338
Chris Lattner103ff152009-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 Dunbar3be44e62009-09-20 02:20:51 +0000343
Chris Lattner103ff152009-01-02 07:01:27 +0000344 NumberedTypes.push_back(Ty);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000345
Chris Lattner103ff152009-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 Lattner6226fd22009-01-02 08:05:26 +0000354 Lex.Lex(); // eat LocalVar.
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000355
Owen Anderson35b47072009-08-13 21:58:54 +0000356 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000357
Chris Lattner6226fd22009-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 Dunbar3be44e62009-09-20 02:20:51 +0000362
Chris Lattner103ff152009-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 Lattnerdd9f7c92009-01-05 18:19:46 +0000372 if (FI->second.first.get() == Ty)
373 return Error(NameLoc, "self referential type is invalid");
374
Chris Lattner103ff152009-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 Dunbar3be44e62009-09-20 02:20:51 +0000379
Chris Lattner103ff152009-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 Dunbar3be44e62009-09-20 02:20:51 +0000383
Chris Lattner103ff152009-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 Dunbar3be44e62009-09-20 02:20:51 +0000388
Chris Lattner103ff152009-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 Dunbar3be44e62009-09-20 02:20:51 +0000400
Chris Lattner103ff152009-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 Dunbar3be44e62009-09-20 02:20:51 +0000410
Chris Lattner103ff152009-01-02 07:01:27 +0000411 Function *F;
Chris Lattner6226fd22009-01-02 08:05:26 +0000412 return ParseFunctionHeader(F, true) ||
413 ParseFunctionBody(*F);
Chris Lattner103ff152009-01-02 07:01:27 +0000414}
415
Chris Lattner6226fd22009-01-02 08:05:26 +0000416/// ParseGlobalType
417/// ::= 'constant'
418/// ::= 'global'
Chris Lattner103ff152009-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 Sandsbdc3a152009-02-10 16:24:55 +0000424 else {
425 IsConstant = false;
Chris Lattner103ff152009-01-02 07:01:27 +0000426 return TokError("expected 'global' or 'constant'");
Duncan Sandsbdc3a152009-02-10 16:24:55 +0000427 }
Chris Lattner103ff152009-01-02 07:01:27 +0000428 Lex.Lex();
429 return false;
430}
431
Dan Gohman39c2d2f2009-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 Dunbar3be44e62009-09-20 02:20:51 +0000458
Dan Gohman39c2d2f2009-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 Lattner103ff152009-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 Dunbar3be44e62009-09-20 02:20:51 +0000472
Chris Lattner103ff152009-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 Dunbar3be44e62009-09-20 02:20:51 +0000479
Chris Lattner103ff152009-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 Patel12f2c9d2009-07-20 19:00:08 +0000485// MDString:
486// ::= '!' STRINGCONSTANT
Chris Lattnerb3d6fad2009-12-29 21:53:55 +0000487bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel12f2c9d2009-07-20 19:00:08 +0000488 std::string Str;
489 if (ParseStringConstant(Str)) return true;
Chris Lattnerb3d6fad2009-12-29 21:53:55 +0000490 Result = MDString::get(Context, Str);
Devang Patel12f2c9d2009-07-20 19:00:08 +0000491 return false;
492}
493
494// MDNode:
495// ::= '!' MDNodeNumber
Chris Lattner8919f2e2010-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 Lattner84a86d22009-12-30 04:15:23 +0000511bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel12f2c9d2009-07-20 19:00:08 +0000512 // !{ ..., !42, ... }
513 unsigned MID = 0;
Chris Lattner8919f2e2010-04-01 05:14:45 +0000514 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000515
Chris Lattner8919f2e2010-04-01 05:14:45 +0000516 // If not a forward reference, just return it now.
517 if (Result) return false;
Devang Patel12f2c9d2009-07-20 19:00:08 +0000518
Chris Lattner8919f2e2010-04-01 05:14:45 +0000519 // Otherwise, create MDNode forward reference.
Chris Lattner99c6ed12009-12-29 22:01:50 +0000520
521 // FIXME: This is not unique enough!
Devang Patel12f2c9d2009-07-20 19:00:08 +0000522 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Benjamin Kramer809f96f2009-12-29 22:17:06 +0000523 Value *V = MDString::get(Context, FwdRefName);
Chris Lattner99c6ed12009-12-29 22:01:50 +0000524 MDNode *FwdNode = MDNode::get(Context, &V, 1);
Devang Patel12f2c9d2009-07-20 19:00:08 +0000525 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattnercc286d22009-12-30 04:51:58 +0000526
527 if (NumberedMetadata.size() <= MID)
528 NumberedMetadata.resize(MID+1);
529 NumberedMetadata[MID] = FwdNode;
Chris Lattnerb3d6fad2009-12-29 21:53:55 +0000530 Result = FwdNode;
Devang Patel12f2c9d2009-07-20 19:00:08 +0000531 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000532}
Devang Patel12f2c9d2009-07-20 19:00:08 +0000533
Chris Lattnerbe7a0252009-12-29 22:35:39 +0000534/// ParseNamedMetadata:
Devang Patelf6e6aa02009-07-29 00:34:02 +0000535/// !foo = !{ !1, !2 }
536bool LLParser::ParseNamedMetadata() {
Chris Lattner7e4b4aa2009-12-30 05:02:06 +0000537 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelf6e6aa02009-07-29 00:34:02 +0000538 std::string Name = Lex.getStrVal();
Chris Lattner7e4b4aa2009-12-30 05:02:06 +0000539 Lex.Lex();
Devang Patelf6e6aa02009-07-29 00:34:02 +0000540
Chris Lattnerbe7a0252009-12-29 22:35:39 +0000541 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnerf39c84f2009-12-30 04:56:59 +0000542 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerbe7a0252009-12-29 22:35:39 +0000543 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelf6e6aa02009-07-29 00:34:02 +0000544 return true;
545
Devang Patelc5bb7252010-01-05 20:41:31 +0000546 SmallVector<MDNode *, 8> Elts;
Devang Patelf6e6aa02009-07-29 00:34:02 +0000547 do {
Devang Patel148981c2010-01-05 21:47:32 +0000548 // Null is a special case since it is typeless.
549 if (EatIfPresent(lltok::kw_null)) {
550 Elts.push_back(0);
551 continue;
552 }
553
Chris Lattnerf39c84f2009-12-30 04:56:59 +0000554 if (ParseToken(lltok::exclaim, "Expected '!' here"))
Chris Lattner99c6ed12009-12-29 22:01:50 +0000555 return true;
Chris Lattnerb3d6fad2009-12-29 21:53:55 +0000556
Chris Lattnerb3d6fad2009-12-29 21:53:55 +0000557 MDNode *N = 0;
Chris Lattner84a86d22009-12-30 04:15:23 +0000558 if (ParseMDNodeID(N)) return true;
Devang Patelf6e6aa02009-07-29 00:34:02 +0000559 Elts.push_back(N);
560 } while (EatIfPresent(lltok::comma));
561
562 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
563 return true;
564
Owen Anderson35b47072009-08-13 21:58:54 +0000565 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
Devang Patelf6e6aa02009-07-29 00:34:02 +0000566 return false;
567}
568
Devang Patela8261c62009-07-01 19:21:12 +0000569/// ParseStandaloneMetadata:
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000570/// !42 = !{...}
Devang Patela8261c62009-07-01 19:21:12 +0000571bool LLParser::ParseStandaloneMetadata() {
Chris Lattnerf39c84f2009-12-30 04:56:59 +0000572 assert(Lex.getKind() == lltok::exclaim);
Devang Patela8261c62009-07-01 19:21:12 +0000573 Lex.Lex();
574 unsigned MetadataID = 0;
Devang Patela8261c62009-07-01 19:21:12 +0000575
576 LocTy TyLoc;
Owen Anderson35b47072009-08-13 21:58:54 +0000577 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel54199ef2009-07-23 01:07:34 +0000578 SmallVector<Value *, 16> Elts;
Chris Lattner73fd84e2009-12-29 22:40:21 +0000579 if (ParseUInt32(MetadataID) ||
580 ParseToken(lltok::equal, "expected '=' here") ||
581 ParseType(Ty, TyLoc) ||
Chris Lattnerf39c84f2009-12-30 04:56:59 +0000582 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner73fd84e2009-12-29 22:40:21 +0000583 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandezc4261242010-01-10 07:14:18 +0000584 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner73fd84e2009-12-29 22:40:21 +0000585 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel54199ef2009-07-23 01:07:34 +0000586 return true;
587
Owen Anderson20be0582009-07-31 21:35:40 +0000588 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Chris Lattnercc286d22009-12-30 04:51:58 +0000589
590 // See if this was forward referenced, if so, handle it.
Chris Lattner9e9fa652009-12-29 21:43:58 +0000591 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patelef716812009-07-08 19:23:54 +0000592 FI = ForwardRefMDNodes.find(MetadataID);
593 if (FI != ForwardRefMDNodes.end()) {
Chris Lattner9e9fa652009-12-29 21:43:58 +0000594 FI->second.first->replaceAllUsesWith(Init);
Devang Patelef716812009-07-08 19:23:54 +0000595 ForwardRefMDNodes.erase(FI);
Chris Lattnercc286d22009-12-30 04:51:58 +0000596
597 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
598 } else {
599 if (MetadataID >= NumberedMetadata.size())
600 NumberedMetadata.resize(MetadataID+1);
601
602 if (NumberedMetadata[MetadataID] != 0)
603 return TokError("Metadata id is already used");
604 NumberedMetadata[MetadataID] = Init;
Devang Patelef716812009-07-08 19:23:54 +0000605 }
606
Devang Patela8261c62009-07-01 19:21:12 +0000607 return false;
608}
609
Chris Lattner103ff152009-01-02 07:01:27 +0000610/// ParseAlias:
611/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
612/// Aliasee
Chris Lattner5a871bb2009-04-25 21:26:00 +0000613/// ::= TypeAndValue
614/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohman106b2ae2009-07-27 21:53:46 +0000615/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattner103ff152009-01-02 07:01:27 +0000616///
617/// Everything through visibility has already been parsed.
618///
619bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
620 unsigned Visibility) {
621 assert(Lex.getKind() == lltok::kw_alias);
622 Lex.Lex();
623 unsigned Linkage;
624 LocTy LinkageLoc = Lex.getLoc();
625 if (ParseOptionalLinkage(Linkage))
626 return true;
627
628 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands19d161f2009-03-07 15:45:40 +0000629 Linkage != GlobalValue::WeakAnyLinkage &&
630 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000631 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling41a07852009-07-20 01:03:30 +0000632 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendlingf8b61372010-06-29 21:24:00 +0000633 Linkage != GlobalValue::LinkerPrivateLinkage &&
634 Linkage != GlobalValue::LinkerWeakLinkage)
Chris Lattner103ff152009-01-02 07:01:27 +0000635 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000636
Chris Lattner103ff152009-01-02 07:01:27 +0000637 Constant *Aliasee;
638 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner5a871bb2009-04-25 21:26:00 +0000639 if (Lex.getKind() != lltok::kw_bitcast &&
640 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattner103ff152009-01-02 07:01:27 +0000641 if (ParseGlobalTypeAndValue(Aliasee)) return true;
642 } else {
643 // The bitcast dest type is not present, it is implied by the dest type.
644 ValID ID;
645 if (ParseValID(ID)) return true;
646 if (ID.Kind != ValID::t_Constant)
647 return Error(AliaseeLoc, "invalid aliasee");
648 Aliasee = ID.ConstantVal;
649 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000650
Duncan Sands10343d92010-02-16 11:11:14 +0000651 if (!Aliasee->getType()->isPointerTy())
Chris Lattner103ff152009-01-02 07:01:27 +0000652 return Error(AliaseeLoc, "alias must have pointer type");
653
654 // Okay, create the alias but do not insert it into the module yet.
655 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
656 (GlobalValue::LinkageTypes)Linkage, Name,
657 Aliasee);
658 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000659
Chris Lattner103ff152009-01-02 07:01:27 +0000660 // See if this value already exists in the symbol table. If so, it is either
661 // a redefinition or a definition of a forward reference.
Chris Lattner85ee7092009-10-25 23:22:50 +0000662 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattner103ff152009-01-02 07:01:27 +0000663 // See if this was a redefinition. If so, there is no entry in
664 // ForwardRefVals.
665 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
666 I = ForwardRefVals.find(Name);
667 if (I == ForwardRefVals.end())
668 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
669
670 // Otherwise, this was a definition of forward ref. Verify that types
671 // agree.
672 if (Val->getType() != GA->getType())
673 return Error(NameLoc,
674 "forward reference and definition of alias have different types");
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000675
Chris Lattner103ff152009-01-02 07:01:27 +0000676 // If they agree, just RAUW the old value with the alias and remove the
677 // forward ref info.
678 Val->replaceAllUsesWith(GA);
679 Val->eraseFromParent();
680 ForwardRefVals.erase(I);
681 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000682
Chris Lattner103ff152009-01-02 07:01:27 +0000683 // Insert into the module, we know its name won't collide now.
684 M->getAliasList().push_back(GA);
685 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000686
Chris Lattner103ff152009-01-02 07:01:27 +0000687 return false;
688}
689
690/// ParseGlobal
691/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
692/// OptionalAddrSpace GlobalType Type Const
693/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
694/// OptionalAddrSpace GlobalType Type Const
695///
696/// Everything through visibility has been parsed already.
697///
698bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
699 unsigned Linkage, bool HasLinkage,
700 unsigned Visibility) {
701 unsigned AddrSpace;
702 bool ThreadLocal, IsConstant;
703 LocTy TyLoc;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000704
Owen Anderson35b47072009-08-13 21:58:54 +0000705 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattner103ff152009-01-02 07:01:27 +0000706 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
707 ParseOptionalAddrSpace(AddrSpace) ||
708 ParseGlobalType(IsConstant) ||
709 ParseType(Ty, TyLoc))
710 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000711
Chris Lattner103ff152009-01-02 07:01:27 +0000712 // If the linkage is specified and is external, then no initializer is
713 // present.
714 Constant *Init = 0;
715 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands565f65d2009-03-11 08:08:06 +0000716 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattner103ff152009-01-02 07:01:27 +0000717 Linkage != GlobalValue::ExternalLinkage)) {
718 if (ParseGlobalValue(Ty, Init))
719 return true;
720 }
721
Duncan Sands10343d92010-02-16 11:11:14 +0000722 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner516512d2009-02-08 20:00:15 +0000723 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000724
Chris Lattner103ff152009-01-02 07:01:27 +0000725 GlobalVariable *GV = 0;
726
727 // See if the global was forward referenced, if so, use the global.
Chris Lattnerdb6a6a12009-02-02 07:24:28 +0000728 if (!Name.empty()) {
Chris Lattner85ee7092009-10-25 23:22:50 +0000729 if (GlobalValue *GVal = M->getNamedValue(Name)) {
730 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
731 return Error(NameLoc, "redefinition of global '@" + Name + "'");
732 GV = cast<GlobalVariable>(GVal);
733 }
Chris Lattner103ff152009-01-02 07:01:27 +0000734 } else {
735 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
736 I = ForwardRefValIDs.find(NumberedVals.size());
737 if (I != ForwardRefValIDs.end()) {
738 GV = cast<GlobalVariable>(I->second.first);
739 ForwardRefValIDs.erase(I);
740 }
741 }
742
743 if (GV == 0) {
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000744 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone17fc1d2009-07-08 19:03:57 +0000745 Name, 0, false, AddrSpace);
Chris Lattner103ff152009-01-02 07:01:27 +0000746 } else {
747 if (GV->getType()->getElementType() != Ty)
748 return Error(TyLoc,
749 "forward reference and definition of global have different types");
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000750
Chris Lattner103ff152009-01-02 07:01:27 +0000751 // Move the forward-reference to the correct spot in the module.
752 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
753 }
754
755 if (Name.empty())
756 NumberedVals.push_back(GV);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000757
Chris Lattner103ff152009-01-02 07:01:27 +0000758 // Set the parsed properties on the global.
759 if (Init)
760 GV->setInitializer(Init);
761 GV->setConstant(IsConstant);
762 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
763 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
764 GV->setThreadLocal(ThreadLocal);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000765
Chris Lattner103ff152009-01-02 07:01:27 +0000766 // Parse attributes on the global.
767 while (Lex.getKind() == lltok::comma) {
768 Lex.Lex();
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000769
Chris Lattner103ff152009-01-02 07:01:27 +0000770 if (Lex.getKind() == lltok::kw_section) {
771 Lex.Lex();
772 GV->setSection(Lex.getStrVal());
773 if (ParseToken(lltok::StringConstant, "expected global section string"))
774 return true;
775 } else if (Lex.getKind() == lltok::kw_align) {
776 unsigned Alignment;
777 if (ParseOptionalAlignment(Alignment)) return true;
778 GV->setAlignment(Alignment);
779 } else {
780 TokError("unknown global variable property!");
781 }
782 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000783
Chris Lattner103ff152009-01-02 07:01:27 +0000784 return false;
785}
786
787
788//===----------------------------------------------------------------------===//
789// GlobalValue Reference/Resolution Routines.
790//===----------------------------------------------------------------------===//
791
792/// GetGlobalVal - Get a value with the specified name or ID, creating a
793/// forward reference record if needed. This can return null if the value
794/// exists but does not have the right type.
795GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
796 LocTy Loc) {
797 const PointerType *PTy = dyn_cast<PointerType>(Ty);
798 if (PTy == 0) {
799 Error(Loc, "global variable reference must have pointer type");
800 return 0;
801 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000802
Chris Lattner103ff152009-01-02 07:01:27 +0000803 // Look this name up in the normal function symbol table.
804 GlobalValue *Val =
805 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000806
Chris Lattner103ff152009-01-02 07:01:27 +0000807 // If this is a forward reference for the value, see if we already created a
808 // forward ref record.
809 if (Val == 0) {
810 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
811 I = ForwardRefVals.find(Name);
812 if (I != ForwardRefVals.end())
813 Val = I->second.first;
814 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000815
Chris Lattner103ff152009-01-02 07:01:27 +0000816 // If we have the value in the symbol table or fwd-ref table, return it.
817 if (Val) {
818 if (Val->getType() == Ty) return Val;
819 Error(Loc, "'@" + Name + "' defined with type '" +
820 Val->getType()->getDescription() + "'");
821 return 0;
822 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000823
Chris Lattner103ff152009-01-02 07:01:27 +0000824 // Otherwise, create a new forward reference for this value and remember it.
825 GlobalValue *FwdVal;
Chris Lattner05c495e2009-01-08 19:05:36 +0000826 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
827 // Function types can return opaque but functions can't.
Duncan Sands1e6932c2010-02-16 14:50:09 +0000828 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner05c495e2009-01-08 19:05:36 +0000829 Error(Loc, "function may not return opaque type");
830 return 0;
831 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000832
Duncan Sands565f65d2009-03-11 08:08:06 +0000833 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner05c495e2009-01-08 19:05:36 +0000834 } else {
Owen Andersone17fc1d2009-07-08 19:03:57 +0000835 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
836 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner05c495e2009-01-08 19:05:36 +0000837 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000838
Chris Lattner103ff152009-01-02 07:01:27 +0000839 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
840 return FwdVal;
841}
842
843GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
844 const PointerType *PTy = dyn_cast<PointerType>(Ty);
845 if (PTy == 0) {
846 Error(Loc, "global variable reference must have pointer type");
847 return 0;
848 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000849
Chris Lattner103ff152009-01-02 07:01:27 +0000850 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000851
Chris Lattner103ff152009-01-02 07:01:27 +0000852 // If this is a forward reference for the value, see if we already created a
853 // forward ref record.
854 if (Val == 0) {
855 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
856 I = ForwardRefValIDs.find(ID);
857 if (I != ForwardRefValIDs.end())
858 Val = I->second.first;
859 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000860
Chris Lattner103ff152009-01-02 07:01:27 +0000861 // If we have the value in the symbol table or fwd-ref table, return it.
862 if (Val) {
863 if (Val->getType() == Ty) return Val;
864 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
865 Val->getType()->getDescription() + "'");
866 return 0;
867 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000868
Chris Lattner103ff152009-01-02 07:01:27 +0000869 // Otherwise, create a new forward reference for this value and remember it.
870 GlobalValue *FwdVal;
Chris Lattnerff2429a2009-01-05 18:27:50 +0000871 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
872 // Function types can return opaque but functions can't.
Duncan Sands1e6932c2010-02-16 14:50:09 +0000873 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattnerf712b462009-01-05 18:56:52 +0000874 Error(Loc, "function may not return opaque type");
Chris Lattnerff2429a2009-01-05 18:27:50 +0000875 return 0;
876 }
Duncan Sands565f65d2009-03-11 08:08:06 +0000877 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerff2429a2009-01-05 18:27:50 +0000878 } else {
Owen Andersone17fc1d2009-07-08 19:03:57 +0000879 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
880 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattnerff2429a2009-01-05 18:27:50 +0000881 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000882
Chris Lattner103ff152009-01-02 07:01:27 +0000883 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
884 return FwdVal;
885}
886
887
888//===----------------------------------------------------------------------===//
889// Helper Routines.
890//===----------------------------------------------------------------------===//
891
892/// ParseToken - If the current token has the specified kind, eat it and return
893/// success. Otherwise, emit the specified error and return failure.
894bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
895 if (Lex.getKind() != T)
896 return TokError(ErrMsg);
897 Lex.Lex();
898 return false;
899}
900
Chris Lattner6226fd22009-01-02 08:05:26 +0000901/// ParseStringConstant
902/// ::= StringConstant
903bool LLParser::ParseStringConstant(std::string &Result) {
904 if (Lex.getKind() != lltok::StringConstant)
905 return TokError("expected string constant");
906 Result = Lex.getStrVal();
907 Lex.Lex();
908 return false;
909}
910
911/// ParseUInt32
912/// ::= uint32
913bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattner103ff152009-01-02 07:01:27 +0000914 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
915 return TokError("expected integer");
916 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
917 if (Val64 != unsigned(Val64))
918 return TokError("expected 32-bit integer (too large)");
919 Val = Val64;
920 Lex.Lex();
921 return false;
922}
923
924
925/// ParseOptionalAddrSpace
926/// := /*empty*/
927/// := 'addrspace' '(' uint32 ')'
928bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
929 AddrSpace = 0;
Chris Lattner6226fd22009-01-02 08:05:26 +0000930 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattner103ff152009-01-02 07:01:27 +0000931 return false;
Chris Lattner103ff152009-01-02 07:01:27 +0000932 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner6226fd22009-01-02 08:05:26 +0000933 ParseUInt32(AddrSpace) ||
Chris Lattner103ff152009-01-02 07:01:27 +0000934 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000935}
Chris Lattner103ff152009-01-02 07:01:27 +0000936
937/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
938/// indicates what kind of attribute list this is: 0: function arg, 1: result,
939/// 2: function attr.
Chris Lattnerf9922e62009-03-25 06:36:36 +0000940/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattner103ff152009-01-02 07:01:27 +0000941bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
942 Attrs = Attribute::None;
943 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000944
Chris Lattner103ff152009-01-02 07:01:27 +0000945 while (1) {
946 switch (Lex.getKind()) {
947 case lltok::kw_sext:
948 case lltok::kw_zext:
Chris Lattnerf9922e62009-03-25 06:36:36 +0000949 // Treat these as signext/zeroext if they occur in the argument list after
950 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
951 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
952 // expr.
Chris Lattner103ff152009-01-02 07:01:27 +0000953 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerf9922e62009-03-25 06:36:36 +0000954 if (AttrKind == 3) {
Chris Lattner103ff152009-01-02 07:01:27 +0000955 if (Lex.getKind() == lltok::kw_sext)
956 Attrs |= Attribute::SExt;
957 else
958 Attrs |= Attribute::ZExt;
959 break;
960 }
961 // FALL THROUGH.
962 default: // End of attributes.
963 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
964 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000965
Chris Lattnerf9922e62009-03-25 06:36:36 +0000966 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattner103ff152009-01-02 07:01:27 +0000967 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000968
Chris Lattner103ff152009-01-02 07:01:27 +0000969 return false;
Devang Patelc386c842009-06-05 21:57:13 +0000970 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
971 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
972 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
973 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
974 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
975 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
976 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
977 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattner103ff152009-01-02 07:01:27 +0000978
Devang Patelc386c842009-06-05 21:57:13 +0000979 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
980 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
981 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
982 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
983 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen77180732010-02-06 01:16:28 +0000984 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patelc386c842009-06-05 21:57:13 +0000985 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
986 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
987 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
988 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
989 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
990 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovedd7d112009-07-17 18:07:26 +0000991 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000992
Charles Davisfaa8f752010-02-12 00:31:15 +0000993 case lltok::kw_alignstack: {
994 unsigned Alignment;
995 if (ParseOptionalStackAlignment(Alignment))
996 return true;
997 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
998 continue;
999 }
1000
Chris Lattner103ff152009-01-02 07:01:27 +00001001 case lltok::kw_align: {
1002 unsigned Alignment;
1003 if (ParseOptionalAlignment(Alignment))
1004 return true;
1005 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
1006 continue;
1007 }
Charles Davisfaa8f752010-02-12 00:31:15 +00001008
Chris Lattner103ff152009-01-02 07:01:27 +00001009 }
1010 Lex.Lex();
1011 }
1012}
1013
1014/// ParseOptionalLinkage
1015/// ::= /*empty*/
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001016/// ::= 'private'
Bill Wendling41a07852009-07-20 01:03:30 +00001017/// ::= 'linker_private'
Bill Wendlingf8b61372010-06-29 21:24:00 +00001018/// ::= 'linker_weak'
Chris Lattner103ff152009-01-02 07:01:27 +00001019/// ::= 'internal'
1020/// ::= 'weak'
Duncan Sands19d161f2009-03-07 15:45:40 +00001021/// ::= 'weak_odr'
Chris Lattner103ff152009-01-02 07:01:27 +00001022/// ::= 'linkonce'
Duncan Sands19d161f2009-03-07 15:45:40 +00001023/// ::= 'linkonce_odr'
Chris Lattner103ff152009-01-02 07:01:27 +00001024/// ::= 'appending'
1025/// ::= 'dllexport'
1026/// ::= 'common'
1027/// ::= 'dllimport'
1028/// ::= 'extern_weak'
1029/// ::= 'external'
1030bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1031 HasLinkage = false;
1032 switch (Lex.getKind()) {
Bill Wendling41a07852009-07-20 01:03:30 +00001033 default: Res=GlobalValue::ExternalLinkage; return false;
1034 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1035 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendlingf8b61372010-06-29 21:24:00 +00001036 case lltok::kw_linker_weak: Res = GlobalValue::LinkerWeakLinkage; break;
Bill Wendling41a07852009-07-20 01:03:30 +00001037 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1038 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1039 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1040 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1041 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner68433442009-04-13 05:44:34 +00001042 case lltok::kw_available_externally:
1043 Res = GlobalValue::AvailableExternallyLinkage;
1044 break;
Bill Wendling41a07852009-07-20 01:03:30 +00001045 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1046 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1047 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1048 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1049 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1050 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattner103ff152009-01-02 07:01:27 +00001051 }
1052 Lex.Lex();
1053 HasLinkage = true;
1054 return false;
1055}
1056
1057/// ParseOptionalVisibility
1058/// ::= /*empty*/
1059/// ::= 'default'
1060/// ::= 'hidden'
1061/// ::= 'protected'
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001062///
Chris Lattner103ff152009-01-02 07:01:27 +00001063bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1064 switch (Lex.getKind()) {
1065 default: Res = GlobalValue::DefaultVisibility; return false;
1066 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1067 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1068 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1069 }
1070 Lex.Lex();
1071 return false;
1072}
1073
1074/// ParseOptionalCallingConv
1075/// ::= /*empty*/
1076/// ::= 'ccc'
1077/// ::= 'fastcc'
1078/// ::= 'coldcc'
1079/// ::= 'x86_stdcallcc'
1080/// ::= 'x86_fastcallcc'
Anton Korobeynikove454f182010-05-16 09:08:45 +00001081/// ::= 'x86_thiscallcc'
Anton Korobeynikov1395c2c2009-06-16 18:50:49 +00001082/// ::= 'arm_apcscc'
1083/// ::= 'arm_aapcscc'
1084/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov56998002009-12-07 02:27:35 +00001085/// ::= 'msp430_intrcc'
Chris Lattner103ff152009-01-02 07:01:27 +00001086/// ::= 'cc' UINT
Anton Korobeynikov1395c2c2009-06-16 18:50:49 +00001087///
Sandeep Patel5838baa2009-09-02 08:44:58 +00001088bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattner103ff152009-01-02 07:01:27 +00001089 switch (Lex.getKind()) {
1090 default: CC = CallingConv::C; return false;
1091 case lltok::kw_ccc: CC = CallingConv::C; break;
1092 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1093 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1094 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1095 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikove454f182010-05-16 09:08:45 +00001096 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov1395c2c2009-06-16 18:50:49 +00001097 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1098 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1099 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov56998002009-12-07 02:27:35 +00001100 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Sandeep Patel5838baa2009-09-02 08:44:58 +00001101 case lltok::kw_cc: {
1102 unsigned ArbitraryCC;
1103 Lex.Lex();
1104 if (ParseUInt32(ArbitraryCC)) {
1105 return true;
1106 } else
1107 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1108 return false;
1109 }
1110 break;
Chris Lattner103ff152009-01-02 07:01:27 +00001111 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001112
Chris Lattner103ff152009-01-02 07:01:27 +00001113 Lex.Lex();
1114 return false;
1115}
1116
Chris Lattner275b6b52009-12-30 05:31:19 +00001117/// ParseInstructionMetadata
Chris Lattner87c9fb52009-12-29 21:25:40 +00001118/// ::= !dbg !42 (',' !dbg !57)*
Chris Lattner93fbde12010-04-01 04:51:13 +00001119bool LLParser::ParseInstructionMetadata(Instruction *Inst) {
Chris Lattner275b6b52009-12-30 05:31:19 +00001120 do {
1121 if (Lex.getKind() != lltok::MetadataVar)
1122 return TokError("expected metadata after comma");
Devang Patel17c60df2009-09-29 00:01:14 +00001123
Chris Lattner87c9fb52009-12-29 21:25:40 +00001124 std::string Name = Lex.getStrVal();
1125 Lex.Lex();
Chris Lattnerc6a1c722009-10-19 05:31:10 +00001126
Chris Lattnerb3d6fad2009-12-29 21:53:55 +00001127 MDNode *Node;
Chris Lattner8919f2e2010-04-01 05:14:45 +00001128 unsigned NodeID;
1129 SMLoc Loc = Lex.getLoc();
Chris Lattnerf39c84f2009-12-30 04:56:59 +00001130 if (ParseToken(lltok::exclaim, "expected '!' here") ||
Chris Lattner8919f2e2010-04-01 05:14:45 +00001131 ParseMDNodeID(Node, NodeID))
Chris Lattnerf39c84f2009-12-30 04:56:59 +00001132 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001133
Chris Lattner87c9fb52009-12-29 21:25:40 +00001134 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner8919f2e2010-04-01 05:14:45 +00001135 if (Node) {
1136 // If we got the node, add it to the instruction.
1137 Inst->setMetadata(MDK, Node);
1138 } else {
1139 MDRef R = { Loc, MDK, NodeID };
1140 // Otherwise, remember that this should be resolved later.
1141 ForwardRefInstMetadata[Inst].push_back(R);
1142 }
Chris Lattner87c9fb52009-12-29 21:25:40 +00001143
1144 // If this is the end of the list, we're done.
Chris Lattner275b6b52009-12-30 05:31:19 +00001145 } while (EatIfPresent(lltok::comma));
1146 return false;
Devang Patel91c79232009-09-17 23:04:48 +00001147}
1148
Chris Lattner103ff152009-01-02 07:01:27 +00001149/// ParseOptionalAlignment
1150/// ::= /* empty */
1151/// ::= 'align' 4
1152bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1153 Alignment = 0;
Chris Lattner6226fd22009-01-02 08:05:26 +00001154 if (!EatIfPresent(lltok::kw_align))
1155 return false;
Chris Lattner27878a22009-01-05 07:46:05 +00001156 LocTy AlignLoc = Lex.getLoc();
1157 if (ParseUInt32(Alignment)) return true;
1158 if (!isPowerOf2_32(Alignment))
1159 return Error(AlignLoc, "alignment is not a power of two");
1160 return false;
Chris Lattner103ff152009-01-02 07:01:27 +00001161}
1162
Chris Lattner4db8a012009-12-30 05:44:30 +00001163/// ParseOptionalCommaAlign
1164/// ::=
1165/// ::= ',' align 4
1166///
1167/// This returns with AteExtraComma set to true if it ate an excess comma at the
1168/// end.
1169bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1170 bool &AteExtraComma) {
1171 AteExtraComma = false;
1172 while (EatIfPresent(lltok::comma)) {
1173 // Metadata at the end is an early exit.
Chris Lattner7e4b4aa2009-12-30 05:02:06 +00001174 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattner4db8a012009-12-30 05:44:30 +00001175 AteExtraComma = true;
1176 return false;
1177 }
1178
Chris Lattneref67a042010-04-23 00:50:50 +00001179 if (Lex.getKind() != lltok::kw_align)
1180 return Error(Lex.getLoc(), "expected metadata or 'align'");
1181
1182 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner4db8a012009-12-30 05:44:30 +00001183 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001184
Devang Patel91c79232009-09-17 23:04:48 +00001185 return false;
Chris Lattner103ff152009-01-02 07:01:27 +00001186}
1187
Charles Davisfaa8f752010-02-12 00:31:15 +00001188/// ParseOptionalStackAlignment
1189/// ::= /* empty */
1190/// ::= 'alignstack' '(' 4 ')'
1191bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1192 Alignment = 0;
1193 if (!EatIfPresent(lltok::kw_alignstack))
1194 return false;
1195 LocTy ParenLoc = Lex.getLoc();
1196 if (!EatIfPresent(lltok::lparen))
1197 return Error(ParenLoc, "expected '('");
1198 LocTy AlignLoc = Lex.getLoc();
1199 if (ParseUInt32(Alignment)) return true;
1200 ParenLoc = Lex.getLoc();
1201 if (!EatIfPresent(lltok::rparen))
1202 return Error(ParenLoc, "expected ')'");
1203 if (!isPowerOf2_32(Alignment))
1204 return Error(AlignLoc, "stack alignment is not a power of two");
1205 return false;
1206}
Devang Patel91c79232009-09-17 23:04:48 +00001207
Chris Lattner7c3b4082009-12-30 05:14:00 +00001208/// ParseIndexList - This parses the index list for an insert/extractvalue
1209/// instruction. This sets AteExtraComma in the case where we eat an extra
1210/// comma at the end of the line and find that it is followed by metadata.
1211/// Clients that don't allow metadata can call the version of this function that
1212/// only takes one argument.
1213///
Chris Lattner103ff152009-01-02 07:01:27 +00001214/// ParseIndexList
1215/// ::= (',' uint32)+
Chris Lattner7c3b4082009-12-30 05:14:00 +00001216///
1217bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1218 bool &AteExtraComma) {
1219 AteExtraComma = false;
1220
Chris Lattner103ff152009-01-02 07:01:27 +00001221 if (Lex.getKind() != lltok::comma)
1222 return TokError("expected ',' as start of index list");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001223
Chris Lattner6226fd22009-01-02 08:05:26 +00001224 while (EatIfPresent(lltok::comma)) {
Chris Lattner7c3b4082009-12-30 05:14:00 +00001225 if (Lex.getKind() == lltok::MetadataVar) {
1226 AteExtraComma = true;
1227 return false;
1228 }
Chris Lattner103ff152009-01-02 07:01:27 +00001229 unsigned Idx;
Chris Lattner6226fd22009-01-02 08:05:26 +00001230 if (ParseUInt32(Idx)) return true;
Chris Lattner103ff152009-01-02 07:01:27 +00001231 Indices.push_back(Idx);
1232 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001233
Chris Lattner103ff152009-01-02 07:01:27 +00001234 return false;
1235}
1236
1237//===----------------------------------------------------------------------===//
1238// Type Parsing.
1239//===----------------------------------------------------------------------===//
1240
1241/// ParseType - Parse and resolve a full type.
Chris Lattnerc3a8e192009-03-09 04:49:14 +00001242bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1243 LocTy TypeLoc = Lex.getLoc();
Chris Lattner103ff152009-01-02 07:01:27 +00001244 if (ParseTypeRec(Result)) return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001245
Chris Lattner103ff152009-01-02 07:01:27 +00001246 // Verify no unresolved uprefs.
1247 if (!UpRefs.empty())
1248 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001249
Chris Lattner82cdc062009-10-05 05:54:46 +00001250 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnerc3a8e192009-03-09 04:49:14 +00001251 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001252
Chris Lattner103ff152009-01-02 07:01:27 +00001253 return false;
1254}
1255
1256/// HandleUpRefs - Every time we finish a new layer of types, this function is
1257/// called. It loops through the UpRefs vector, which is a list of the
1258/// currently active types. For each type, if the up-reference is contained in
1259/// the newly completed type, we decrement the level count. When the level
1260/// count reaches zero, the up-referenced type is the type that is passed in:
1261/// thus we can complete the cycle.
1262///
1263PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1264 // If Ty isn't abstract, or if there are no up-references in it, then there is
1265 // nothing to resolve here.
1266 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001267
Chris Lattner103ff152009-01-02 07:01:27 +00001268 PATypeHolder Ty(ty);
1269#if 0
David Greenea3267132009-12-23 23:38:28 +00001270 dbgs() << "Type '" << Ty->getDescription()
Chris Lattner103ff152009-01-02 07:01:27 +00001271 << "' newly formed. Resolving upreferences.\n"
1272 << UpRefs.size() << " upreferences active!\n";
1273#endif
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001274
Chris Lattner103ff152009-01-02 07:01:27 +00001275 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1276 // to zero), we resolve them all together before we resolve them to Ty. At
1277 // the end of the loop, if there is anything to resolve to Ty, it will be in
1278 // this variable.
1279 OpaqueType *TypeToResolve = 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001280
Chris Lattner103ff152009-01-02 07:01:27 +00001281 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1282 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1283 bool ContainsType =
1284 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1285 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001286
Chris Lattner103ff152009-01-02 07:01:27 +00001287#if 0
David Greenea3267132009-12-23 23:38:28 +00001288 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattner103ff152009-01-02 07:01:27 +00001289 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1290 << (ContainsType ? "true" : "false")
1291 << " level=" << UpRefs[i].NestingLevel << "\n";
1292#endif
1293 if (!ContainsType)
1294 continue;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001295
Chris Lattner103ff152009-01-02 07:01:27 +00001296 // Decrement level of upreference
1297 unsigned Level = --UpRefs[i].NestingLevel;
1298 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001299
Chris Lattner103ff152009-01-02 07:01:27 +00001300 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1301 if (Level != 0)
1302 continue;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001303
Chris Lattner103ff152009-01-02 07:01:27 +00001304#if 0
David Greenea3267132009-12-23 23:38:28 +00001305 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattner103ff152009-01-02 07:01:27 +00001306#endif
1307 if (!TypeToResolve)
1308 TypeToResolve = UpRefs[i].UpRefTy;
1309 else
1310 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1311 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1312 --i; // Do not skip the next element.
1313 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001314
Chris Lattner103ff152009-01-02 07:01:27 +00001315 if (TypeToResolve)
1316 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001317
Chris Lattner103ff152009-01-02 07:01:27 +00001318 return Ty;
1319}
1320
1321
1322/// ParseTypeRec - The recursive function used to process the internal
1323/// implementation details of types.
1324bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1325 switch (Lex.getKind()) {
1326 default:
1327 return TokError("expected type");
1328 case lltok::Type:
1329 // TypeRec ::= 'float' | 'void' (etc)
1330 Result = Lex.getTyVal();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001331 Lex.Lex();
Chris Lattner103ff152009-01-02 07:01:27 +00001332 break;
1333 case lltok::kw_opaque:
1334 // TypeRec ::= 'opaque'
Owen Anderson02f7bd52009-08-13 23:27:32 +00001335 Result = OpaqueType::get(Context);
Chris Lattner103ff152009-01-02 07:01:27 +00001336 Lex.Lex();
1337 break;
1338 case lltok::lbrace:
1339 // TypeRec ::= '{' ... '}'
1340 if (ParseStructType(Result, false))
1341 return true;
1342 break;
Chris Lattnerd5d51722010-02-12 20:49:41 +00001343 case lltok::kw_union:
1344 // TypeRec ::= 'union' '{' ... '}'
1345 if (ParseUnionType(Result))
1346 return true;
1347 break;
Chris Lattner103ff152009-01-02 07:01:27 +00001348 case lltok::lsquare:
1349 // TypeRec ::= '[' ... ']'
1350 Lex.Lex(); // eat the lsquare.
1351 if (ParseArrayVectorType(Result, false))
1352 return true;
1353 break;
1354 case lltok::less: // Either vector or packed struct.
1355 // TypeRec ::= '<' ... '>'
Chris Lattner6226fd22009-01-02 08:05:26 +00001356 Lex.Lex();
1357 if (Lex.getKind() == lltok::lbrace) {
1358 if (ParseStructType(Result, true) ||
1359 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattner103ff152009-01-02 07:01:27 +00001360 return true;
Chris Lattner103ff152009-01-02 07:01:27 +00001361 } else if (ParseArrayVectorType(Result, true))
1362 return true;
1363 break;
1364 case lltok::LocalVar:
1365 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1366 // TypeRec ::= %foo
1367 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1368 Result = T;
1369 } else {
Owen Anderson02f7bd52009-08-13 23:27:32 +00001370 Result = OpaqueType::get(Context);
Chris Lattner103ff152009-01-02 07:01:27 +00001371 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1372 std::make_pair(Result,
1373 Lex.getLoc())));
1374 M->addTypeName(Lex.getStrVal(), Result.get());
1375 }
1376 Lex.Lex();
1377 break;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001378
Chris Lattner103ff152009-01-02 07:01:27 +00001379 case lltok::LocalVarID:
1380 // TypeRec ::= %4
1381 if (Lex.getUIntVal() < NumberedTypes.size())
1382 Result = NumberedTypes[Lex.getUIntVal()];
1383 else {
1384 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1385 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1386 if (I != ForwardRefTypeIDs.end())
1387 Result = I->second.first;
1388 else {
Owen Anderson02f7bd52009-08-13 23:27:32 +00001389 Result = OpaqueType::get(Context);
Chris Lattner103ff152009-01-02 07:01:27 +00001390 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1391 std::make_pair(Result,
1392 Lex.getLoc())));
1393 }
1394 }
1395 Lex.Lex();
1396 break;
1397 case lltok::backslash: {
1398 // TypeRec ::= '\' 4
Chris Lattner103ff152009-01-02 07:01:27 +00001399 Lex.Lex();
Chris Lattner6226fd22009-01-02 08:05:26 +00001400 unsigned Val;
1401 if (ParseUInt32(Val)) return true;
Owen Anderson02f7bd52009-08-13 23:27:32 +00001402 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattner103ff152009-01-02 07:01:27 +00001403 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1404 Result = OT;
1405 break;
1406 }
1407 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001408
1409 // Parse the type suffixes.
Chris Lattner103ff152009-01-02 07:01:27 +00001410 while (1) {
1411 switch (Lex.getKind()) {
1412 // End of type.
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001413 default: return false;
Chris Lattner103ff152009-01-02 07:01:27 +00001414
1415 // TypeRec ::= TypeRec '*'
1416 case lltok::star:
Chris Lattner82cdc062009-10-05 05:54:46 +00001417 if (Result.get()->isLabelTy())
Chris Lattner103ff152009-01-02 07:01:27 +00001418 return TokError("basic block pointers are invalid");
Chris Lattner82cdc062009-10-05 05:54:46 +00001419 if (Result.get()->isVoidTy())
Dan Gohmanc7b2a882009-02-09 17:41:21 +00001420 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewycky85387e42009-06-07 07:26:46 +00001421 if (!PointerType::isValidElementType(Result.get()))
1422 return TokError("pointer to this type is invalid");
Owen Anderson6b6e2d92009-07-29 22:17:13 +00001423 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattner103ff152009-01-02 07:01:27 +00001424 Lex.Lex();
1425 break;
1426
1427 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1428 case lltok::kw_addrspace: {
Chris Lattner82cdc062009-10-05 05:54:46 +00001429 if (Result.get()->isLabelTy())
Chris Lattner103ff152009-01-02 07:01:27 +00001430 return TokError("basic block pointers are invalid");
Chris Lattner82cdc062009-10-05 05:54:46 +00001431 if (Result.get()->isVoidTy())
Dan Gohmanc7b2a882009-02-09 17:41:21 +00001432 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewycky85387e42009-06-07 07:26:46 +00001433 if (!PointerType::isValidElementType(Result.get()))
1434 return TokError("pointer to this type is invalid");
Chris Lattner103ff152009-01-02 07:01:27 +00001435 unsigned AddrSpace;
1436 if (ParseOptionalAddrSpace(AddrSpace) ||
1437 ParseToken(lltok::star, "expected '*' in address space"))
1438 return true;
1439
Owen Anderson6b6e2d92009-07-29 22:17:13 +00001440 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattner103ff152009-01-02 07:01:27 +00001441 break;
1442 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001443
Chris Lattner103ff152009-01-02 07:01:27 +00001444 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1445 case lltok::lparen:
1446 if (ParseFunctionType(Result))
1447 return true;
1448 break;
1449 }
1450 }
1451}
1452
1453/// ParseParameterList
1454/// ::= '(' ')'
1455/// ::= '(' Arg (',' Arg)* ')'
1456/// Arg
1457/// ::= Type OptionalAttributes Value OptionalAttributes
1458bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1459 PerFunctionState &PFS) {
1460 if (ParseToken(lltok::lparen, "expected '(' in call"))
1461 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001462
Chris Lattner103ff152009-01-02 07:01:27 +00001463 while (Lex.getKind() != lltok::rparen) {
1464 // If this isn't the first argument, we need a comma.
1465 if (!ArgList.empty() &&
1466 ParseToken(lltok::comma, "expected ',' in argument list"))
1467 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001468
Chris Lattner103ff152009-01-02 07:01:27 +00001469 // Parse the argument.
1470 LocTy ArgLoc;
Owen Anderson35b47072009-08-13 21:58:54 +00001471 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez223c7142009-12-03 23:40:58 +00001472 unsigned ArgAttrs1 = Attribute::None;
1473 unsigned ArgAttrs2 = Attribute::None;
Chris Lattner103ff152009-01-02 07:01:27 +00001474 Value *V;
Victor Hernandez223c7142009-12-03 23:40:58 +00001475 if (ParseType(ArgTy, ArgLoc))
Chris Lattner103ff152009-01-02 07:01:27 +00001476 return true;
Victor Hernandez223c7142009-12-03 23:40:58 +00001477
Chris Lattner4a413b52009-12-30 02:11:14 +00001478 // Otherwise, handle normal operands.
1479 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1480 ParseValue(ArgTy, V, PFS) ||
1481 // FIXME: Should not allow attributes after the argument, remove this
1482 // in LLVM 3.0.
1483 ParseOptionalAttrs(ArgAttrs2, 3))
1484 return true;
Chris Lattner103ff152009-01-02 07:01:27 +00001485 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1486 }
1487
1488 Lex.Lex(); // Lex the ')'.
1489 return false;
1490}
1491
1492
1493
Chris Lattnerd3dcc922009-01-05 18:34:07 +00001494/// ParseArgumentList - Parse the argument list for a function type or function
1495/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattner103ff152009-01-02 07:01:27 +00001496/// ::= '(' ArgTypeListI ')'
1497/// ArgTypeListI
1498/// ::= /*empty*/
1499/// ::= '...'
1500/// ::= ArgTypeList ',' '...'
1501/// ::= ArgType (',' ArgType)*
Chris Lattnerd3dcc922009-01-05 18:34:07 +00001502///
Chris Lattner103ff152009-01-02 07:01:27 +00001503bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerd3dcc922009-01-05 18:34:07 +00001504 bool &isVarArg, bool inType) {
Chris Lattner103ff152009-01-02 07:01:27 +00001505 isVarArg = false;
1506 assert(Lex.getKind() == lltok::lparen);
1507 Lex.Lex(); // eat the (.
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001508
Chris Lattner103ff152009-01-02 07:01:27 +00001509 if (Lex.getKind() == lltok::rparen) {
1510 // empty
1511 } else if (Lex.getKind() == lltok::dotdotdot) {
1512 isVarArg = true;
1513 Lex.Lex();
1514 } else {
1515 LocTy TypeLoc = Lex.getLoc();
Owen Anderson35b47072009-08-13 21:58:54 +00001516 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattner103ff152009-01-02 07:01:27 +00001517 unsigned Attrs;
Chris Lattner103ff152009-01-02 07:01:27 +00001518 std::string Name;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001519
Chris Lattnerd3dcc922009-01-05 18:34:07 +00001520 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1521 // types (such as a function returning a pointer to itself). If parsing a
1522 // function prototype, we require fully resolved types.
1523 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner6226fd22009-01-02 08:05:26 +00001524 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001525
Chris Lattner82cdc062009-10-05 05:54:46 +00001526 if (ArgTy->isVoidTy())
Chris Lattnerc3a8e192009-03-09 04:49:14 +00001527 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001528
Chris Lattner103ff152009-01-02 07:01:27 +00001529 if (Lex.getKind() == lltok::LocalVar ||
1530 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1531 Name = Lex.getStrVal();
1532 Lex.Lex();
1533 }
Chris Lattner6226fd22009-01-02 08:05:26 +00001534
Nick Lewycky85387e42009-06-07 07:26:46 +00001535 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner6226fd22009-01-02 08:05:26 +00001536 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001537
Chris Lattner103ff152009-01-02 07:01:27 +00001538 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001539
Chris Lattner6226fd22009-01-02 08:05:26 +00001540 while (EatIfPresent(lltok::comma)) {
Chris Lattner103ff152009-01-02 07:01:27 +00001541 // Handle ... at end of arg list.
Chris Lattner6226fd22009-01-02 08:05:26 +00001542 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattner103ff152009-01-02 07:01:27 +00001543 isVarArg = true;
Chris Lattner103ff152009-01-02 07:01:27 +00001544 break;
1545 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001546
Chris Lattner103ff152009-01-02 07:01:27 +00001547 // Otherwise must be an argument type.
1548 TypeLoc = Lex.getLoc();
Chris Lattnerc3a8e192009-03-09 04:49:14 +00001549 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner6226fd22009-01-02 08:05:26 +00001550 ParseOptionalAttrs(Attrs, 0)) return true;
1551
Chris Lattner82cdc062009-10-05 05:54:46 +00001552 if (ArgTy->isVoidTy())
Chris Lattnerc3a8e192009-03-09 04:49:14 +00001553 return Error(TypeLoc, "argument can not have void type");
1554
Chris Lattner103ff152009-01-02 07:01:27 +00001555 if (Lex.getKind() == lltok::LocalVar ||
1556 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1557 Name = Lex.getStrVal();
1558 Lex.Lex();
1559 } else {
1560 Name = "";
1561 }
Chris Lattner6226fd22009-01-02 08:05:26 +00001562
Duncan Sands1e6932c2010-02-16 14:50:09 +00001563 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner6226fd22009-01-02 08:05:26 +00001564 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001565
Chris Lattner103ff152009-01-02 07:01:27 +00001566 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1567 }
1568 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001569
Chris Lattner6226fd22009-01-02 08:05:26 +00001570 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattner103ff152009-01-02 07:01:27 +00001571}
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001572
Chris Lattner103ff152009-01-02 07:01:27 +00001573/// ParseFunctionType
1574/// ::= Type ArgumentList OptionalAttrs
1575bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1576 assert(Lex.getKind() == lltok::lparen);
1577
Chris Lattnerbfba09d2009-01-05 08:04:33 +00001578 if (!FunctionType::isValidReturnType(Result))
1579 return TokError("invalid function return type");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001580
Chris Lattner103ff152009-01-02 07:01:27 +00001581 std::vector<ArgInfo> ArgList;
1582 bool isVarArg;
1583 unsigned Attrs;
Chris Lattnerd3dcc922009-01-05 18:34:07 +00001584 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattner103ff152009-01-02 07:01:27 +00001585 // FIXME: Allow, but ignore attributes on function types!
1586 // FIXME: Remove in LLVM 3.0
1587 ParseOptionalAttrs(Attrs, 2))
1588 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001589
Chris Lattner103ff152009-01-02 07:01:27 +00001590 // Reject names on the arguments lists.
1591 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1592 if (!ArgList[i].Name.empty())
1593 return Error(ArgList[i].Loc, "argument name invalid in function type");
1594 if (!ArgList[i].Attrs != 0) {
1595 // Allow but ignore attributes on function types; this permits
1596 // auto-upgrade.
1597 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1598 }
1599 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001600
Chris Lattner103ff152009-01-02 07:01:27 +00001601 std::vector<const Type*> ArgListTy;
1602 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1603 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001604
Owen Anderson6b6e2d92009-07-29 22:17:13 +00001605 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonc3644562009-07-01 23:57:11 +00001606 ArgListTy, isVarArg));
Chris Lattner103ff152009-01-02 07:01:27 +00001607 return false;
1608}
1609
1610/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1611/// TypeRec
1612/// ::= '{' '}'
1613/// ::= '{' TypeRec (',' TypeRec)* '}'
1614/// ::= '<' '{' '}' '>'
1615/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1616bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1617 assert(Lex.getKind() == lltok::lbrace);
1618 Lex.Lex(); // Consume the '{'
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001619
Chris Lattner6226fd22009-01-02 08:05:26 +00001620 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond2ed7452009-08-05 23:16:16 +00001621 Result = StructType::get(Context, Packed);
Chris Lattner103ff152009-01-02 07:01:27 +00001622 return false;
1623 }
1624
1625 std::vector<PATypeHolder> ParamsList;
Chris Lattnerc3a8e192009-03-09 04:49:14 +00001626 LocTy EltTyLoc = Lex.getLoc();
Chris Lattner103ff152009-01-02 07:01:27 +00001627 if (ParseTypeRec(Result)) return true;
1628 ParamsList.push_back(Result);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001629
Chris Lattner82cdc062009-10-05 05:54:46 +00001630 if (Result->isVoidTy())
Chris Lattnerc3a8e192009-03-09 04:49:14 +00001631 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewycky85387e42009-06-07 07:26:46 +00001632 if (!StructType::isValidElementType(Result))
1633 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001634
Chris Lattner6226fd22009-01-02 08:05:26 +00001635 while (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a8e192009-03-09 04:49:14 +00001636 EltTyLoc = Lex.getLoc();
Chris Lattner103ff152009-01-02 07:01:27 +00001637 if (ParseTypeRec(Result)) return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001638
Chris Lattner82cdc062009-10-05 05:54:46 +00001639 if (Result->isVoidTy())
Chris Lattnerc3a8e192009-03-09 04:49:14 +00001640 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewycky85387e42009-06-07 07:26:46 +00001641 if (!StructType::isValidElementType(Result))
1642 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001643
Chris Lattner103ff152009-01-02 07:01:27 +00001644 ParamsList.push_back(Result);
1645 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001646
Chris Lattner6226fd22009-01-02 08:05:26 +00001647 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1648 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001649
Chris Lattner103ff152009-01-02 07:01:27 +00001650 std::vector<const Type*> ParamsListTy;
1651 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1652 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond2ed7452009-08-05 23:16:16 +00001653 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattner103ff152009-01-02 07:01:27 +00001654 return false;
1655}
1656
Chris Lattnerd5d51722010-02-12 20:49:41 +00001657/// ParseUnionType
1658/// TypeRec
1659/// ::= 'union' '{' TypeRec (',' TypeRec)* '}'
1660bool LLParser::ParseUnionType(PATypeHolder &Result) {
1661 assert(Lex.getKind() == lltok::kw_union);
1662 Lex.Lex(); // Consume the 'union'
1663
1664 if (ParseToken(lltok::lbrace, "'{' expected after 'union'")) return true;
1665
1666 SmallVector<PATypeHolder, 8> ParamsList;
1667 do {
1668 LocTy EltTyLoc = Lex.getLoc();
1669 if (ParseTypeRec(Result)) return true;
1670 ParamsList.push_back(Result);
1671
1672 if (Result->isVoidTy())
1673 return Error(EltTyLoc, "union element can not have void type");
1674 if (!UnionType::isValidElementType(Result))
1675 return Error(EltTyLoc, "invalid element type for union");
1676
1677 } while (EatIfPresent(lltok::comma)) ;
1678
1679 if (ParseToken(lltok::rbrace, "expected '}' at end of union"))
1680 return true;
1681
1682 SmallVector<const Type*, 8> ParamsListTy;
1683 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1684 ParamsListTy.push_back(ParamsList[i].get());
1685 Result = HandleUpRefs(UnionType::get(&ParamsListTy[0], ParamsListTy.size()));
1686 return false;
1687}
1688
Chris Lattner103ff152009-01-02 07:01:27 +00001689/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1690/// token has already been consumed.
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001691/// TypeRec
Chris Lattner103ff152009-01-02 07:01:27 +00001692/// ::= '[' APSINTVAL 'x' Types ']'
1693/// ::= '<' APSINTVAL 'x' Types '>'
1694bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1695 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1696 Lex.getAPSIntVal().getBitWidth() > 64)
1697 return TokError("expected number in address space");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001698
Chris Lattner103ff152009-01-02 07:01:27 +00001699 LocTy SizeLoc = Lex.getLoc();
1700 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner6226fd22009-01-02 08:05:26 +00001701 Lex.Lex();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001702
Chris Lattner6226fd22009-01-02 08:05:26 +00001703 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1704 return true;
Chris Lattner103ff152009-01-02 07:01:27 +00001705
1706 LocTy TypeLoc = Lex.getLoc();
Owen Anderson35b47072009-08-13 21:58:54 +00001707 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner103ff152009-01-02 07:01:27 +00001708 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001709
Chris Lattner82cdc062009-10-05 05:54:46 +00001710 if (EltTy->isVoidTy())
Chris Lattnerc3a8e192009-03-09 04:49:14 +00001711 return Error(TypeLoc, "array and vector element type cannot be void");
1712
Chris Lattner6226fd22009-01-02 08:05:26 +00001713 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1714 "expected end of sequential type"))
1715 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001716
Chris Lattner103ff152009-01-02 07:01:27 +00001717 if (isVector) {
Chris Lattner8100d382009-02-28 18:12:41 +00001718 if (Size == 0)
1719 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattner103ff152009-01-02 07:01:27 +00001720 if ((unsigned)Size != Size)
1721 return Error(SizeLoc, "size too large for vector");
Nick Lewycky85387e42009-06-07 07:26:46 +00001722 if (!VectorType::isValidElementType(EltTy))
Chris Lattner103ff152009-01-02 07:01:27 +00001723 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Anderson6b6e2d92009-07-29 22:17:13 +00001724 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattner103ff152009-01-02 07:01:27 +00001725 } else {
Nick Lewycky85387e42009-06-07 07:26:46 +00001726 if (!ArrayType::isValidElementType(EltTy))
Chris Lattner103ff152009-01-02 07:01:27 +00001727 return Error(TypeLoc, "invalid array element type");
Owen Anderson6b6e2d92009-07-29 22:17:13 +00001728 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattner103ff152009-01-02 07:01:27 +00001729 }
1730 return false;
1731}
1732
1733//===----------------------------------------------------------------------===//
1734// Function Semantic Analysis.
1735//===----------------------------------------------------------------------===//
1736
Chris Lattner5bb63f12009-10-28 03:39:23 +00001737LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1738 int functionNumber)
1739 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattner103ff152009-01-02 07:01:27 +00001740
1741 // Insert unnamed arguments into the NumberedVals list.
1742 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1743 AI != E; ++AI)
1744 if (!AI->hasName())
1745 NumberedVals.push_back(AI);
1746}
1747
1748LLParser::PerFunctionState::~PerFunctionState() {
1749 // If there were any forward referenced non-basicblock values, delete them.
1750 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1751 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1752 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson04cbeec2009-07-02 17:04:01 +00001753 I->second.first->replaceAllUsesWith(
Owen Andersonb99ecca2009-07-30 23:03:37 +00001754 UndefValue::get(I->second.first->getType()));
Chris Lattner103ff152009-01-02 07:01:27 +00001755 delete I->second.first;
1756 I->second.first = 0;
1757 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001758
Chris Lattner103ff152009-01-02 07:01:27 +00001759 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1760 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1761 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson04cbeec2009-07-02 17:04:01 +00001762 I->second.first->replaceAllUsesWith(
Owen Andersonb99ecca2009-07-30 23:03:37 +00001763 UndefValue::get(I->second.first->getType()));
Chris Lattner103ff152009-01-02 07:01:27 +00001764 delete I->second.first;
1765 I->second.first = 0;
1766 }
1767}
1768
Chris Lattner5bb63f12009-10-28 03:39:23 +00001769bool LLParser::PerFunctionState::FinishFunction() {
1770 // Check to see if someone took the address of labels in this block.
1771 if (!P.ForwardRefBlockAddresses.empty()) {
1772 ValID FunctionID;
1773 if (!F.getName().empty()) {
1774 FunctionID.Kind = ValID::t_GlobalName;
1775 FunctionID.StrVal = F.getName();
1776 } else {
1777 FunctionID.Kind = ValID::t_GlobalID;
1778 FunctionID.UIntVal = FunctionNumber;
1779 }
1780
1781 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1782 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1783 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1784 // Resolve all these references.
1785 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1786 return true;
1787
1788 P.ForwardRefBlockAddresses.erase(FRBAI);
1789 }
1790 }
1791
Chris Lattner103ff152009-01-02 07:01:27 +00001792 if (!ForwardRefVals.empty())
1793 return P.Error(ForwardRefVals.begin()->second.second,
1794 "use of undefined value '%" + ForwardRefVals.begin()->first +
1795 "'");
1796 if (!ForwardRefValIDs.empty())
1797 return P.Error(ForwardRefValIDs.begin()->second.second,
1798 "use of undefined value '%" +
1799 utostr(ForwardRefValIDs.begin()->first) + "'");
1800 return false;
1801}
1802
1803
1804/// GetVal - Get a value with the specified name or ID, creating a
1805/// forward reference record if needed. This can return null if the value
1806/// exists but does not have the right type.
1807Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1808 const Type *Ty, LocTy Loc) {
1809 // Look this name up in the normal function symbol table.
1810 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001811
Chris Lattner103ff152009-01-02 07:01:27 +00001812 // If this is a forward reference for the value, see if we already created a
1813 // forward ref record.
1814 if (Val == 0) {
1815 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1816 I = ForwardRefVals.find(Name);
1817 if (I != ForwardRefVals.end())
1818 Val = I->second.first;
1819 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001820
Chris Lattner103ff152009-01-02 07:01:27 +00001821 // If we have the value in the symbol table or fwd-ref table, return it.
1822 if (Val) {
1823 if (Val->getType() == Ty) return Val;
Chris Lattner82cdc062009-10-05 05:54:46 +00001824 if (Ty->isLabelTy())
Chris Lattner103ff152009-01-02 07:01:27 +00001825 P.Error(Loc, "'%" + Name + "' is not a basic block");
1826 else
1827 P.Error(Loc, "'%" + Name + "' defined with type '" +
1828 Val->getType()->getDescription() + "'");
1829 return 0;
1830 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001831
Chris Lattner103ff152009-01-02 07:01:27 +00001832 // Don't make placeholders with invalid type.
Duncan Sands1e6932c2010-02-16 14:50:09 +00001833 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattner103ff152009-01-02 07:01:27 +00001834 P.Error(Loc, "invalid use of a non-first-class type");
1835 return 0;
1836 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001837
Chris Lattner103ff152009-01-02 07:01:27 +00001838 // Otherwise, create a new forward reference for this value and remember it.
1839 Value *FwdVal;
Chris Lattner82cdc062009-10-05 05:54:46 +00001840 if (Ty->isLabelTy())
Owen Anderson35b47072009-08-13 21:58:54 +00001841 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattner103ff152009-01-02 07:01:27 +00001842 else
1843 FwdVal = new Argument(Ty, Name);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001844
Chris Lattner103ff152009-01-02 07:01:27 +00001845 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1846 return FwdVal;
1847}
1848
1849Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1850 LocTy Loc) {
1851 // Look this name up in the normal function symbol table.
1852 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001853
Chris Lattner103ff152009-01-02 07:01:27 +00001854 // If this is a forward reference for the value, see if we already created a
1855 // forward ref record.
1856 if (Val == 0) {
1857 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1858 I = ForwardRefValIDs.find(ID);
1859 if (I != ForwardRefValIDs.end())
1860 Val = I->second.first;
1861 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001862
Chris Lattner103ff152009-01-02 07:01:27 +00001863 // If we have the value in the symbol table or fwd-ref table, return it.
1864 if (Val) {
1865 if (Val->getType() == Ty) return Val;
Chris Lattner82cdc062009-10-05 05:54:46 +00001866 if (Ty->isLabelTy())
Chris Lattner103ff152009-01-02 07:01:27 +00001867 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1868 else
1869 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1870 Val->getType()->getDescription() + "'");
1871 return 0;
1872 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001873
Duncan Sands1e6932c2010-02-16 14:50:09 +00001874 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattner103ff152009-01-02 07:01:27 +00001875 P.Error(Loc, "invalid use of a non-first-class type");
1876 return 0;
1877 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001878
Chris Lattner103ff152009-01-02 07:01:27 +00001879 // Otherwise, create a new forward reference for this value and remember it.
1880 Value *FwdVal;
Chris Lattner82cdc062009-10-05 05:54:46 +00001881 if (Ty->isLabelTy())
Owen Anderson35b47072009-08-13 21:58:54 +00001882 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattner103ff152009-01-02 07:01:27 +00001883 else
1884 FwdVal = new Argument(Ty);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001885
Chris Lattner103ff152009-01-02 07:01:27 +00001886 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1887 return FwdVal;
1888}
1889
1890/// SetInstName - After an instruction is parsed and inserted into its
1891/// basic block, this installs its name.
1892bool LLParser::PerFunctionState::SetInstName(int NameID,
1893 const std::string &NameStr,
1894 LocTy NameLoc, Instruction *Inst) {
1895 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattner82cdc062009-10-05 05:54:46 +00001896 if (Inst->getType()->isVoidTy()) {
Chris Lattner103ff152009-01-02 07:01:27 +00001897 if (NameID != -1 || !NameStr.empty())
1898 return P.Error(NameLoc, "instructions returning void cannot have a name");
1899 return false;
1900 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001901
Chris Lattner103ff152009-01-02 07:01:27 +00001902 // If this was a numbered instruction, verify that the instruction is the
1903 // expected value and resolve any forward references.
1904 if (NameStr.empty()) {
1905 // If neither a name nor an ID was specified, just use the next ID.
1906 if (NameID == -1)
1907 NameID = NumberedVals.size();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001908
Chris Lattner103ff152009-01-02 07:01:27 +00001909 if (unsigned(NameID) != NumberedVals.size())
1910 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1911 utostr(NumberedVals.size()) + "'");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001912
Chris Lattner103ff152009-01-02 07:01:27 +00001913 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1914 ForwardRefValIDs.find(NameID);
1915 if (FI != ForwardRefValIDs.end()) {
1916 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001917 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner103ff152009-01-02 07:01:27 +00001918 FI->second.first->getType()->getDescription() + "'");
1919 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes58837332009-09-02 15:02:57 +00001920 delete FI->second.first;
Chris Lattner103ff152009-01-02 07:01:27 +00001921 ForwardRefValIDs.erase(FI);
1922 }
1923
1924 NumberedVals.push_back(Inst);
1925 return false;
1926 }
1927
1928 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1929 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1930 FI = ForwardRefVals.find(NameStr);
1931 if (FI != ForwardRefVals.end()) {
1932 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001933 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner103ff152009-01-02 07:01:27 +00001934 FI->second.first->getType()->getDescription() + "'");
1935 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopesf50aecf2009-09-02 14:22:03 +00001936 delete FI->second.first;
Chris Lattner103ff152009-01-02 07:01:27 +00001937 ForwardRefVals.erase(FI);
1938 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001939
Chris Lattner103ff152009-01-02 07:01:27 +00001940 // Set the name on the instruction.
1941 Inst->setName(NameStr);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001942
Chris Lattner103ff152009-01-02 07:01:27 +00001943 if (Inst->getNameStr() != NameStr)
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001944 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattner103ff152009-01-02 07:01:27 +00001945 NameStr + "'");
1946 return false;
1947}
1948
1949/// GetBB - Get a basic block with the specified name or ID, creating a
1950/// forward reference record if needed.
1951BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1952 LocTy Loc) {
Owen Anderson35b47072009-08-13 21:58:54 +00001953 return cast_or_null<BasicBlock>(GetVal(Name,
1954 Type::getLabelTy(F.getContext()), Loc));
Chris Lattner103ff152009-01-02 07:01:27 +00001955}
1956
1957BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson35b47072009-08-13 21:58:54 +00001958 return cast_or_null<BasicBlock>(GetVal(ID,
1959 Type::getLabelTy(F.getContext()), Loc));
Chris Lattner103ff152009-01-02 07:01:27 +00001960}
1961
1962/// DefineBB - Define the specified basic block, which is either named or
1963/// unnamed. If there is an error, this returns null otherwise it returns
1964/// the block being defined.
1965BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1966 LocTy Loc) {
1967 BasicBlock *BB;
1968 if (Name.empty())
1969 BB = GetBB(NumberedVals.size(), Loc);
1970 else
1971 BB = GetBB(Name, Loc);
1972 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001973
Chris Lattner103ff152009-01-02 07:01:27 +00001974 // Move the block to the end of the function. Forward ref'd blocks are
1975 // inserted wherever they happen to be referenced.
1976 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001977
Chris Lattner103ff152009-01-02 07:01:27 +00001978 // Remove the block from forward ref sets.
1979 if (Name.empty()) {
1980 ForwardRefValIDs.erase(NumberedVals.size());
1981 NumberedVals.push_back(BB);
1982 } else {
1983 // BB forward references are already in the function symbol table.
1984 ForwardRefVals.erase(Name);
1985 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001986
Chris Lattner103ff152009-01-02 07:01:27 +00001987 return BB;
1988}
1989
1990//===----------------------------------------------------------------------===//
1991// Constants.
1992//===----------------------------------------------------------------------===//
1993
1994/// ParseValID - Parse an abstract value that doesn't necessarily have a
1995/// type implied. For example, if we parse "4" we don't know what integer type
1996/// it has. The value will later be combined with its type and checked for
Victor Hernandezc4261242010-01-10 07:14:18 +00001997/// sanity. PFS is used to convert function-local operands of metadata (since
1998/// metadata operands are not just parsed here but also converted to values).
1999/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf454d22010-01-05 22:22:14 +00002000bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattner103ff152009-01-02 07:01:27 +00002001 ID.Loc = Lex.getLoc();
2002 switch (Lex.getKind()) {
2003 default: return TokError("expected value token");
2004 case lltok::GlobalID: // @42
2005 ID.UIntVal = Lex.getUIntVal();
2006 ID.Kind = ValID::t_GlobalID;
2007 break;
2008 case lltok::GlobalVar: // @foo
2009 ID.StrVal = Lex.getStrVal();
2010 ID.Kind = ValID::t_GlobalName;
2011 break;
2012 case lltok::LocalVarID: // %42
2013 ID.UIntVal = Lex.getUIntVal();
2014 ID.Kind = ValID::t_LocalID;
2015 break;
2016 case lltok::LocalVar: // %foo
2017 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2018 ID.StrVal = Lex.getStrVal();
2019 ID.Kind = ValID::t_LocalName;
2020 break;
Chris Lattnerf39c84f2009-12-30 04:56:59 +00002021 case lltok::exclaim: // !{...} MDNode, !"foo" MDString
Nick Lewycky4dcf8102009-04-04 07:22:01 +00002022 Lex.Lex();
Chris Lattnerb3d6fad2009-12-29 21:53:55 +00002023
Chris Lattner73fd84e2009-12-29 22:40:21 +00002024 if (EatIfPresent(lltok::lbrace)) {
Nick Lewycky117f4382009-05-10 20:57:05 +00002025 SmallVector<Value*, 16> Elts;
Victor Hernandezc4261242010-01-10 07:14:18 +00002026 if (ParseMDNodeVector(Elts, PFS) ||
Nick Lewycky4dcf8102009-04-04 07:22:01 +00002027 ParseToken(lltok::rbrace, "expected end of metadata node"))
2028 return true;
Nick Lewycky117f4382009-05-10 20:57:05 +00002029
Victor Hernandezc4261242010-01-10 07:14:18 +00002030 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
Chris Lattner4a413b52009-12-30 02:11:14 +00002031 ID.Kind = ValID::t_MDNode;
Nick Lewycky4dcf8102009-04-04 07:22:01 +00002032 return false;
2033 }
2034
Devang Patela8261c62009-07-01 19:21:12 +00002035 // Standalone metadata reference
2036 // !{ ..., !42, ... }
Chris Lattnercd7e6f62009-12-30 04:13:37 +00002037 if (Lex.getKind() == lltok::APSInt) {
Chris Lattner84a86d22009-12-30 04:15:23 +00002038 if (ParseMDNodeID(ID.MDNodeVal)) return true;
Chris Lattner4a413b52009-12-30 02:11:14 +00002039 ID.Kind = ValID::t_MDNode;
Devang Patela8261c62009-07-01 19:21:12 +00002040 return false;
Chris Lattner4a413b52009-12-30 02:11:14 +00002041 }
2042
Nick Lewycky4dcf8102009-04-04 07:22:01 +00002043 // MDString:
2044 // ::= '!' STRINGCONSTANT
Chris Lattner4a413b52009-12-30 02:11:14 +00002045 if (ParseMDString(ID.MDStringVal)) return true;
2046 ID.Kind = ValID::t_MDString;
Nick Lewycky4dcf8102009-04-04 07:22:01 +00002047 return false;
Chris Lattner103ff152009-01-02 07:01:27 +00002048 case lltok::APSInt:
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002049 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattner103ff152009-01-02 07:01:27 +00002050 ID.Kind = ValID::t_APSInt;
2051 break;
2052 case lltok::APFloat:
2053 ID.APFloatVal = Lex.getAPFloatVal();
2054 ID.Kind = ValID::t_APFloat;
2055 break;
2056 case lltok::kw_true:
Owen Anderson4f720fa2009-07-31 17:39:07 +00002057 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattner103ff152009-01-02 07:01:27 +00002058 ID.Kind = ValID::t_Constant;
2059 break;
2060 case lltok::kw_false:
Owen Anderson4f720fa2009-07-31 17:39:07 +00002061 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattner103ff152009-01-02 07:01:27 +00002062 ID.Kind = ValID::t_Constant;
2063 break;
2064 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2065 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2066 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002067
Chris Lattner103ff152009-01-02 07:01:27 +00002068 case lltok::lbrace: {
2069 // ValID ::= '{' ConstVector '}'
2070 Lex.Lex();
2071 SmallVector<Constant*, 16> Elts;
2072 if (ParseGlobalValueVector(Elts) ||
2073 ParseToken(lltok::rbrace, "expected end of struct constant"))
2074 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002075
Owen Andersond2ed7452009-08-05 23:16:16 +00002076 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2077 Elts.size(), false);
Chris Lattner103ff152009-01-02 07:01:27 +00002078 ID.Kind = ValID::t_Constant;
2079 return false;
2080 }
2081 case lltok::less: {
2082 // ValID ::= '<' ConstVector '>' --> Vector.
2083 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2084 Lex.Lex();
Chris Lattner6226fd22009-01-02 08:05:26 +00002085 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002086
Chris Lattner103ff152009-01-02 07:01:27 +00002087 SmallVector<Constant*, 16> Elts;
2088 LocTy FirstEltLoc = Lex.getLoc();
2089 if (ParseGlobalValueVector(Elts) ||
2090 (isPackedStruct &&
2091 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2092 ParseToken(lltok::greater, "expected end of constant"))
2093 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002094
Chris Lattner103ff152009-01-02 07:01:27 +00002095 if (isPackedStruct) {
Owen Andersonc3644562009-07-01 23:57:11 +00002096 ID.ConstantVal =
Owen Andersond2ed7452009-08-05 23:16:16 +00002097 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattner103ff152009-01-02 07:01:27 +00002098 ID.Kind = ValID::t_Constant;
2099 return false;
2100 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002101
Chris Lattner103ff152009-01-02 07:01:27 +00002102 if (Elts.empty())
2103 return Error(ID.Loc, "constant vector must not be empty");
2104
Duncan Sandse92dee12010-02-15 16:12:20 +00002105 if (!Elts[0]->getType()->isIntegerTy() &&
2106 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattner103ff152009-01-02 07:01:27 +00002107 return Error(FirstEltLoc,
2108 "vector elements must have integer or floating point type");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002109
Chris Lattner103ff152009-01-02 07:01:27 +00002110 // Verify that all the vector elements have the same type.
2111 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2112 if (Elts[i]->getType() != Elts[0]->getType())
2113 return Error(FirstEltLoc,
2114 "vector element #" + utostr(i) +
2115 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002116
Owen Anderson2f422e02009-07-28 21:19:26 +00002117 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattner103ff152009-01-02 07:01:27 +00002118 ID.Kind = ValID::t_Constant;
2119 return false;
2120 }
2121 case lltok::lsquare: { // Array Constant
2122 Lex.Lex();
2123 SmallVector<Constant*, 16> Elts;
2124 LocTy FirstEltLoc = Lex.getLoc();
2125 if (ParseGlobalValueVector(Elts) ||
2126 ParseToken(lltok::rsquare, "expected end of array constant"))
2127 return true;
2128
2129 // Handle empty element.
2130 if (Elts.empty()) {
2131 // Use undef instead of an array because it's inconvenient to determine
2132 // the element type at this point, there being no elements to examine.
Chris Lattnera5ce0fe2009-01-05 07:52:51 +00002133 ID.Kind = ValID::t_EmptyArray;
Chris Lattner103ff152009-01-02 07:01:27 +00002134 return false;
2135 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002136
Chris Lattner103ff152009-01-02 07:01:27 +00002137 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002138 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner103ff152009-01-02 07:01:27 +00002139 Elts[0]->getType()->getDescription());
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002140
Owen Anderson6b6e2d92009-07-29 22:17:13 +00002141 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002142
Chris Lattner103ff152009-01-02 07:01:27 +00002143 // Verify all elements are correct type!
Chris Lattner8c8ebf22009-01-02 08:49:06 +00002144 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattner103ff152009-01-02 07:01:27 +00002145 if (Elts[i]->getType() != Elts[0]->getType())
2146 return Error(FirstEltLoc,
2147 "array element #" + utostr(i) +
2148 " is not of type '" +Elts[0]->getType()->getDescription());
2149 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002150
Owen Anderson7b4f9f82009-07-28 18:32:17 +00002151 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattner103ff152009-01-02 07:01:27 +00002152 ID.Kind = ValID::t_Constant;
2153 return false;
2154 }
2155 case lltok::kw_c: // c "foo"
2156 Lex.Lex();
Owen Anderson35b47072009-08-13 21:58:54 +00002157 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattner103ff152009-01-02 07:01:27 +00002158 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2159 ID.Kind = ValID::t_Constant;
2160 return false;
2161
2162 case lltok::kw_asm: {
Dale Johannesen5ee3e4b2009-10-21 23:28:00 +00002163 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2164 bool HasSideEffect, AlignStack;
Chris Lattner103ff152009-01-02 07:01:27 +00002165 Lex.Lex();
2166 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen5ee3e4b2009-10-21 23:28:00 +00002167 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner6226fd22009-01-02 08:05:26 +00002168 ParseStringConstant(ID.StrVal) ||
2169 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattner103ff152009-01-02 07:01:27 +00002170 ParseToken(lltok::StringConstant, "expected constraint string"))
2171 return true;
2172 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbar630690c2009-11-07 23:51:55 +00002173 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattner103ff152009-01-02 07:01:27 +00002174 ID.Kind = ValID::t_InlineAsm;
2175 return false;
2176 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002177
Chris Lattner5bb63f12009-10-28 03:39:23 +00002178 case lltok::kw_blockaddress: {
2179 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2180 Lex.Lex();
2181
2182 ValID Fn, Label;
2183 LocTy FnLoc, LabelLoc;
2184
2185 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2186 ParseValID(Fn) ||
2187 ParseToken(lltok::comma, "expected comma in block address expression")||
2188 ParseValID(Label) ||
2189 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2190 return true;
Chris Lattner620cead2009-11-01 01:27:45 +00002191
Chris Lattner5bb63f12009-10-28 03:39:23 +00002192 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2193 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattner620cead2009-11-01 01:27:45 +00002194 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner5bb63f12009-10-28 03:39:23 +00002195 return Error(Label.Loc, "expected basic block name in blockaddress");
2196
2197 // Make a global variable as a placeholder for this reference.
2198 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2199 false, GlobalValue::InternalLinkage,
2200 0, "");
2201 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2202 ID.ConstantVal = FwdRef;
2203 ID.Kind = ValID::t_Constant;
2204 return false;
2205 }
2206
Chris Lattner103ff152009-01-02 07:01:27 +00002207 case lltok::kw_trunc:
2208 case lltok::kw_zext:
2209 case lltok::kw_sext:
2210 case lltok::kw_fptrunc:
2211 case lltok::kw_fpext:
2212 case lltok::kw_bitcast:
2213 case lltok::kw_uitofp:
2214 case lltok::kw_sitofp:
2215 case lltok::kw_fptoui:
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002216 case lltok::kw_fptosi:
Chris Lattner103ff152009-01-02 07:01:27 +00002217 case lltok::kw_inttoptr:
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002218 case lltok::kw_ptrtoint: {
Chris Lattner103ff152009-01-02 07:01:27 +00002219 unsigned Opc = Lex.getUIntVal();
Owen Anderson35b47072009-08-13 21:58:54 +00002220 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattner103ff152009-01-02 07:01:27 +00002221 Constant *SrcVal;
2222 Lex.Lex();
2223 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2224 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman162d20a2009-06-15 21:52:11 +00002225 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattner103ff152009-01-02 07:01:27 +00002226 ParseType(DestTy) ||
2227 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2228 return true;
2229 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2230 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2231 SrcVal->getType()->getDescription() + "' to '" +
2232 DestTy->getDescription() + "'");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002233 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonc3644562009-07-01 23:57:11 +00002234 SrcVal, DestTy);
Chris Lattner103ff152009-01-02 07:01:27 +00002235 ID.Kind = ValID::t_Constant;
2236 return false;
2237 }
2238 case lltok::kw_extractvalue: {
2239 Lex.Lex();
2240 Constant *Val;
2241 SmallVector<unsigned, 4> Indices;
2242 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2243 ParseGlobalTypeAndValue(Val) ||
2244 ParseIndexList(Indices) ||
2245 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2246 return true;
Devang Patelad58bb32009-11-03 19:06:07 +00002247
Chris Lattnerd5d51722010-02-12 20:49:41 +00002248 if (!Val->getType()->isAggregateType())
2249 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattner103ff152009-01-02 07:01:27 +00002250 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2251 Indices.end()))
2252 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad2d9b3cb2009-05-21 09:52:38 +00002253 ID.ConstantVal =
Owen Anderson02b48c32009-07-29 18:55:55 +00002254 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattner103ff152009-01-02 07:01:27 +00002255 ID.Kind = ValID::t_Constant;
2256 return false;
2257 }
2258 case lltok::kw_insertvalue: {
2259 Lex.Lex();
2260 Constant *Val0, *Val1;
2261 SmallVector<unsigned, 4> Indices;
2262 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2263 ParseGlobalTypeAndValue(Val0) ||
2264 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2265 ParseGlobalTypeAndValue(Val1) ||
2266 ParseIndexList(Indices) ||
2267 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2268 return true;
Chris Lattnerd5d51722010-02-12 20:49:41 +00002269 if (!Val0->getType()->isAggregateType())
2270 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattner103ff152009-01-02 07:01:27 +00002271 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2272 Indices.end()))
2273 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Anderson02b48c32009-07-29 18:55:55 +00002274 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonc3644562009-07-01 23:57:11 +00002275 Indices.data(), Indices.size());
Chris Lattner103ff152009-01-02 07:01:27 +00002276 ID.Kind = ValID::t_Constant;
2277 return false;
2278 }
2279 case lltok::kw_icmp:
Nick Lewycky8f5253b2009-07-08 03:04:38 +00002280 case lltok::kw_fcmp: {
Chris Lattner103ff152009-01-02 07:01:27 +00002281 unsigned PredVal, Opc = Lex.getUIntVal();
2282 Constant *Val0, *Val1;
2283 Lex.Lex();
2284 if (ParseCmpPredicate(PredVal, Opc) ||
2285 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2286 ParseGlobalTypeAndValue(Val0) ||
2287 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2288 ParseGlobalTypeAndValue(Val1) ||
2289 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2290 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002291
Chris Lattner103ff152009-01-02 07:01:27 +00002292 if (Val0->getType() != Val1->getType())
2293 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002294
Chris Lattner103ff152009-01-02 07:01:27 +00002295 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002296
Chris Lattner103ff152009-01-02 07:01:27 +00002297 if (Opc == Instruction::FCmp) {
Duncan Sandse92dee12010-02-15 16:12:20 +00002298 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattner103ff152009-01-02 07:01:27 +00002299 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson02b48c32009-07-29 18:55:55 +00002300 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky8f5253b2009-07-08 03:04:38 +00002301 } else {
2302 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandse92dee12010-02-15 16:12:20 +00002303 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands10343d92010-02-16 11:11:14 +00002304 !Val0->getType()->isPointerTy())
Chris Lattner103ff152009-01-02 07:01:27 +00002305 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson02b48c32009-07-29 18:55:55 +00002306 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattner103ff152009-01-02 07:01:27 +00002307 }
2308 ID.Kind = ValID::t_Constant;
2309 return false;
2310 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002311
Chris Lattner103ff152009-01-02 07:01:27 +00002312 // Binary Operators.
2313 case lltok::kw_add:
Dan Gohman7ce405e2009-06-04 22:49:04 +00002314 case lltok::kw_fadd:
Chris Lattner103ff152009-01-02 07:01:27 +00002315 case lltok::kw_sub:
Dan Gohman7ce405e2009-06-04 22:49:04 +00002316 case lltok::kw_fsub:
Chris Lattner103ff152009-01-02 07:01:27 +00002317 case lltok::kw_mul:
Dan Gohman7ce405e2009-06-04 22:49:04 +00002318 case lltok::kw_fmul:
Chris Lattner103ff152009-01-02 07:01:27 +00002319 case lltok::kw_udiv:
2320 case lltok::kw_sdiv:
2321 case lltok::kw_fdiv:
2322 case lltok::kw_urem:
2323 case lltok::kw_srem:
2324 case lltok::kw_frem: {
Dan Gohman29392252009-07-27 16:11:46 +00002325 bool NUW = false;
2326 bool NSW = false;
2327 bool Exact = false;
Chris Lattner103ff152009-01-02 07:01:27 +00002328 unsigned Opc = Lex.getUIntVal();
2329 Constant *Val0, *Val1;
2330 Lex.Lex();
Dan Gohman29392252009-07-27 16:11:46 +00002331 LocTy ModifierLoc = Lex.getLoc();
2332 if (Opc == Instruction::Add ||
2333 Opc == Instruction::Sub ||
2334 Opc == Instruction::Mul) {
2335 if (EatIfPresent(lltok::kw_nuw))
2336 NUW = true;
2337 if (EatIfPresent(lltok::kw_nsw)) {
2338 NSW = true;
2339 if (EatIfPresent(lltok::kw_nuw))
2340 NUW = true;
2341 }
2342 } else if (Opc == Instruction::SDiv) {
2343 if (EatIfPresent(lltok::kw_exact))
2344 Exact = true;
2345 }
Chris Lattner103ff152009-01-02 07:01:27 +00002346 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2347 ParseGlobalTypeAndValue(Val0) ||
2348 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2349 ParseGlobalTypeAndValue(Val1) ||
2350 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2351 return true;
2352 if (Val0->getType() != Val1->getType())
2353 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandse92dee12010-02-15 16:12:20 +00002354 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman29392252009-07-27 16:11:46 +00002355 if (NUW)
2356 return Error(ModifierLoc, "nuw only applies to integer operations");
2357 if (NSW)
2358 return Error(ModifierLoc, "nsw only applies to integer operations");
2359 }
Dan Gohman571834f2010-05-03 22:44:19 +00002360 // Check that the type is valid for the operator.
2361 switch (Opc) {
2362 case Instruction::Add:
2363 case Instruction::Sub:
2364 case Instruction::Mul:
2365 case Instruction::UDiv:
2366 case Instruction::SDiv:
2367 case Instruction::URem:
2368 case Instruction::SRem:
2369 if (!Val0->getType()->isIntOrIntVectorTy())
2370 return Error(ID.Loc, "constexpr requires integer operands");
2371 break;
2372 case Instruction::FAdd:
2373 case Instruction::FSub:
2374 case Instruction::FMul:
2375 case Instruction::FDiv:
2376 case Instruction::FRem:
2377 if (!Val0->getType()->isFPOrFPVectorTy())
2378 return Error(ID.Loc, "constexpr requires fp operands");
2379 break;
2380 default: llvm_unreachable("Unknown binary operator!");
2381 }
Dan Gohmanf3a08b82009-09-07 23:54:19 +00002382 unsigned Flags = 0;
2383 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2384 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2385 if (Exact) Flags |= SDivOperator::IsExact;
2386 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman29392252009-07-27 16:11:46 +00002387 ID.ConstantVal = C;
Chris Lattner103ff152009-01-02 07:01:27 +00002388 ID.Kind = ValID::t_Constant;
2389 return false;
2390 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002391
Chris Lattner103ff152009-01-02 07:01:27 +00002392 // Logical Operations
2393 case lltok::kw_shl:
2394 case lltok::kw_lshr:
2395 case lltok::kw_ashr:
2396 case lltok::kw_and:
2397 case lltok::kw_or:
2398 case lltok::kw_xor: {
2399 unsigned Opc = Lex.getUIntVal();
2400 Constant *Val0, *Val1;
2401 Lex.Lex();
2402 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2403 ParseGlobalTypeAndValue(Val0) ||
2404 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2405 ParseGlobalTypeAndValue(Val1) ||
2406 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2407 return true;
2408 if (Val0->getType() != Val1->getType())
2409 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandse92dee12010-02-15 16:12:20 +00002410 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattner103ff152009-01-02 07:01:27 +00002411 return Error(ID.Loc,
2412 "constexpr requires integer or integer vector operands");
Owen Anderson02b48c32009-07-29 18:55:55 +00002413 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattner103ff152009-01-02 07:01:27 +00002414 ID.Kind = ValID::t_Constant;
2415 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002416 }
2417
Chris Lattner103ff152009-01-02 07:01:27 +00002418 case lltok::kw_getelementptr:
2419 case lltok::kw_shufflevector:
2420 case lltok::kw_insertelement:
2421 case lltok::kw_extractelement:
2422 case lltok::kw_select: {
2423 unsigned Opc = Lex.getUIntVal();
2424 SmallVector<Constant*, 16> Elts;
Dan Gohman106b2ae2009-07-27 21:53:46 +00002425 bool InBounds = false;
Chris Lattner103ff152009-01-02 07:01:27 +00002426 Lex.Lex();
Dan Gohman106b2ae2009-07-27 21:53:46 +00002427 if (Opc == Instruction::GetElementPtr)
Dan Gohmand0fd20d2009-07-29 15:58:36 +00002428 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattner103ff152009-01-02 07:01:27 +00002429 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2430 ParseGlobalValueVector(Elts) ||
2431 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2432 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002433
Chris Lattner103ff152009-01-02 07:01:27 +00002434 if (Opc == Instruction::GetElementPtr) {
Duncan Sands10343d92010-02-16 11:11:14 +00002435 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattner103ff152009-01-02 07:01:27 +00002436 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002437
Chris Lattner103ff152009-01-02 07:01:27 +00002438 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman5aeb2512009-07-24 21:56:17 +00002439 (Value**)(Elts.data() + 1),
2440 Elts.size() - 1))
Chris Lattner103ff152009-01-02 07:01:27 +00002441 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf3a08b82009-09-07 23:54:19 +00002442 ID.ConstantVal = InBounds ?
2443 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2444 Elts.data() + 1,
2445 Elts.size() - 1) :
2446 ConstantExpr::getGetElementPtr(Elts[0],
2447 Elts.data() + 1, Elts.size() - 1);
Chris Lattner103ff152009-01-02 07:01:27 +00002448 } else if (Opc == Instruction::Select) {
2449 if (Elts.size() != 3)
2450 return Error(ID.Loc, "expected three operands to select");
2451 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2452 Elts[2]))
2453 return Error(ID.Loc, Reason);
Owen Anderson02b48c32009-07-29 18:55:55 +00002454 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattner103ff152009-01-02 07:01:27 +00002455 } else if (Opc == Instruction::ShuffleVector) {
2456 if (Elts.size() != 3)
2457 return Error(ID.Loc, "expected three operands to shufflevector");
2458 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2459 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonc3644562009-07-01 23:57:11 +00002460 ID.ConstantVal =
Owen Anderson02b48c32009-07-29 18:55:55 +00002461 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattner103ff152009-01-02 07:01:27 +00002462 } else if (Opc == Instruction::ExtractElement) {
2463 if (Elts.size() != 2)
2464 return Error(ID.Loc, "expected two operands to extractelement");
2465 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2466 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson02b48c32009-07-29 18:55:55 +00002467 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattner103ff152009-01-02 07:01:27 +00002468 } else {
2469 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2470 if (Elts.size() != 3)
2471 return Error(ID.Loc, "expected three operands to insertelement");
2472 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2473 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonc3644562009-07-01 23:57:11 +00002474 ID.ConstantVal =
Owen Anderson02b48c32009-07-29 18:55:55 +00002475 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattner103ff152009-01-02 07:01:27 +00002476 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002477
Chris Lattner103ff152009-01-02 07:01:27 +00002478 ID.Kind = ValID::t_Constant;
2479 return false;
2480 }
2481 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002482
Chris Lattner103ff152009-01-02 07:01:27 +00002483 Lex.Lex();
2484 return false;
2485}
2486
2487/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez84793eb2010-01-11 22:31:58 +00002488bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2489 C = 0;
Chris Lattner103ff152009-01-02 07:01:27 +00002490 ValID ID;
Victor Hernandez84793eb2010-01-11 22:31:58 +00002491 Value *V = NULL;
2492 bool Parsed = ParseValID(ID) ||
2493 ConvertValIDToValue(Ty, ID, V, NULL);
2494 if (V && !(C = dyn_cast<Constant>(V)))
2495 return Error(ID.Loc, "global values must be constants");
2496 return Parsed;
Chris Lattner103ff152009-01-02 07:01:27 +00002497}
2498
Victor Hernandez84793eb2010-01-11 22:31:58 +00002499bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2500 PATypeHolder Type(Type::getVoidTy(Context));
2501 return ParseType(Type) ||
2502 ParseGlobalValue(Type, V);
2503}
2504
2505/// ParseGlobalValueVector
2506/// ::= /*empty*/
2507/// ::= TypeAndValue (',' TypeAndValue)*
2508bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2509 // Empty list.
2510 if (Lex.getKind() == lltok::rbrace ||
2511 Lex.getKind() == lltok::rsquare ||
2512 Lex.getKind() == lltok::greater ||
2513 Lex.getKind() == lltok::rparen)
2514 return false;
2515
2516 Constant *C;
2517 if (ParseGlobalTypeAndValue(C)) return true;
2518 Elts.push_back(C);
2519
2520 while (EatIfPresent(lltok::comma)) {
2521 if (ParseGlobalTypeAndValue(C)) return true;
2522 Elts.push_back(C);
2523 }
2524
2525 return false;
2526}
2527
2528
2529//===----------------------------------------------------------------------===//
2530// Function Parsing.
2531//===----------------------------------------------------------------------===//
2532
2533bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2534 PerFunctionState *PFS) {
Duncan Sands10343d92010-02-16 11:11:14 +00002535 if (Ty->isFunctionTy())
Chris Lattner103ff152009-01-02 07:01:27 +00002536 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002537
Chris Lattner103ff152009-01-02 07:01:27 +00002538 switch (ID.Kind) {
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002539 default: llvm_unreachable("Unknown ValID!");
Chris Lattner103ff152009-01-02 07:01:27 +00002540 case ValID::t_LocalID:
Victor Hernandez84793eb2010-01-11 22:31:58 +00002541 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2542 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2543 return (V == 0);
Chris Lattner103ff152009-01-02 07:01:27 +00002544 case ValID::t_LocalName:
Victor Hernandez84793eb2010-01-11 22:31:58 +00002545 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2546 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2547 return (V == 0);
2548 case ValID::t_InlineAsm: {
2549 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2550 const FunctionType *FTy =
2551 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2552 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2553 return Error(ID.Loc, "invalid type for inline asm constraint string");
2554 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2555 return false;
2556 }
2557 case ValID::t_MDNode:
2558 if (!Ty->isMetadataTy())
2559 return Error(ID.Loc, "metadata value must have metadata type");
2560 V = ID.MDNodeVal;
2561 return false;
2562 case ValID::t_MDString:
2563 if (!Ty->isMetadataTy())
2564 return Error(ID.Loc, "metadata value must have metadata type");
2565 V = ID.MDStringVal;
2566 return false;
Chris Lattner103ff152009-01-02 07:01:27 +00002567 case ValID::t_GlobalName:
2568 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2569 return V == 0;
2570 case ValID::t_GlobalID:
2571 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2572 return V == 0;
2573 case ValID::t_APSInt:
Duncan Sands10343d92010-02-16 11:11:14 +00002574 if (!Ty->isIntegerTy())
Chris Lattner103ff152009-01-02 07:01:27 +00002575 return Error(ID.Loc, "integer constant must have integer type");
2576 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneacb44d2009-07-24 23:12:02 +00002577 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattner103ff152009-01-02 07:01:27 +00002578 return false;
2579 case ValID::t_APFloat:
Duncan Sandse92dee12010-02-15 16:12:20 +00002580 if (!Ty->isFloatingPointTy() ||
Chris Lattner103ff152009-01-02 07:01:27 +00002581 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2582 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002583
Chris Lattner103ff152009-01-02 07:01:27 +00002584 // The lexer has no type info, so builds all float and double FP constants
2585 // as double. Fix this here. Long double does not need this.
2586 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattner82cdc062009-10-05 05:54:46 +00002587 Ty->isFloatTy()) {
Chris Lattner103ff152009-01-02 07:01:27 +00002588 bool Ignored;
2589 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2590 &Ignored);
2591 }
Owen Andersond363a0e2009-07-27 20:59:43 +00002592 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002593
Chris Lattnerac0911a2009-01-05 18:24:23 +00002594 if (V->getType() != Ty)
2595 return Error(ID.Loc, "floating point constant does not have type '" +
2596 Ty->getDescription() + "'");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002597
Chris Lattner103ff152009-01-02 07:01:27 +00002598 return false;
2599 case ValID::t_Null:
Duncan Sands10343d92010-02-16 11:11:14 +00002600 if (!Ty->isPointerTy())
Chris Lattner103ff152009-01-02 07:01:27 +00002601 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb99ecca2009-07-30 23:03:37 +00002602 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner103ff152009-01-02 07:01:27 +00002603 return false;
2604 case ValID::t_Undef:
Chris Lattner50c7cea2009-01-05 08:13:38 +00002605 // FIXME: LabelTy should not be a first-class type.
Chris Lattner82cdc062009-10-05 05:54:46 +00002606 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands1e6932c2010-02-16 14:50:09 +00002607 !Ty->isOpaqueTy())
Chris Lattner50c7cea2009-01-05 08:13:38 +00002608 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb99ecca2009-07-30 23:03:37 +00002609 V = UndefValue::get(Ty);
Chris Lattner103ff152009-01-02 07:01:27 +00002610 return false;
Chris Lattnera5ce0fe2009-01-05 07:52:51 +00002611 case ValID::t_EmptyArray:
Duncan Sands10343d92010-02-16 11:11:14 +00002612 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattnera5ce0fe2009-01-05 07:52:51 +00002613 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb99ecca2009-07-30 23:03:37 +00002614 V = UndefValue::get(Ty);
Chris Lattnera5ce0fe2009-01-05 07:52:51 +00002615 return false;
Chris Lattner103ff152009-01-02 07:01:27 +00002616 case ValID::t_Zero:
Chris Lattner50c7cea2009-01-05 08:13:38 +00002617 // FIXME: LabelTy should not be a first-class type.
Chris Lattner82cdc062009-10-05 05:54:46 +00002618 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattner103ff152009-01-02 07:01:27 +00002619 return Error(ID.Loc, "invalid type for null constant");
Owen Andersonaac28372009-07-31 20:28:14 +00002620 V = Constant::getNullValue(Ty);
Chris Lattner103ff152009-01-02 07:01:27 +00002621 return false;
2622 case ValID::t_Constant:
Chris Lattnerd5d51722010-02-12 20:49:41 +00002623 if (ID.ConstantVal->getType() != Ty) {
2624 // Allow a constant struct with a single member to be converted
2625 // to a union, if the union has a member which is the same type
2626 // as the struct member.
2627 if (const UnionType* utype = dyn_cast<UnionType>(Ty)) {
2628 return ParseUnionValue(utype, ID, V);
2629 }
2630
Chris Lattner103ff152009-01-02 07:01:27 +00002631 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerd5d51722010-02-12 20:49:41 +00002632 }
2633
Chris Lattner103ff152009-01-02 07:01:27 +00002634 V = ID.ConstantVal;
2635 return false;
2636 }
2637}
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002638
Chris Lattner103ff152009-01-02 07:01:27 +00002639bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2640 V = 0;
2641 ValID ID;
Victor Hernandezbf454d22010-01-05 22:22:14 +00002642 return ParseValID(ID, &PFS) ||
Victor Hernandez84793eb2010-01-11 22:31:58 +00002643 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattner103ff152009-01-02 07:01:27 +00002644}
2645
2646bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson35b47072009-08-13 21:58:54 +00002647 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner6226fd22009-01-02 08:05:26 +00002648 return ParseType(T) ||
2649 ParseValue(T, V, PFS);
Chris Lattner103ff152009-01-02 07:01:27 +00002650}
2651
Chris Lattnere0787282009-10-27 19:13:16 +00002652bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2653 PerFunctionState &PFS) {
2654 Value *V;
2655 Loc = Lex.getLoc();
2656 if (ParseTypeAndValue(V, PFS)) return true;
2657 if (!isa<BasicBlock>(V))
2658 return Error(Loc, "expected a basic block");
2659 BB = cast<BasicBlock>(V);
2660 return false;
2661}
2662
Chris Lattnerd5d51722010-02-12 20:49:41 +00002663bool LLParser::ParseUnionValue(const UnionType* utype, ValID &ID, Value *&V) {
2664 if (const StructType* stype = dyn_cast<StructType>(ID.ConstantVal->getType())) {
2665 if (stype->getNumContainedTypes() != 1)
2666 return Error(ID.Loc, "constant expression type mismatch");
2667 int index = utype->getElementTypeIndex(stype->getContainedType(0));
2668 if (index < 0)
2669 return Error(ID.Loc, "initializer type is not a member of the union");
2670
2671 V = ConstantUnion::get(
2672 utype, cast<Constant>(ID.ConstantVal->getOperand(0)));
2673 return false;
2674 }
2675
2676 return Error(ID.Loc, "constant expression type mismatch");
2677}
2678
Chris Lattnere0787282009-10-27 19:13:16 +00002679
Chris Lattner103ff152009-01-02 07:01:27 +00002680/// FunctionHeader
2681/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2682/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2683/// OptionalAlign OptGC
2684bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2685 // Parse the linkage.
2686 LocTy LinkageLoc = Lex.getLoc();
2687 unsigned Linkage;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002688
Sandeep Patel5838baa2009-09-02 08:44:58 +00002689 unsigned Visibility, RetAttrs;
2690 CallingConv::ID CC;
Owen Anderson35b47072009-08-13 21:58:54 +00002691 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattner103ff152009-01-02 07:01:27 +00002692 LocTy RetTypeLoc = Lex.getLoc();
2693 if (ParseOptionalLinkage(Linkage) ||
2694 ParseOptionalVisibility(Visibility) ||
2695 ParseOptionalCallingConv(CC) ||
2696 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnerc3a8e192009-03-09 04:49:14 +00002697 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattner103ff152009-01-02 07:01:27 +00002698 return true;
2699
2700 // Verify that the linkage is ok.
2701 switch ((GlobalValue::LinkageTypes)Linkage) {
2702 case GlobalValue::ExternalLinkage:
2703 break; // always ok.
2704 case GlobalValue::DLLImportLinkage:
Duncan Sands565f65d2009-03-11 08:08:06 +00002705 case GlobalValue::ExternalWeakLinkage:
Chris Lattner103ff152009-01-02 07:01:27 +00002706 if (isDefine)
2707 return Error(LinkageLoc, "invalid linkage for function definition");
2708 break;
Rafael Espindolaa168fc92009-01-15 20:18:42 +00002709 case GlobalValue::PrivateLinkage:
Bill Wendling41a07852009-07-20 01:03:30 +00002710 case GlobalValue::LinkerPrivateLinkage:
Bill Wendlingf8b61372010-06-29 21:24:00 +00002711 case GlobalValue::LinkerWeakLinkage:
Chris Lattner103ff152009-01-02 07:01:27 +00002712 case GlobalValue::InternalLinkage:
Nick Lewycky22087702009-04-13 07:02:02 +00002713 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands19d161f2009-03-07 15:45:40 +00002714 case GlobalValue::LinkOnceAnyLinkage:
2715 case GlobalValue::LinkOnceODRLinkage:
2716 case GlobalValue::WeakAnyLinkage:
2717 case GlobalValue::WeakODRLinkage:
Chris Lattner103ff152009-01-02 07:01:27 +00002718 case GlobalValue::DLLExportLinkage:
2719 if (!isDefine)
2720 return Error(LinkageLoc, "invalid linkage for function declaration");
2721 break;
2722 case GlobalValue::AppendingLinkage:
Duncan Sandsb95df792009-03-11 20:14:15 +00002723 case GlobalValue::CommonLinkage:
Chris Lattner103ff152009-01-02 07:01:27 +00002724 return Error(LinkageLoc, "invalid function linkage type");
2725 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002726
Chris Lattner7c4a7bf2009-01-05 08:00:30 +00002727 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands1e6932c2010-02-16 14:50:09 +00002728 RetType->isOpaqueTy())
Chris Lattner103ff152009-01-02 07:01:27 +00002729 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002730
Chris Lattner103ff152009-01-02 07:01:27 +00002731 LocTy NameLoc = Lex.getLoc();
Chris Lattner3aa011f2009-02-18 21:48:13 +00002732
2733 std::string FunctionName;
2734 if (Lex.getKind() == lltok::GlobalVar) {
2735 FunctionName = Lex.getStrVal();
2736 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2737 unsigned NameID = Lex.getUIntVal();
2738
2739 if (NameID != NumberedVals.size())
2740 return TokError("function expected to be numbered '%" +
2741 utostr(NumberedVals.size()) + "'");
2742 } else {
2743 return TokError("expected function name");
2744 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002745
Chris Lattner6226fd22009-01-02 08:05:26 +00002746 Lex.Lex();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002747
Chris Lattner6226fd22009-01-02 08:05:26 +00002748 if (Lex.getKind() != lltok::lparen)
Chris Lattner103ff152009-01-02 07:01:27 +00002749 return TokError("expected '(' in function argument list");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002750
Chris Lattner103ff152009-01-02 07:01:27 +00002751 std::vector<ArgInfo> ArgList;
2752 bool isVarArg;
Chris Lattner103ff152009-01-02 07:01:27 +00002753 unsigned FuncAttrs;
Chris Lattner103ff152009-01-02 07:01:27 +00002754 std::string Section;
Chris Lattner103ff152009-01-02 07:01:27 +00002755 unsigned Alignment;
Chris Lattner6226fd22009-01-02 08:05:26 +00002756 std::string GC;
2757
Chris Lattnerd3dcc922009-01-05 18:34:07 +00002758 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner6226fd22009-01-02 08:05:26 +00002759 ParseOptionalAttrs(FuncAttrs, 2) ||
2760 (EatIfPresent(lltok::kw_section) &&
2761 ParseStringConstant(Section)) ||
2762 ParseOptionalAlignment(Alignment) ||
2763 (EatIfPresent(lltok::kw_gc) &&
2764 ParseStringConstant(GC)))
2765 return true;
Chris Lattner103ff152009-01-02 07:01:27 +00002766
2767 // If the alignment was parsed as an attribute, move to the alignment field.
2768 if (FuncAttrs & Attribute::Alignment) {
2769 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2770 FuncAttrs &= ~Attribute::Alignment;
2771 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002772
Chris Lattner103ff152009-01-02 07:01:27 +00002773 // Okay, if we got here, the function is syntactically valid. Convert types
2774 // and do semantic checks.
2775 std::vector<const Type*> ParamTypeList;
2776 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002777 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattner103ff152009-01-02 07:01:27 +00002778 // attributes.
2779 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2780 if (FuncAttrs & ObsoleteFuncAttrs) {
2781 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2782 FuncAttrs &= ~ObsoleteFuncAttrs;
2783 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002784
Chris Lattner103ff152009-01-02 07:01:27 +00002785 if (RetAttrs != Attribute::None)
2786 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002787
Chris Lattner103ff152009-01-02 07:01:27 +00002788 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2789 ParamTypeList.push_back(ArgList[i].Type);
2790 if (ArgList[i].Attrs != Attribute::None)
2791 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2792 }
2793
2794 if (FuncAttrs != Attribute::None)
2795 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2796
2797 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002798
Benjamin Kramerf2052d52010-01-05 13:12:22 +00002799 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002800 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2801
Owen Andersonc3644562009-07-01 23:57:11 +00002802 const FunctionType *FT =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00002803 FunctionType::get(RetType, ParamTypeList, isVarArg);
2804 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattner103ff152009-01-02 07:01:27 +00002805
2806 Fn = 0;
2807 if (!FunctionName.empty()) {
2808 // If this was a definition of a forward reference, remove the definition
2809 // from the forward reference table and fill in the forward ref.
2810 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2811 ForwardRefVals.find(FunctionName);
2812 if (FRVI != ForwardRefVals.end()) {
2813 Fn = M->getFunction(FunctionName);
Chris Lattnerdc04d852010-04-20 04:49:11 +00002814 if (Fn->getType() != PFT)
2815 return Error(FRVI->second.second, "invalid forward reference to "
2816 "function '" + FunctionName + "' with wrong type!");
2817
Chris Lattner103ff152009-01-02 07:01:27 +00002818 ForwardRefVals.erase(FRVI);
2819 } else if ((Fn = M->getFunction(FunctionName))) {
2820 // If this function already exists in the symbol table, then it is
2821 // multiply defined. We accept a few cases for old backwards compat.
2822 // FIXME: Remove this stuff for LLVM 3.0.
2823 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2824 (!Fn->isDeclaration() && isDefine)) {
2825 // If the redefinition has different type or different attributes,
2826 // reject it. If both have bodies, reject it.
2827 return Error(NameLoc, "invalid redefinition of function '" +
2828 FunctionName + "'");
2829 } else if (Fn->isDeclaration()) {
2830 // Make sure to strip off any argument names so we can't get conflicts.
2831 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2832 AI != AE; ++AI)
2833 AI->setName("");
2834 }
Chris Lattner85ee7092009-10-25 23:22:50 +00002835 } else if (M->getNamedValue(FunctionName)) {
2836 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattner103ff152009-01-02 07:01:27 +00002837 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002838
Dan Gohmanf928ad42009-08-29 23:37:49 +00002839 } else {
Chris Lattner103ff152009-01-02 07:01:27 +00002840 // If this is a definition of a forward referenced function, make sure the
2841 // types agree.
2842 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2843 = ForwardRefValIDs.find(NumberedVals.size());
2844 if (I != ForwardRefValIDs.end()) {
2845 Fn = cast<Function>(I->second.first);
2846 if (Fn->getType() != PFT)
2847 return Error(NameLoc, "type of definition and forward reference of '@" +
2848 utostr(NumberedVals.size()) +"' disagree");
2849 ForwardRefValIDs.erase(I);
2850 }
2851 }
2852
2853 if (Fn == 0)
2854 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2855 else // Move the forward-reference to the correct spot in the module.
2856 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2857
2858 if (FunctionName.empty())
2859 NumberedVals.push_back(Fn);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002860
Chris Lattner103ff152009-01-02 07:01:27 +00002861 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2862 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2863 Fn->setCallingConv(CC);
2864 Fn->setAttributes(PAL);
2865 Fn->setAlignment(Alignment);
2866 Fn->setSection(Section);
2867 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002868
Chris Lattner103ff152009-01-02 07:01:27 +00002869 // Add all of the arguments we parsed to the function.
2870 Function::arg_iterator ArgIt = Fn->arg_begin();
2871 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattnerb0689942009-11-26 22:48:23 +00002872 // If we run out of arguments in the Function prototype, exit early.
2873 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2874 if (ArgIt == Fn->arg_end()) break;
2875
Chris Lattner103ff152009-01-02 07:01:27 +00002876 // If the argument has a name, insert it into the argument symbol table.
2877 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002878
Chris Lattner103ff152009-01-02 07:01:27 +00002879 // Set the name, if it conflicted, it will be auto-renamed.
2880 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002881
Chris Lattner103ff152009-01-02 07:01:27 +00002882 if (ArgIt->getNameStr() != ArgList[i].Name)
2883 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2884 ArgList[i].Name + "'");
2885 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002886
Chris Lattner103ff152009-01-02 07:01:27 +00002887 return false;
2888}
2889
2890
2891/// ParseFunctionBody
2892/// ::= '{' BasicBlock+ '}'
2893/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2894///
2895bool LLParser::ParseFunctionBody(Function &Fn) {
2896 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2897 return TokError("expected '{' in function body");
2898 Lex.Lex(); // eat the {.
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002899
Chris Lattner5bb63f12009-10-28 03:39:23 +00002900 int FunctionNumber = -1;
2901 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2902
2903 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002904
Chris Lattner02af7842010-01-09 19:20:07 +00002905 // We need at least one basic block.
2906 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2907 return TokError("function body requires at least one basic block");
2908
Chris Lattner103ff152009-01-02 07:01:27 +00002909 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2910 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002911
Chris Lattner103ff152009-01-02 07:01:27 +00002912 // Eat the }.
2913 Lex.Lex();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002914
Chris Lattner103ff152009-01-02 07:01:27 +00002915 // Verify function is ok.
Chris Lattner5bb63f12009-10-28 03:39:23 +00002916 return PFS.FinishFunction();
Chris Lattner103ff152009-01-02 07:01:27 +00002917}
2918
2919/// ParseBasicBlock
2920/// ::= LabelStr? Instruction*
2921bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2922 // If this basic block starts out with a name, remember it.
2923 std::string Name;
2924 LocTy NameLoc = Lex.getLoc();
2925 if (Lex.getKind() == lltok::LabelStr) {
2926 Name = Lex.getStrVal();
2927 Lex.Lex();
2928 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002929
Chris Lattner103ff152009-01-02 07:01:27 +00002930 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2931 if (BB == 0) return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002932
Chris Lattner103ff152009-01-02 07:01:27 +00002933 std::string NameStr;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002934
Chris Lattner103ff152009-01-02 07:01:27 +00002935 // Parse the instructions in this block until we get a terminator.
2936 Instruction *Inst;
Chris Lattner61643fd2009-12-30 05:48:36 +00002937 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattner103ff152009-01-02 07:01:27 +00002938 do {
2939 // This instruction may have three possibilities for a name: a) none
2940 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2941 LocTy NameLoc = Lex.getLoc();
2942 int NameID = -1;
2943 NameStr = "";
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002944
Chris Lattner103ff152009-01-02 07:01:27 +00002945 if (Lex.getKind() == lltok::LocalVarID) {
2946 NameID = Lex.getUIntVal();
2947 Lex.Lex();
2948 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2949 return true;
2950 } else if (Lex.getKind() == lltok::LocalVar ||
2951 // FIXME: REMOVE IN LLVM 3.0
2952 Lex.getKind() == lltok::StringConstant) {
2953 NameStr = Lex.getStrVal();
2954 Lex.Lex();
2955 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2956 return true;
2957 }
Devang Patel91c79232009-09-17 23:04:48 +00002958
Chris Lattner2c33e0e2009-12-30 05:23:43 +00002959 switch (ParseInstruction(Inst, BB, PFS)) {
2960 default: assert(0 && "Unknown ParseInstruction result!");
2961 case InstError: return true;
2962 case InstNormal:
Chris Lattnerfaff44c2010-04-07 04:08:57 +00002963 BB->getInstList().push_back(Inst);
2964
Chris Lattner2c33e0e2009-12-30 05:23:43 +00002965 // With a normal result, we check to see if the instruction is followed by
2966 // a comma and metadata.
2967 if (EatIfPresent(lltok::comma))
Chris Lattner93fbde12010-04-01 04:51:13 +00002968 if (ParseInstructionMetadata(Inst))
Chris Lattner2c33e0e2009-12-30 05:23:43 +00002969 return true;
2970 break;
2971 case InstExtraComma:
Chris Lattnerfaff44c2010-04-07 04:08:57 +00002972 BB->getInstList().push_back(Inst);
2973
Chris Lattner2c33e0e2009-12-30 05:23:43 +00002974 // If the instruction parser ate an extra comma at the end of it, it
2975 // *must* be followed by metadata.
Chris Lattner93fbde12010-04-01 04:51:13 +00002976 if (ParseInstructionMetadata(Inst))
Chris Lattner2c33e0e2009-12-30 05:23:43 +00002977 return true;
2978 break;
2979 }
Devang Patel91c79232009-09-17 23:04:48 +00002980
Chris Lattner103ff152009-01-02 07:01:27 +00002981 // Set the name on the instruction.
2982 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2983 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002984
Chris Lattner103ff152009-01-02 07:01:27 +00002985 return false;
2986}
2987
2988//===----------------------------------------------------------------------===//
2989// Instruction Parsing.
2990//===----------------------------------------------------------------------===//
2991
2992/// ParseInstruction - Parse one of the many different instructions.
2993///
Chris Lattner2c33e0e2009-12-30 05:23:43 +00002994int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2995 PerFunctionState &PFS) {
Chris Lattner103ff152009-01-02 07:01:27 +00002996 lltok::Kind Token = Lex.getKind();
2997 if (Token == lltok::Eof)
2998 return TokError("found end of file when expecting more instructions");
2999 LocTy Loc = Lex.getLoc();
Chris Lattnerae4da272009-03-01 00:53:13 +00003000 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattner103ff152009-01-02 07:01:27 +00003001 Lex.Lex(); // Eat the keyword.
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003002
Chris Lattner103ff152009-01-02 07:01:27 +00003003 switch (Token) {
3004 default: return Error(Loc, "expected instruction opcode");
3005 // Terminator Instructions.
Owen Anderson35b47072009-08-13 21:58:54 +00003006 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
3007 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattner103ff152009-01-02 07:01:27 +00003008 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3009 case lltok::kw_br: return ParseBr(Inst, PFS);
3010 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattner4c3800f2009-10-28 00:19:10 +00003011 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattner103ff152009-01-02 07:01:27 +00003012 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3013 // Binary Operators.
3014 case lltok::kw_add:
3015 case lltok::kw_sub:
Dan Gohman29392252009-07-27 16:11:46 +00003016 case lltok::kw_mul: {
3017 bool NUW = false;
3018 bool NSW = false;
3019 LocTy ModifierLoc = Lex.getLoc();
3020 if (EatIfPresent(lltok::kw_nuw))
3021 NUW = true;
3022 if (EatIfPresent(lltok::kw_nsw)) {
3023 NSW = true;
3024 if (EatIfPresent(lltok::kw_nuw))
3025 NUW = true;
3026 }
Dan Gohman571834f2010-05-03 22:44:19 +00003027 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
Dan Gohman29392252009-07-27 16:11:46 +00003028 if (!Result) {
Duncan Sandse92dee12010-02-15 16:12:20 +00003029 if (!Inst->getType()->isIntOrIntVectorTy()) {
Dan Gohman29392252009-07-27 16:11:46 +00003030 if (NUW)
3031 return Error(ModifierLoc, "nuw only applies to integer operations");
3032 if (NSW)
3033 return Error(ModifierLoc, "nsw only applies to integer operations");
3034 }
3035 if (NUW)
Dan Gohmanf3a08b82009-09-07 23:54:19 +00003036 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman29392252009-07-27 16:11:46 +00003037 if (NSW)
Dan Gohmanf3a08b82009-09-07 23:54:19 +00003038 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman29392252009-07-27 16:11:46 +00003039 }
3040 return Result;
3041 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00003042 case lltok::kw_fadd:
3043 case lltok::kw_fsub:
3044 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3045
Dan Gohman29392252009-07-27 16:11:46 +00003046 case lltok::kw_sdiv: {
3047 bool Exact = false;
3048 if (EatIfPresent(lltok::kw_exact))
3049 Exact = true;
3050 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3051 if (!Result)
3052 if (Exact)
Dan Gohmanf3a08b82009-09-07 23:54:19 +00003053 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman29392252009-07-27 16:11:46 +00003054 return Result;
3055 }
3056
Chris Lattner103ff152009-01-02 07:01:27 +00003057 case lltok::kw_udiv:
Chris Lattner103ff152009-01-02 07:01:27 +00003058 case lltok::kw_urem:
Chris Lattnerae4da272009-03-01 00:53:13 +00003059 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattner0d5bffc2009-01-05 08:24:46 +00003060 case lltok::kw_fdiv:
Chris Lattnerae4da272009-03-01 00:53:13 +00003061 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattner103ff152009-01-02 07:01:27 +00003062 case lltok::kw_shl:
3063 case lltok::kw_lshr:
3064 case lltok::kw_ashr:
3065 case lltok::kw_and:
3066 case lltok::kw_or:
Chris Lattnerae4da272009-03-01 00:53:13 +00003067 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattner103ff152009-01-02 07:01:27 +00003068 case lltok::kw_icmp:
Nick Lewycky8f5253b2009-07-08 03:04:38 +00003069 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattner103ff152009-01-02 07:01:27 +00003070 // Casts.
3071 case lltok::kw_trunc:
3072 case lltok::kw_zext:
3073 case lltok::kw_sext:
3074 case lltok::kw_fptrunc:
3075 case lltok::kw_fpext:
3076 case lltok::kw_bitcast:
3077 case lltok::kw_uitofp:
3078 case lltok::kw_sitofp:
3079 case lltok::kw_fptoui:
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003080 case lltok::kw_fptosi:
Chris Lattner103ff152009-01-02 07:01:27 +00003081 case lltok::kw_inttoptr:
Chris Lattnerae4da272009-03-01 00:53:13 +00003082 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattner103ff152009-01-02 07:01:27 +00003083 // Other.
3084 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0f928312009-01-05 08:18:44 +00003085 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattner103ff152009-01-02 07:01:27 +00003086 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3087 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3088 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3089 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3090 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3091 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3092 // Memory.
Victor Hernandez6203d9d2009-10-17 00:00:19 +00003093 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3094 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez93946082009-10-24 04:23:03 +00003095 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattner103ff152009-01-02 07:01:27 +00003096 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3097 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3098 case lltok::kw_volatile:
Chris Lattner6226fd22009-01-02 08:05:26 +00003099 if (EatIfPresent(lltok::kw_load))
Chris Lattner103ff152009-01-02 07:01:27 +00003100 return ParseLoad(Inst, PFS, true);
Chris Lattner6226fd22009-01-02 08:05:26 +00003101 else if (EatIfPresent(lltok::kw_store))
Chris Lattner103ff152009-01-02 07:01:27 +00003102 return ParseStore(Inst, PFS, true);
Chris Lattner6226fd22009-01-02 08:05:26 +00003103 else
Chris Lattner103ff152009-01-02 07:01:27 +00003104 return TokError("expected 'load' or 'store'");
Chris Lattner103ff152009-01-02 07:01:27 +00003105 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3106 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3107 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3108 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3109 }
3110}
3111
3112/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3113bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky8f5253b2009-07-08 03:04:38 +00003114 if (Opc == Instruction::FCmp) {
Chris Lattner103ff152009-01-02 07:01:27 +00003115 switch (Lex.getKind()) {
3116 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3117 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3118 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3119 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3120 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3121 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3122 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3123 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3124 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3125 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3126 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3127 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3128 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3129 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3130 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3131 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3132 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3133 }
3134 } else {
3135 switch (Lex.getKind()) {
3136 default: TokError("expected icmp predicate (e.g. 'eq')");
3137 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3138 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3139 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3140 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3141 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3142 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3143 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3144 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3145 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3146 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3147 }
3148 }
3149 Lex.Lex();
3150 return false;
3151}
3152
3153//===----------------------------------------------------------------------===//
3154// Terminator Instructions.
3155//===----------------------------------------------------------------------===//
3156
3157/// ParseRet - Parse a return instruction.
Chris Lattner87c9fb52009-12-29 21:25:40 +00003158/// ::= 'ret' void (',' !dbg, !1)*
3159/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3160/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patel91c79232009-09-17 23:04:48 +00003161/// [[obsolete: LLVM 3.0]]
Chris Lattner2c33e0e2009-12-30 05:23:43 +00003162int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3163 PerFunctionState &PFS) {
Owen Anderson35b47072009-08-13 21:58:54 +00003164 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerc3a8e192009-03-09 04:49:14 +00003165 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003166
Chris Lattner82cdc062009-10-05 05:54:46 +00003167 if (Ty->isVoidTy()) {
Owen Anderson35b47072009-08-13 21:58:54 +00003168 Inst = ReturnInst::Create(Context);
Chris Lattner103ff152009-01-02 07:01:27 +00003169 return false;
3170 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003171
Chris Lattner103ff152009-01-02 07:01:27 +00003172 Value *RV;
3173 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattner103ff152009-01-02 07:01:27 +00003174
Chris Lattner2c33e0e2009-12-30 05:23:43 +00003175 bool ExtraComma = false;
Devang Patel91c79232009-09-17 23:04:48 +00003176 if (EatIfPresent(lltok::comma)) {
Devang Patel17c60df2009-09-29 00:01:14 +00003177 // Parse optional custom metadata, e.g. !dbg
Chris Lattner7e4b4aa2009-12-30 05:02:06 +00003178 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattner2c33e0e2009-12-30 05:23:43 +00003179 ExtraComma = true;
Devang Patel91c79232009-09-17 23:04:48 +00003180 } else {
3181 // The normal case is one return value.
Chris Lattner87c9fb52009-12-29 21:25:40 +00003182 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3183 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patel91c79232009-09-17 23:04:48 +00003184 SmallVector<Value*, 8> RVs;
3185 RVs.push_back(RV);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003186
Devang Patel91c79232009-09-17 23:04:48 +00003187 do {
Devang Patel17c60df2009-09-29 00:01:14 +00003188 // If optional custom metadata, e.g. !dbg is seen then this is the
3189 // end of MRV.
Chris Lattner7e4b4aa2009-12-30 05:02:06 +00003190 if (Lex.getKind() == lltok::MetadataVar)
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003191 break;
3192 if (ParseTypeAndValue(RV, PFS)) return true;
3193 RVs.push_back(RV);
Devang Patel91c79232009-09-17 23:04:48 +00003194 } while (EatIfPresent(lltok::comma));
3195
3196 RV = UndefValue::get(PFS.getFunction().getReturnType());
3197 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003198 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3199 BB->getInstList().push_back(I);
3200 RV = I;
Devang Patel91c79232009-09-17 23:04:48 +00003201 }
Chris Lattner103ff152009-01-02 07:01:27 +00003202 }
3203 }
Devang Patel91c79232009-09-17 23:04:48 +00003204
Owen Anderson35b47072009-08-13 21:58:54 +00003205 Inst = ReturnInst::Create(Context, RV);
Chris Lattner2c33e0e2009-12-30 05:23:43 +00003206 return ExtraComma ? InstExtraComma : InstNormal;
Chris Lattner103ff152009-01-02 07:01:27 +00003207}
3208
3209
3210/// ParseBr
3211/// ::= 'br' TypeAndValue
3212/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3213bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3214 LocTy Loc, Loc2;
Chris Lattnere0787282009-10-27 19:13:16 +00003215 Value *Op0;
3216 BasicBlock *Op1, *Op2;
Chris Lattner103ff152009-01-02 07:01:27 +00003217 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003218
Chris Lattner103ff152009-01-02 07:01:27 +00003219 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3220 Inst = BranchInst::Create(BB);
3221 return false;
3222 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003223
Owen Anderson35b47072009-08-13 21:58:54 +00003224 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattner103ff152009-01-02 07:01:27 +00003225 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003226
Chris Lattner103ff152009-01-02 07:01:27 +00003227 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnere0787282009-10-27 19:13:16 +00003228 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattner103ff152009-01-02 07:01:27 +00003229 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnere0787282009-10-27 19:13:16 +00003230 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattner103ff152009-01-02 07:01:27 +00003231 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003232
Chris Lattnere0787282009-10-27 19:13:16 +00003233 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattner103ff152009-01-02 07:01:27 +00003234 return false;
3235}
3236
3237/// ParseSwitch
3238/// Instruction
3239/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3240/// JumpTable
3241/// ::= (TypeAndValue ',' TypeAndValue)*
3242bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3243 LocTy CondLoc, BBLoc;
Chris Lattnere0787282009-10-27 19:13:16 +00003244 Value *Cond;
3245 BasicBlock *DefaultBB;
Chris Lattner103ff152009-01-02 07:01:27 +00003246 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3247 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnere0787282009-10-27 19:13:16 +00003248 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattner103ff152009-01-02 07:01:27 +00003249 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3250 return true;
3251
Duncan Sands10343d92010-02-16 11:11:14 +00003252 if (!Cond->getType()->isIntegerTy())
Chris Lattner103ff152009-01-02 07:01:27 +00003253 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003254
Chris Lattner103ff152009-01-02 07:01:27 +00003255 // Parse the jump table pairs.
3256 SmallPtrSet<Value*, 32> SeenCases;
3257 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3258 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnere0787282009-10-27 19:13:16 +00003259 Value *Constant;
3260 BasicBlock *DestBB;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003261
Chris Lattner103ff152009-01-02 07:01:27 +00003262 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3263 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnere0787282009-10-27 19:13:16 +00003264 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattner103ff152009-01-02 07:01:27 +00003265 return true;
Chris Lattnere0787282009-10-27 19:13:16 +00003266
Chris Lattner103ff152009-01-02 07:01:27 +00003267 if (!SeenCases.insert(Constant))
3268 return Error(CondLoc, "duplicate case value in switch");
3269 if (!isa<ConstantInt>(Constant))
3270 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003271
Chris Lattnere0787282009-10-27 19:13:16 +00003272 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattner103ff152009-01-02 07:01:27 +00003273 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003274
Chris Lattner103ff152009-01-02 07:01:27 +00003275 Lex.Lex(); // Eat the ']'.
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003276
Chris Lattnere0787282009-10-27 19:13:16 +00003277 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattner103ff152009-01-02 07:01:27 +00003278 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3279 SI->addCase(Table[i].first, Table[i].second);
3280 Inst = SI;
3281 return false;
3282}
3283
Chris Lattner4c3800f2009-10-28 00:19:10 +00003284/// ParseIndirectBr
Chris Lattnere0787282009-10-27 19:13:16 +00003285/// Instruction
Chris Lattner4c3800f2009-10-28 00:19:10 +00003286/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3287bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnere0787282009-10-27 19:13:16 +00003288 LocTy AddrLoc;
3289 Value *Address;
3290 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattner4c3800f2009-10-28 00:19:10 +00003291 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3292 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnere0787282009-10-27 19:13:16 +00003293 return true;
3294
Duncan Sands10343d92010-02-16 11:11:14 +00003295 if (!Address->getType()->isPointerTy())
Chris Lattner4c3800f2009-10-28 00:19:10 +00003296 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnere0787282009-10-27 19:13:16 +00003297
3298 // Parse the destination list.
3299 SmallVector<BasicBlock*, 16> DestList;
3300
3301 if (Lex.getKind() != lltok::rsquare) {
3302 BasicBlock *DestBB;
3303 if (ParseTypeAndBasicBlock(DestBB, PFS))
3304 return true;
3305 DestList.push_back(DestBB);
3306
3307 while (EatIfPresent(lltok::comma)) {
3308 if (ParseTypeAndBasicBlock(DestBB, PFS))
3309 return true;
3310 DestList.push_back(DestBB);
3311 }
3312 }
3313
3314 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3315 return true;
3316
Chris Lattner4c3800f2009-10-28 00:19:10 +00003317 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnere0787282009-10-27 19:13:16 +00003318 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3319 IBI->addDestination(DestList[i]);
3320 Inst = IBI;
3321 return false;
3322}
3323
3324
Chris Lattner103ff152009-01-02 07:01:27 +00003325/// ParseInvoke
3326/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3327/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3328bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3329 LocTy CallLoc = Lex.getLoc();
Sandeep Patel5838baa2009-09-02 08:44:58 +00003330 unsigned RetAttrs, FnAttrs;
3331 CallingConv::ID CC;
Owen Anderson35b47072009-08-13 21:58:54 +00003332 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattner103ff152009-01-02 07:01:27 +00003333 LocTy RetTypeLoc;
3334 ValID CalleeID;
3335 SmallVector<ParamInfo, 16> ArgList;
3336
Chris Lattnere0787282009-10-27 19:13:16 +00003337 BasicBlock *NormalBB, *UnwindBB;
Chris Lattner103ff152009-01-02 07:01:27 +00003338 if (ParseOptionalCallingConv(CC) ||
3339 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnerc3a8e192009-03-09 04:49:14 +00003340 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattner103ff152009-01-02 07:01:27 +00003341 ParseValID(CalleeID) ||
3342 ParseParameterList(ArgList, PFS) ||
3343 ParseOptionalAttrs(FnAttrs, 2) ||
3344 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnere0787282009-10-27 19:13:16 +00003345 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattner103ff152009-01-02 07:01:27 +00003346 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnere0787282009-10-27 19:13:16 +00003347 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattner103ff152009-01-02 07:01:27 +00003348 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003349
Chris Lattner103ff152009-01-02 07:01:27 +00003350 // If RetType is a non-function pointer type, then this is the short syntax
3351 // for the call, which means that RetType is just the return type. Infer the
3352 // rest of the function argument types from the arguments that are present.
3353 const PointerType *PFTy = 0;
3354 const FunctionType *Ty = 0;
3355 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3356 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3357 // Pull out the types of all of the arguments...
3358 std::vector<const Type*> ParamTypes;
3359 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3360 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003361
Chris Lattner103ff152009-01-02 07:01:27 +00003362 if (!FunctionType::isValidReturnType(RetType))
3363 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003364
Owen Anderson6b6e2d92009-07-29 22:17:13 +00003365 Ty = FunctionType::get(RetType, ParamTypes, false);
3366 PFTy = PointerType::getUnqual(Ty);
Chris Lattner103ff152009-01-02 07:01:27 +00003367 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003368
Chris Lattner103ff152009-01-02 07:01:27 +00003369 // Look up the callee.
3370 Value *Callee;
Victor Hernandez84793eb2010-01-11 22:31:58 +00003371 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003372
Chris Lattner103ff152009-01-02 07:01:27 +00003373 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3374 // function attributes.
3375 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3376 if (FnAttrs & ObsoleteFuncAttrs) {
3377 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3378 FnAttrs &= ~ObsoleteFuncAttrs;
3379 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003380
Chris Lattner103ff152009-01-02 07:01:27 +00003381 // Set up the Attributes for the function.
3382 SmallVector<AttributeWithIndex, 8> Attrs;
3383 if (RetAttrs != Attribute::None)
3384 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003385
Chris Lattner103ff152009-01-02 07:01:27 +00003386 SmallVector<Value*, 8> Args;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003387
Chris Lattner103ff152009-01-02 07:01:27 +00003388 // Loop through FunctionType's arguments and ensure they are specified
3389 // correctly. Also, gather any parameter attributes.
3390 FunctionType::param_iterator I = Ty->param_begin();
3391 FunctionType::param_iterator E = Ty->param_end();
3392 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3393 const Type *ExpectedTy = 0;
3394 if (I != E) {
3395 ExpectedTy = *I++;
3396 } else if (!Ty->isVarArg()) {
3397 return Error(ArgList[i].Loc, "too many arguments specified");
3398 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003399
Chris Lattner103ff152009-01-02 07:01:27 +00003400 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3401 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3402 ExpectedTy->getDescription() + "'");
3403 Args.push_back(ArgList[i].V);
3404 if (ArgList[i].Attrs != Attribute::None)
3405 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3406 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003407
Chris Lattner103ff152009-01-02 07:01:27 +00003408 if (I != E)
3409 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003410
Chris Lattner103ff152009-01-02 07:01:27 +00003411 if (FnAttrs != Attribute::None)
3412 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003413
Chris Lattner103ff152009-01-02 07:01:27 +00003414 // Finish off the Attributes and check them
3415 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003416
Chris Lattnere0787282009-10-27 19:13:16 +00003417 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattner103ff152009-01-02 07:01:27 +00003418 Args.begin(), Args.end());
3419 II->setCallingConv(CC);
3420 II->setAttributes(PAL);
3421 Inst = II;
3422 return false;
3423}
3424
3425
3426
3427//===----------------------------------------------------------------------===//
3428// Binary Operators.
3429//===----------------------------------------------------------------------===//
3430
3431/// ParseArithmetic
Chris Lattner0d5bffc2009-01-05 08:24:46 +00003432/// ::= ArithmeticOps TypeAndValue ',' Value
3433///
3434/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3435/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattner103ff152009-01-02 07:01:27 +00003436bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattner0d5bffc2009-01-05 08:24:46 +00003437 unsigned Opc, unsigned OperandType) {
Chris Lattner103ff152009-01-02 07:01:27 +00003438 LocTy Loc; Value *LHS, *RHS;
3439 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3440 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3441 ParseValue(LHS->getType(), RHS, PFS))
3442 return true;
3443
Chris Lattner0d5bffc2009-01-05 08:24:46 +00003444 bool Valid;
3445 switch (OperandType) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003446 default: llvm_unreachable("Unknown operand type!");
Chris Lattner0d5bffc2009-01-05 08:24:46 +00003447 case 0: // int or FP.
Duncan Sandse92dee12010-02-15 16:12:20 +00003448 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3449 LHS->getType()->isFPOrFPVectorTy();
Chris Lattner0d5bffc2009-01-05 08:24:46 +00003450 break;
Duncan Sandse92dee12010-02-15 16:12:20 +00003451 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3452 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattner0d5bffc2009-01-05 08:24:46 +00003453 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003454
Chris Lattner0d5bffc2009-01-05 08:24:46 +00003455 if (!Valid)
3456 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003457
Chris Lattner103ff152009-01-02 07:01:27 +00003458 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3459 return false;
3460}
3461
3462/// ParseLogical
3463/// ::= ArithmeticOps TypeAndValue ',' Value {
3464bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3465 unsigned Opc) {
3466 LocTy Loc; Value *LHS, *RHS;
3467 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3468 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3469 ParseValue(LHS->getType(), RHS, PFS))
3470 return true;
3471
Duncan Sandse92dee12010-02-15 16:12:20 +00003472 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattner103ff152009-01-02 07:01:27 +00003473 return Error(Loc,"instruction requires integer or integer vector operands");
3474
3475 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3476 return false;
3477}
3478
3479
3480/// ParseCompare
3481/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3482/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattner103ff152009-01-02 07:01:27 +00003483bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3484 unsigned Opc) {
3485 // Parse the integer/fp comparison predicate.
3486 LocTy Loc;
3487 unsigned Pred;
3488 Value *LHS, *RHS;
3489 if (ParseCmpPredicate(Pred, Opc) ||
3490 ParseTypeAndValue(LHS, Loc, PFS) ||
3491 ParseToken(lltok::comma, "expected ',' after compare value") ||
3492 ParseValue(LHS->getType(), RHS, PFS))
3493 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003494
Chris Lattner103ff152009-01-02 07:01:27 +00003495 if (Opc == Instruction::FCmp) {
Duncan Sandse92dee12010-02-15 16:12:20 +00003496 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattner103ff152009-01-02 07:01:27 +00003497 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmane6803b82009-08-25 23:17:54 +00003498 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky8f5253b2009-07-08 03:04:38 +00003499 } else {
3500 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandse92dee12010-02-15 16:12:20 +00003501 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands10343d92010-02-16 11:11:14 +00003502 !LHS->getType()->isPointerTy())
Chris Lattner103ff152009-01-02 07:01:27 +00003503 return Error(Loc, "icmp requires integer operands");
Dan Gohmane6803b82009-08-25 23:17:54 +00003504 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattner103ff152009-01-02 07:01:27 +00003505 }
3506 return false;
3507}
3508
3509//===----------------------------------------------------------------------===//
3510// Other Instructions.
3511//===----------------------------------------------------------------------===//
3512
3513
3514/// ParseCast
3515/// ::= CastOpc TypeAndValue 'to' Type
3516bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3517 unsigned Opc) {
3518 LocTy Loc; Value *Op;
Owen Anderson35b47072009-08-13 21:58:54 +00003519 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattner103ff152009-01-02 07:01:27 +00003520 if (ParseTypeAndValue(Op, Loc, PFS) ||
3521 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3522 ParseType(DestTy))
3523 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003524
Chris Lattnerae4da272009-03-01 00:53:13 +00003525 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3526 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattner103ff152009-01-02 07:01:27 +00003527 return Error(Loc, "invalid cast opcode for cast from '" +
3528 Op->getType()->getDescription() + "' to '" +
3529 DestTy->getDescription() + "'");
Chris Lattnerae4da272009-03-01 00:53:13 +00003530 }
Chris Lattner103ff152009-01-02 07:01:27 +00003531 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3532 return false;
3533}
3534
3535/// ParseSelect
3536/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3537bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3538 LocTy Loc;
3539 Value *Op0, *Op1, *Op2;
3540 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3541 ParseToken(lltok::comma, "expected ',' after select condition") ||
3542 ParseTypeAndValue(Op1, PFS) ||
3543 ParseToken(lltok::comma, "expected ',' after select value") ||
3544 ParseTypeAndValue(Op2, PFS))
3545 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003546
Chris Lattner103ff152009-01-02 07:01:27 +00003547 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3548 return Error(Loc, Reason);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003549
Chris Lattner103ff152009-01-02 07:01:27 +00003550 Inst = SelectInst::Create(Op0, Op1, Op2);
3551 return false;
3552}
3553
Chris Lattner0f928312009-01-05 08:18:44 +00003554/// ParseVA_Arg
3555/// ::= 'va_arg' TypeAndValue ',' Type
3556bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner103ff152009-01-02 07:01:27 +00003557 Value *Op;
Owen Anderson35b47072009-08-13 21:58:54 +00003558 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0f928312009-01-05 08:18:44 +00003559 LocTy TypeLoc;
Chris Lattner103ff152009-01-02 07:01:27 +00003560 if (ParseTypeAndValue(Op, PFS) ||
3561 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0f928312009-01-05 08:18:44 +00003562 ParseType(EltTy, TypeLoc))
Chris Lattner103ff152009-01-02 07:01:27 +00003563 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003564
Chris Lattner0f928312009-01-05 08:18:44 +00003565 if (!EltTy->isFirstClassType())
3566 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattner103ff152009-01-02 07:01:27 +00003567
3568 Inst = new VAArgInst(Op, EltTy);
3569 return false;
3570}
3571
3572/// ParseExtractElement
3573/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3574bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3575 LocTy Loc;
3576 Value *Op0, *Op1;
3577 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3578 ParseToken(lltok::comma, "expected ',' after extract value") ||
3579 ParseTypeAndValue(Op1, PFS))
3580 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003581
Chris Lattner103ff152009-01-02 07:01:27 +00003582 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3583 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003584
Eric Christopher1ba36872009-07-25 02:28:41 +00003585 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattner103ff152009-01-02 07:01:27 +00003586 return false;
3587}
3588
3589/// ParseInsertElement
3590/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3591bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3592 LocTy Loc;
3593 Value *Op0, *Op1, *Op2;
3594 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3595 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3596 ParseTypeAndValue(Op1, PFS) ||
3597 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3598 ParseTypeAndValue(Op2, PFS))
3599 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003600
Chris Lattner103ff152009-01-02 07:01:27 +00003601 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher65b39662009-07-23 01:01:32 +00003602 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003603
Chris Lattner103ff152009-01-02 07:01:27 +00003604 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3605 return false;
3606}
3607
3608/// ParseShuffleVector
3609/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3610bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3611 LocTy Loc;
3612 Value *Op0, *Op1, *Op2;
3613 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3614 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3615 ParseTypeAndValue(Op1, PFS) ||
3616 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3617 ParseTypeAndValue(Op2, PFS))
3618 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003619
Chris Lattner103ff152009-01-02 07:01:27 +00003620 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3621 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003622
Chris Lattner103ff152009-01-02 07:01:27 +00003623 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3624 return false;
3625}
3626
3627/// ParsePHI
Chris Lattner66f2cb92009-10-18 05:27:44 +00003628/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattner993c02d2009-12-30 05:27:33 +00003629int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson35b47072009-08-13 21:58:54 +00003630 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattner103ff152009-01-02 07:01:27 +00003631 Value *Op0, *Op1;
3632 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003633
Chris Lattner103ff152009-01-02 07:01:27 +00003634 if (ParseType(Ty) ||
3635 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3636 ParseValue(Ty, Op0, PFS) ||
3637 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson35b47072009-08-13 21:58:54 +00003638 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattner103ff152009-01-02 07:01:27 +00003639 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3640 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003641
Chris Lattner993c02d2009-12-30 05:27:33 +00003642 bool AteExtraComma = false;
Chris Lattner103ff152009-01-02 07:01:27 +00003643 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3644 while (1) {
3645 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003646
Chris Lattner6226fd22009-01-02 08:05:26 +00003647 if (!EatIfPresent(lltok::comma))
Chris Lattner103ff152009-01-02 07:01:27 +00003648 break;
3649
Chris Lattner993c02d2009-12-30 05:27:33 +00003650 if (Lex.getKind() == lltok::MetadataVar) {
3651 AteExtraComma = true;
Devang Patel1a2ffff2009-10-16 18:45:49 +00003652 break;
Chris Lattner993c02d2009-12-30 05:27:33 +00003653 }
Devang Patel1a2ffff2009-10-16 18:45:49 +00003654
Chris Lattner6226fd22009-01-02 08:05:26 +00003655 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattner103ff152009-01-02 07:01:27 +00003656 ParseValue(Ty, Op0, PFS) ||
3657 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson35b47072009-08-13 21:58:54 +00003658 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattner103ff152009-01-02 07:01:27 +00003659 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3660 return true;
3661 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003662
Chris Lattner103ff152009-01-02 07:01:27 +00003663 if (!Ty->isFirstClassType())
3664 return Error(TypeLoc, "phi node must have first class type");
3665
3666 PHINode *PN = PHINode::Create(Ty);
3667 PN->reserveOperandSpace(PHIVals.size());
3668 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3669 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3670 Inst = PN;
Chris Lattner993c02d2009-12-30 05:27:33 +00003671 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattner103ff152009-01-02 07:01:27 +00003672}
3673
3674/// ParseCall
3675/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3676/// ParameterList OptionalAttrs
3677bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3678 bool isTail) {
Sandeep Patel5838baa2009-09-02 08:44:58 +00003679 unsigned RetAttrs, FnAttrs;
3680 CallingConv::ID CC;
Owen Anderson35b47072009-08-13 21:58:54 +00003681 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattner103ff152009-01-02 07:01:27 +00003682 LocTy RetTypeLoc;
3683 ValID CalleeID;
3684 SmallVector<ParamInfo, 16> ArgList;
3685 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003686
Chris Lattner103ff152009-01-02 07:01:27 +00003687 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3688 ParseOptionalCallingConv(CC) ||
3689 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnerc3a8e192009-03-09 04:49:14 +00003690 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattner103ff152009-01-02 07:01:27 +00003691 ParseValID(CalleeID) ||
3692 ParseParameterList(ArgList, PFS) ||
3693 ParseOptionalAttrs(FnAttrs, 2))
3694 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003695
Chris Lattner103ff152009-01-02 07:01:27 +00003696 // If RetType is a non-function pointer type, then this is the short syntax
3697 // for the call, which means that RetType is just the return type. Infer the
3698 // rest of the function argument types from the arguments that are present.
3699 const PointerType *PFTy = 0;
3700 const FunctionType *Ty = 0;
3701 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3702 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3703 // Pull out the types of all of the arguments...
3704 std::vector<const Type*> ParamTypes;
3705 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3706 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003707
Chris Lattner103ff152009-01-02 07:01:27 +00003708 if (!FunctionType::isValidReturnType(RetType))
3709 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003710
Owen Anderson6b6e2d92009-07-29 22:17:13 +00003711 Ty = FunctionType::get(RetType, ParamTypes, false);
3712 PFTy = PointerType::getUnqual(Ty);
Chris Lattner103ff152009-01-02 07:01:27 +00003713 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003714
Chris Lattner103ff152009-01-02 07:01:27 +00003715 // Look up the callee.
3716 Value *Callee;
Victor Hernandez84793eb2010-01-11 22:31:58 +00003717 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003718
Chris Lattner103ff152009-01-02 07:01:27 +00003719 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3720 // function attributes.
3721 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3722 if (FnAttrs & ObsoleteFuncAttrs) {
3723 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3724 FnAttrs &= ~ObsoleteFuncAttrs;
3725 }
3726
3727 // Set up the Attributes for the function.
3728 SmallVector<AttributeWithIndex, 8> Attrs;
3729 if (RetAttrs != Attribute::None)
3730 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003731
Chris Lattner103ff152009-01-02 07:01:27 +00003732 SmallVector<Value*, 8> Args;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003733
Chris Lattner103ff152009-01-02 07:01:27 +00003734 // Loop through FunctionType's arguments and ensure they are specified
3735 // correctly. Also, gather any parameter attributes.
3736 FunctionType::param_iterator I = Ty->param_begin();
3737 FunctionType::param_iterator E = Ty->param_end();
3738 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3739 const Type *ExpectedTy = 0;
3740 if (I != E) {
3741 ExpectedTy = *I++;
3742 } else if (!Ty->isVarArg()) {
3743 return Error(ArgList[i].Loc, "too many arguments specified");
3744 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003745
Chris Lattner103ff152009-01-02 07:01:27 +00003746 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3747 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3748 ExpectedTy->getDescription() + "'");
3749 Args.push_back(ArgList[i].V);
3750 if (ArgList[i].Attrs != Attribute::None)
3751 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3752 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003753
Chris Lattner103ff152009-01-02 07:01:27 +00003754 if (I != E)
3755 return Error(CallLoc, "not enough parameters specified for call");
3756
3757 if (FnAttrs != Attribute::None)
3758 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3759
3760 // Finish off the Attributes and check them
3761 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003762
Chris Lattner103ff152009-01-02 07:01:27 +00003763 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3764 CI->setTailCall(isTail);
3765 CI->setCallingConv(CC);
3766 CI->setAttributes(PAL);
3767 Inst = CI;
3768 return false;
3769}
3770
3771//===----------------------------------------------------------------------===//
3772// Memory Instructions.
3773//===----------------------------------------------------------------------===//
3774
3775/// ParseAlloc
Devang Patel91c79232009-09-17 23:04:48 +00003776/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3777/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattner4db8a012009-12-30 05:44:30 +00003778int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3779 BasicBlock* BB, bool isAlloca) {
Owen Anderson35b47072009-08-13 21:58:54 +00003780 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattner103ff152009-01-02 07:01:27 +00003781 Value *Size = 0;
Chris Lattner0ffa08f2009-07-02 23:08:13 +00003782 LocTy SizeLoc;
Chris Lattner103ff152009-01-02 07:01:27 +00003783 unsigned Alignment = 0;
Chris Lattner6226fd22009-01-02 08:05:26 +00003784 if (ParseType(Ty)) return true;
Chris Lattner103ff152009-01-02 07:01:27 +00003785
Chris Lattner4db8a012009-12-30 05:44:30 +00003786 bool AteExtraComma = false;
Chris Lattner6226fd22009-01-02 08:05:26 +00003787 if (EatIfPresent(lltok::comma)) {
Chris Lattner4db8a012009-12-30 05:44:30 +00003788 if (Lex.getKind() == lltok::kw_align) {
3789 if (ParseOptionalAlignment(Alignment)) return true;
3790 } else if (Lex.getKind() == lltok::MetadataVar) {
3791 AteExtraComma = true;
Devang Patel91c79232009-09-17 23:04:48 +00003792 } else {
Chris Lattner4db8a012009-12-30 05:44:30 +00003793 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3794 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3795 return true;
Chris Lattner103ff152009-01-02 07:01:27 +00003796 }
3797 }
3798
Dan Gohman3eb67d52010-05-28 01:14:11 +00003799 if (Size && !Size->getType()->isIntegerTy())
3800 return Error(SizeLoc, "element count must have integer type");
Chris Lattner103ff152009-01-02 07:01:27 +00003801
Victor Hernandez67439f02009-10-21 19:11:40 +00003802 if (isAlloca) {
Owen Anderson140166d2009-07-15 23:53:25 +00003803 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattner4db8a012009-12-30 05:44:30 +00003804 return AteExtraComma ? InstExtraComma : InstNormal;
Victor Hernandez6203d9d2009-10-17 00:00:19 +00003805 }
Victor Hernandez67439f02009-10-21 19:11:40 +00003806
3807 // Autoupgrade old malloc instruction to malloc call.
3808 // FIXME: Remove in LLVM 3.0.
Dan Gohman3eb67d52010-05-28 01:14:11 +00003809 if (Size && !Size->getType()->isIntegerTy(32))
3810 return Error(SizeLoc, "element count must be i32");
Victor Hernandez67439f02009-10-21 19:11:40 +00003811 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez955449e2009-11-07 00:16:28 +00003812 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3813 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
Victor Hernandez67439f02009-10-21 19:11:40 +00003814 if (!MallocF)
3815 // Prototype malloc as "void *(int32)".
3816 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez9167ebd2009-10-23 00:59:10 +00003817 MallocF = cast<Function>(
3818 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez955449e2009-11-07 00:16:28 +00003819 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
Chris Lattner4db8a012009-12-30 05:44:30 +00003820return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattner103ff152009-01-02 07:01:27 +00003821}
3822
3823/// ParseFree
3824/// ::= 'free' TypeAndValue
Victor Hernandez93946082009-10-24 04:23:03 +00003825bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3826 BasicBlock* BB) {
Chris Lattner103ff152009-01-02 07:01:27 +00003827 Value *Val; LocTy Loc;
3828 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Duncan Sands10343d92010-02-16 11:11:14 +00003829 if (!Val->getType()->isPointerTy())
Chris Lattner103ff152009-01-02 07:01:27 +00003830 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez93946082009-10-24 04:23:03 +00003831 Inst = CallInst::CreateFree(Val, BB);
Chris Lattner103ff152009-01-02 07:01:27 +00003832 return false;
3833}
3834
3835/// ParseLoad
Devang Patel91c79232009-09-17 23:04:48 +00003836/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattner4db8a012009-12-30 05:44:30 +00003837int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3838 bool isVolatile) {
Chris Lattner103ff152009-01-02 07:01:27 +00003839 Value *Val; LocTy Loc;
Devang Patel91c79232009-09-17 23:04:48 +00003840 unsigned Alignment = 0;
Chris Lattner4db8a012009-12-30 05:44:30 +00003841 bool AteExtraComma = false;
3842 if (ParseTypeAndValue(Val, Loc, PFS) ||
3843 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3844 return true;
Chris Lattner103ff152009-01-02 07:01:27 +00003845
Duncan Sands10343d92010-02-16 11:11:14 +00003846 if (!Val->getType()->isPointerTy() ||
Chris Lattner103ff152009-01-02 07:01:27 +00003847 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3848 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003849
Chris Lattner103ff152009-01-02 07:01:27 +00003850 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattner4db8a012009-12-30 05:44:30 +00003851 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattner103ff152009-01-02 07:01:27 +00003852}
3853
3854/// ParseStore
Dan Gohman9e1657f2009-06-14 23:30:43 +00003855/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattner4db8a012009-12-30 05:44:30 +00003856int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3857 bool isVolatile) {
Chris Lattner103ff152009-01-02 07:01:27 +00003858 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patel91c79232009-09-17 23:04:48 +00003859 unsigned Alignment = 0;
Chris Lattner4db8a012009-12-30 05:44:30 +00003860 bool AteExtraComma = false;
Chris Lattner103ff152009-01-02 07:01:27 +00003861 if (ParseTypeAndValue(Val, Loc, PFS) ||
3862 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattner4db8a012009-12-30 05:44:30 +00003863 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3864 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattner103ff152009-01-02 07:01:27 +00003865 return true;
Devang Patel91c79232009-09-17 23:04:48 +00003866
Duncan Sands10343d92010-02-16 11:11:14 +00003867 if (!Ptr->getType()->isPointerTy())
Chris Lattner103ff152009-01-02 07:01:27 +00003868 return Error(PtrLoc, "store operand must be a pointer");
3869 if (!Val->getType()->isFirstClassType())
3870 return Error(Loc, "store operand must be a first class value");
3871 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3872 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003873
Chris Lattner103ff152009-01-02 07:01:27 +00003874 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattner4db8a012009-12-30 05:44:30 +00003875 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattner103ff152009-01-02 07:01:27 +00003876}
3877
3878/// ParseGetResult
Dan Gohman9e1657f2009-06-14 23:30:43 +00003879/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattner103ff152009-01-02 07:01:27 +00003880/// FIXME: Remove support for getresult in LLVM 3.0
3881bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3882 Value *Val; LocTy ValLoc, EltLoc;
3883 unsigned Element;
3884 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3885 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner6226fd22009-01-02 08:05:26 +00003886 ParseUInt32(Element, EltLoc))
Chris Lattner103ff152009-01-02 07:01:27 +00003887 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003888
Duncan Sands10343d92010-02-16 11:11:14 +00003889 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
Chris Lattner103ff152009-01-02 07:01:27 +00003890 return Error(ValLoc, "getresult inst requires an aggregate operand");
3891 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3892 return Error(EltLoc, "invalid getresult index for value");
3893 Inst = ExtractValueInst::Create(Val, Element);
3894 return false;
3895}
3896
3897/// ParseGetElementPtr
Dan Gohman106b2ae2009-07-27 21:53:46 +00003898/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattner993c02d2009-12-30 05:27:33 +00003899int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner103ff152009-01-02 07:01:27 +00003900 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohman106b2ae2009-07-27 21:53:46 +00003901
Dan Gohmand0fd20d2009-07-29 15:58:36 +00003902 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman106b2ae2009-07-27 21:53:46 +00003903
Chris Lattner6226fd22009-01-02 08:05:26 +00003904 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003905
Duncan Sands10343d92010-02-16 11:11:14 +00003906 if (!Ptr->getType()->isPointerTy())
Chris Lattner103ff152009-01-02 07:01:27 +00003907 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003908
Chris Lattner103ff152009-01-02 07:01:27 +00003909 SmallVector<Value*, 16> Indices;
Chris Lattner993c02d2009-12-30 05:27:33 +00003910 bool AteExtraComma = false;
Chris Lattner6226fd22009-01-02 08:05:26 +00003911 while (EatIfPresent(lltok::comma)) {
Chris Lattner993c02d2009-12-30 05:27:33 +00003912 if (Lex.getKind() == lltok::MetadataVar) {
3913 AteExtraComma = true;
Devang Patel88900a02009-10-13 18:49:55 +00003914 break;
Chris Lattner993c02d2009-12-30 05:27:33 +00003915 }
Chris Lattner6226fd22009-01-02 08:05:26 +00003916 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands10343d92010-02-16 11:11:14 +00003917 if (!Val->getType()->isIntegerTy())
Chris Lattner103ff152009-01-02 07:01:27 +00003918 return Error(EltLoc, "getelementptr index must be an integer");
3919 Indices.push_back(Val);
3920 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003921
Chris Lattner103ff152009-01-02 07:01:27 +00003922 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3923 Indices.begin(), Indices.end()))
3924 return Error(Loc, "invalid getelementptr indices");
3925 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohman106b2ae2009-07-27 21:53:46 +00003926 if (InBounds)
Dan Gohmanf3a08b82009-09-07 23:54:19 +00003927 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattner993c02d2009-12-30 05:27:33 +00003928 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattner103ff152009-01-02 07:01:27 +00003929}
3930
3931/// ParseExtractValue
3932/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattner993c02d2009-12-30 05:27:33 +00003933int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner103ff152009-01-02 07:01:27 +00003934 Value *Val; LocTy Loc;
3935 SmallVector<unsigned, 4> Indices;
Chris Lattner993c02d2009-12-30 05:27:33 +00003936 bool AteExtraComma;
Chris Lattner103ff152009-01-02 07:01:27 +00003937 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattner993c02d2009-12-30 05:27:33 +00003938 ParseIndexList(Indices, AteExtraComma))
Chris Lattner103ff152009-01-02 07:01:27 +00003939 return true;
3940
Chris Lattnerd5d51722010-02-12 20:49:41 +00003941 if (!Val->getType()->isAggregateType())
3942 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattner103ff152009-01-02 07:01:27 +00003943
3944 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3945 Indices.end()))
3946 return Error(Loc, "invalid indices for extractvalue");
3947 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattner993c02d2009-12-30 05:27:33 +00003948 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattner103ff152009-01-02 07:01:27 +00003949}
3950
3951/// ParseInsertValue
3952/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattner993c02d2009-12-30 05:27:33 +00003953int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner103ff152009-01-02 07:01:27 +00003954 Value *Val0, *Val1; LocTy Loc0, Loc1;
3955 SmallVector<unsigned, 4> Indices;
Chris Lattner993c02d2009-12-30 05:27:33 +00003956 bool AteExtraComma;
Chris Lattner103ff152009-01-02 07:01:27 +00003957 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3958 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3959 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattner993c02d2009-12-30 05:27:33 +00003960 ParseIndexList(Indices, AteExtraComma))
Chris Lattner103ff152009-01-02 07:01:27 +00003961 return true;
Chris Lattner7c3b4082009-12-30 05:14:00 +00003962
Chris Lattnerd5d51722010-02-12 20:49:41 +00003963 if (!Val0->getType()->isAggregateType())
3964 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00003965
Chris Lattner103ff152009-01-02 07:01:27 +00003966 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3967 Indices.end()))
3968 return Error(Loc0, "invalid indices for insertvalue");
3969 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattner993c02d2009-12-30 05:27:33 +00003970 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattner103ff152009-01-02 07:01:27 +00003971}
Nick Lewycky4dcf8102009-04-04 07:22:01 +00003972
3973//===----------------------------------------------------------------------===//
3974// Embedded metadata.
3975//===----------------------------------------------------------------------===//
3976
3977/// ParseMDNodeVector
Nick Lewycky117f4382009-05-10 20:57:05 +00003978/// ::= Element (',' Element)*
3979/// Element
3980/// ::= 'null' | TypeAndValue
Victor Hernandezbf454d22010-01-05 22:22:14 +00003981bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandezc4261242010-01-10 07:14:18 +00003982 PerFunctionState *PFS) {
Nick Lewycky4dcf8102009-04-04 07:22:01 +00003983 do {
Chris Lattner8b07fb52009-12-30 04:42:57 +00003984 // Null is a special case since it is typeless.
3985 if (EatIfPresent(lltok::kw_null)) {
3986 Elts.push_back(0);
3987 continue;
Nick Lewycky117f4382009-05-10 20:57:05 +00003988 }
Chris Lattner8b07fb52009-12-30 04:42:57 +00003989
3990 Value *V = 0;
3991 PATypeHolder Ty(Type::getVoidTy(Context));
3992 ValID ID;
Victor Hernandezbf454d22010-01-05 22:22:14 +00003993 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez84793eb2010-01-11 22:31:58 +00003994 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattner8b07fb52009-12-30 04:42:57 +00003995 return true;
3996
Nick Lewycky117f4382009-05-10 20:57:05 +00003997 Elts.push_back(V);
Nick Lewycky4dcf8102009-04-04 07:22:01 +00003998 } while (EatIfPresent(lltok::comma));
3999
4000 return false;
4001}