blob: 8ef8d66445709850e3e16195ec3c345fded124f9 [file] [log] [blame]
Chris Lattnerac161bf2009-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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth91065212014-03-05 10:34:14 +000016#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/CallingConv.h"
18#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000019#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/DerivedTypes.h"
21#include "llvm/IR/InlineAsm.h"
22#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000023#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Module.h"
25#include "llvm/IR/Operator.h"
26#include "llvm/IR/ValueSymbolTable.h"
Torok Edwin56d06592009-07-11 20:10:48 +000027#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000028#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000029#include "llvm/Support/raw_ostream.h"
30using namespace llvm;
31
Chris Lattner229907c2011-07-18 04:54:35 +000032static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000033 std::string Result;
34 raw_string_ostream Tmp(Result);
35 Tmp << *T;
36 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000037}
38
Chris Lattner3822f632009-01-02 08:05:26 +000039/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000040bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000041 // Prime the lexer.
42 Lex.Lex();
43
Chris Lattnerad6f3352009-01-04 20:44:11 +000044 return ParseTopLevelEntities() ||
45 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000046}
47
48/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
49/// module.
50bool LLParser::ValidateEndOfModule() {
Manman Ren209b17c2013-09-28 00:22:27 +000051 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
52 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
53
Bill Wendlingb32b0412013-02-08 06:32:06 +000054 // Handle any function attribute group forward references.
55 for (std::map<Value*, std::vector<unsigned> >::iterator
56 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
57 I != E; ++I) {
58 Value *V = I->first;
59 std::vector<unsigned> &Vec = I->second;
60 AttrBuilder B;
61
62 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
63 VI != VE; ++VI)
64 B.merge(NumberedAttrBuilders[*VI]);
65
66 if (Function *Fn = dyn_cast<Function>(V)) {
67 AttributeSet AS = Fn->getAttributes();
68 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
69 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
70 AS.getFnAttributes());
71
72 FnAttrs.merge(B);
73
74 // If the alignment was parsed as an attribute, move to the alignment
75 // field.
76 if (FnAttrs.hasAlignmentAttr()) {
77 Fn->setAlignment(FnAttrs.getAlignment());
78 FnAttrs.removeAttribute(Attribute::Alignment);
79 }
80
81 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
82 AttributeSet::get(Context,
83 AttributeSet::FunctionIndex,
84 FnAttrs));
85 Fn->setAttributes(AS);
86 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
87 AttributeSet AS = CI->getAttributes();
88 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
89 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
90 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +000091 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +000092 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
93 AttributeSet::get(Context,
94 AttributeSet::FunctionIndex,
95 FnAttrs));
96 CI->setAttributes(AS);
97 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
98 AttributeSet AS = II->getAttributes();
99 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
100 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
101 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000102 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000103 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
104 AttributeSet::get(Context,
105 AttributeSet::FunctionIndex,
106 FnAttrs));
107 II->setAttributes(AS);
108 } else {
109 llvm_unreachable("invalid object with forward attribute group reference");
110 }
111 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000112
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000113 // If there are entries in ForwardRefBlockAddresses at this point, the
114 // function was never defined.
115 if (!ForwardRefBlockAddresses.empty())
116 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
117 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000118
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000119 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
120 if (NumberedTypes[i].second.isValid())
121 return Error(NumberedTypes[i].second,
122 "use of undefined type '%" + Twine(i) + "'");
123
124 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
125 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
126 if (I->second.second.isValid())
127 return Error(I->second.second,
128 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000129
David Majnemerdad0a642014-06-27 18:19:56 +0000130 if (!ForwardRefComdats.empty())
131 return Error(ForwardRefComdats.begin()->second,
132 "use of undefined comdat '$" +
133 ForwardRefComdats.begin()->first + "'");
134
Chris Lattnerac161bf2009-01-02 07:01:27 +0000135 if (!ForwardRefVals.empty())
136 return Error(ForwardRefVals.begin()->second.second,
137 "use of undefined value '@" + ForwardRefVals.begin()->first +
138 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000139
Chris Lattnerac161bf2009-01-02 07:01:27 +0000140 if (!ForwardRefValIDs.empty())
141 return Error(ForwardRefValIDs.begin()->second.second,
142 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000143 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000144
Devang Pateld2541152009-07-08 19:23:54 +0000145 if (!ForwardRefMDNodes.empty())
146 return Error(ForwardRefMDNodes.begin()->second.second,
147 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000148 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000149
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000150 // Resolve metadata cycles.
151 for (auto &N : NumberedMetadata)
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000152 if (N && !N->isResolved())
153 N->resolveCycles();
Devang Pateld2541152009-07-08 19:23:54 +0000154
Chris Lattnerac161bf2009-01-02 07:01:27 +0000155 // Look for intrinsic functions and CallInst that need to be upgraded
156 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
157 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000158
Manman Ren8b4306c2013-12-02 21:29:56 +0000159 UpgradeDebugInfo(*M);
160
Chris Lattnerac161bf2009-01-02 07:01:27 +0000161 return false;
162}
163
164//===----------------------------------------------------------------------===//
165// Top-Level Entities
166//===----------------------------------------------------------------------===//
167
168bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000169 while (1) {
170 switch (Lex.getKind()) {
171 default: return TokError("expected top-level entity");
172 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000173 case lltok::kw_declare: if (ParseDeclare()) return true; break;
174 case lltok::kw_define: if (ParseDefine()) return true; break;
175 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
176 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000177 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000178 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000179 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000180 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000181 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000182 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000183 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000184 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000185
186 // The Global variable production with no name can have many different
187 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000188 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
189 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000190 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000191 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000192 case lltok::kw_internal: // OptionalLinkage
193 case lltok::kw_weak: // OptionalLinkage
194 case lltok::kw_weak_odr: // OptionalLinkage
195 case lltok::kw_linkonce: // OptionalLinkage
196 case lltok::kw_linkonce_odr: // OptionalLinkage
197 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000198 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000199 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000200 case lltok::kw_external: // OptionalLinkage
201 case lltok::kw_default: // OptionalVisibility
202 case lltok::kw_hidden: // OptionalVisibility
203 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000204 case lltok::kw_dllimport: // OptionalDLLStorageClass
205 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000206 case lltok::kw_thread_local: // OptionalThreadLocal
207 case lltok::kw_addrspace: // OptionalAddrSpace
208 case lltok::kw_constant: // GlobalType
209 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000210 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000211 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000212 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000213 bool HasLinkage;
214 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000215 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000216 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000217 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000218 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000219 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000220 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000221 return true;
222 break;
223 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000224
225 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000226 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
227 case lltok::kw_uselistorder_bb:
228 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000229 }
230 }
231}
232
233
234/// toplevelentity
235/// ::= 'module' 'asm' STRINGCONSTANT
236bool LLParser::ParseModuleAsm() {
237 assert(Lex.getKind() == lltok::kw_module);
238 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000239
240 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000241 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
242 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000243
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000244 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000245 return false;
246}
247
248/// toplevelentity
249/// ::= 'target' 'triple' '=' STRINGCONSTANT
250/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
251bool LLParser::ParseTargetDefinition() {
252 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000253 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000254 switch (Lex.Lex()) {
255 default: return TokError("unknown target property");
256 case lltok::kw_triple:
257 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000258 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
259 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000260 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000261 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000262 return false;
263 case lltok::kw_datalayout:
264 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000265 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
266 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000267 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000268 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000269 return false;
270 }
271}
272
Bill Wendling706d3d62012-11-28 08:41:48 +0000273/// toplevelentity
274/// ::= 'deplibs' '=' '[' ']'
275/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
276/// FIXME: Remove in 4.0. Currently parse, but ignore.
277bool LLParser::ParseDepLibs() {
278 assert(Lex.getKind() == lltok::kw_deplibs);
279 Lex.Lex();
280 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
281 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
282 return true;
283
284 if (EatIfPresent(lltok::rsquare))
285 return false;
286
287 do {
288 std::string Str;
289 if (ParseStringConstant(Str)) return true;
290 } while (EatIfPresent(lltok::comma));
291
292 return ParseToken(lltok::rsquare, "expected ']' at end of list");
293}
294
Dan Gohman466876b2009-08-12 23:32:33 +0000295/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000296/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000297bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000298 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000299 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000300 Lex.Lex(); // eat LocalVarID;
301
302 if (ParseToken(lltok::equal, "expected '=' after name") ||
303 ParseToken(lltok::kw_type, "expected 'type' after '='"))
304 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000305
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000306 if (TypeID >= NumberedTypes.size())
307 NumberedTypes.resize(TypeID+1);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000308
Craig Topper2617dcc2014-04-15 06:32:26 +0000309 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000310 if (ParseStructDefinition(TypeLoc, "",
311 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000312
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000313 if (!isa<StructType>(Result)) {
314 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
315 if (Entry.first)
316 return Error(TypeLoc, "non-struct types may not be recursive");
317 Entry.first = Result;
318 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000319 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000320
Chris Lattnerac161bf2009-01-02 07:01:27 +0000321 return false;
322}
323
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000324
Chris Lattnerac161bf2009-01-02 07:01:27 +0000325/// toplevelentity
326/// ::= LocalVar '=' 'type' type
327bool LLParser::ParseNamedType() {
328 std::string Name = Lex.getStrVal();
329 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000330 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000331
Chris Lattner3822f632009-01-02 08:05:26 +0000332 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000333 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000334 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000335
Craig Topper2617dcc2014-04-15 06:32:26 +0000336 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000337 if (ParseStructDefinition(NameLoc, Name,
338 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000339
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000340 if (!isa<StructType>(Result)) {
341 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
342 if (Entry.first)
343 return Error(NameLoc, "non-struct types may not be recursive");
344 Entry.first = Result;
345 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000346 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000347
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000348 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000349}
350
351
352/// toplevelentity
353/// ::= 'declare' FunctionHeader
354bool LLParser::ParseDeclare() {
355 assert(Lex.getKind() == lltok::kw_declare);
356 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000357
Chris Lattnerac161bf2009-01-02 07:01:27 +0000358 Function *F;
359 return ParseFunctionHeader(F, false);
360}
361
362/// toplevelentity
363/// ::= 'define' FunctionHeader '{' ...
364bool LLParser::ParseDefine() {
365 assert(Lex.getKind() == lltok::kw_define);
366 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000367
Chris Lattnerac161bf2009-01-02 07:01:27 +0000368 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000369 return ParseFunctionHeader(F, true) ||
370 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000371}
372
Chris Lattner3822f632009-01-02 08:05:26 +0000373/// ParseGlobalType
374/// ::= 'constant'
375/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000376bool LLParser::ParseGlobalType(bool &IsConstant) {
377 if (Lex.getKind() == lltok::kw_constant)
378 IsConstant = true;
379 else if (Lex.getKind() == lltok::kw_global)
380 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000381 else {
382 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000383 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000384 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000385 Lex.Lex();
386 return false;
387}
388
Dan Gohman466876b2009-08-12 23:32:33 +0000389/// ParseUnnamedGlobal:
390/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000391/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
392/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000393/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000394/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
395/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000396bool LLParser::ParseUnnamedGlobal() {
397 unsigned VarID = NumberedVals.size();
398 std::string Name;
399 LocTy NameLoc = Lex.getLoc();
400
401 // Handle the GlobalID form.
402 if (Lex.getKind() == lltok::GlobalID) {
403 if (Lex.getUIntVal() != VarID)
404 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000405 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000406 Lex.Lex(); // eat GlobalID;
407
408 if (ParseToken(lltok::equal, "expected '=' after name"))
409 return true;
410 }
411
412 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000413 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000414 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000415 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000416 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000417 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000418 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000419 ParseOptionalThreadLocal(TLM) ||
420 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000421 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000422
Rafael Espindola464fe022014-07-30 22:51:54 +0000423 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000424 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000425 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000426 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000427 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000428}
429
Chris Lattnerac161bf2009-01-02 07:01:27 +0000430/// ParseNamedGlobal:
431/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000432/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
433/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000434bool LLParser::ParseNamedGlobal() {
435 assert(Lex.getKind() == lltok::GlobalVar);
436 LocTy NameLoc = Lex.getLoc();
437 std::string Name = Lex.getStrVal();
438 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000439
Chris Lattnerac161bf2009-01-02 07:01:27 +0000440 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000441 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000442 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000443 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000444 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
445 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000446 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000447 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000448 ParseOptionalThreadLocal(TLM) ||
449 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000450 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000451
Rafael Espindola464fe022014-07-30 22:51:54 +0000452 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000453 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000454 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000455
456 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000457 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000458}
459
David Majnemerdad0a642014-06-27 18:19:56 +0000460bool LLParser::parseComdat() {
461 assert(Lex.getKind() == lltok::ComdatVar);
462 std::string Name = Lex.getStrVal();
463 LocTy NameLoc = Lex.getLoc();
464 Lex.Lex();
465
466 if (ParseToken(lltok::equal, "expected '=' here"))
467 return true;
468
469 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
470 return TokError("expected comdat type");
471
472 Comdat::SelectionKind SK;
473 switch (Lex.getKind()) {
474 default:
475 return TokError("unknown selection kind");
476 case lltok::kw_any:
477 SK = Comdat::Any;
478 break;
479 case lltok::kw_exactmatch:
480 SK = Comdat::ExactMatch;
481 break;
482 case lltok::kw_largest:
483 SK = Comdat::Largest;
484 break;
485 case lltok::kw_noduplicates:
486 SK = Comdat::NoDuplicates;
487 break;
488 case lltok::kw_samesize:
489 SK = Comdat::SameSize;
490 break;
491 }
492 Lex.Lex();
493
494 // See if the comdat was forward referenced, if so, use the comdat.
495 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
496 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
497 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
498 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
499
500 Comdat *C;
501 if (I != ComdatSymTab.end())
502 C = &I->second;
503 else
504 C = M->getOrInsertComdat(Name);
505 C->setSelectionKind(SK);
506
507 return false;
508}
509
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000510// MDString:
511// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000512bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000513 std::string Str;
514 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000515 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000516 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000517 return false;
518}
519
520// MDNode:
521// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000522bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000523 // !{ ..., !42, ... }
524 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000525 if (ParseUInt32(MID))
526 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000527
Chris Lattner8eff0152010-04-01 05:14:45 +0000528 // If not a forward reference, just return it now.
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000529 if (MID < NumberedMetadata.size() && NumberedMetadata[MID] != nullptr) {
530 Result = NumberedMetadata[MID];
531 return false;
532 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000533
Chris Lattner8eff0152010-04-01 05:14:45 +0000534 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000535 auto &FwdRef = ForwardRefMDNodes[MID];
536 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000537
Chris Lattnerfc58af22009-12-30 04:51:58 +0000538 if (NumberedMetadata.size() <= MID)
539 NumberedMetadata.resize(MID+1);
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000540 Result = FwdRef.first.get();
541 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000542 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000543}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000544
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000545/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000546/// !foo = !{ !1, !2 }
547bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000548 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000549 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000550 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000551
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000552 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000553 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000554 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000555 return true;
556
Dan Gohman2637cc12010-07-21 23:38:33 +0000557 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000558 if (Lex.getKind() != lltok::rbrace)
559 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000560 if (ParseToken(lltok::exclaim, "Expected '!' here"))
561 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000562
Craig Topper2617dcc2014-04-15 06:32:26 +0000563 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000564 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000565 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000566 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000567
568 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
569 return true;
570
Devang Patelbe626972009-07-29 00:34:02 +0000571 return false;
572}
573
Devang Patel39e64d42009-07-01 19:21:12 +0000574/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000575/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000576bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000577 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000578 Lex.Lex();
579 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000580
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000581 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000582 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000583 ParseToken(lltok::equal, "expected '=' here"))
584 return true;
585
586 // Detect common error, from old metadata syntax.
587 if (Lex.getKind() == lltok::Type)
588 return TokError("unexpected type in metadata definition");
589
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000590 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000591 if (Lex.getKind() == lltok::MetadataVar) {
592 if (ParseSpecializedMDNode(Init, IsDistinct))
593 return true;
594 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
595 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000596 return true;
597
Chris Lattnerfc58af22009-12-30 04:51:58 +0000598 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000599 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000600 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000601 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000602 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000603
Chris Lattnerfc58af22009-12-30 04:51:58 +0000604 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
605 } else {
606 if (MetadataID >= NumberedMetadata.size())
607 NumberedMetadata.resize(MetadataID+1);
608
Craig Topper2617dcc2014-04-15 06:32:26 +0000609 if (NumberedMetadata[MetadataID] != nullptr)
Chris Lattnerfc58af22009-12-30 04:51:58 +0000610 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000611 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000612 }
613
Devang Patel39e64d42009-07-01 19:21:12 +0000614 return false;
615}
616
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000617static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
618 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
619 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
620}
621
Chris Lattnerac161bf2009-01-02 07:01:27 +0000622/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000623/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
624/// OptionalDLLStorageClass OptionalThreadLocal
625/// OptionalUnNammedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000626///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000627/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000628/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000629///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000630/// Everything through OptionalUnNammedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000631///
Rafael Espindola464fe022014-07-30 22:51:54 +0000632bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000633 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000634 GlobalVariable::ThreadLocalMode TLM,
635 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000636 assert(Lex.getKind() == lltok::kw_alias);
637 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000638
Rafael Espindola78527052013-10-06 15:10:43 +0000639 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
640
Rafael Espindolacaa43562013-10-09 16:07:32 +0000641 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000642 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000643
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000644 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000645 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000646 "symbol with local linkage must have default visibility");
647
Rafael Espindola64c1e182014-06-03 02:41:57 +0000648 Constant *Aliasee;
649 LocTy AliaseeLoc = Lex.getLoc();
650 if (Lex.getKind() != lltok::kw_bitcast &&
651 Lex.getKind() != lltok::kw_getelementptr &&
652 Lex.getKind() != lltok::kw_addrspacecast &&
653 Lex.getKind() != lltok::kw_inttoptr) {
654 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000655 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000656 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000657 // The bitcast dest type is not present, it is implied by the dest type.
658 ValID ID;
659 if (ParseValID(ID))
660 return true;
661 if (ID.Kind != ValID::t_Constant)
662 return Error(AliaseeLoc, "invalid aliasee");
663 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000664 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000665
Rafael Espindola64c1e182014-06-03 02:41:57 +0000666 Type *AliaseeType = Aliasee->getType();
667 auto *PTy = dyn_cast<PointerType>(AliaseeType);
668 if (!PTy)
669 return Error(AliaseeLoc, "An alias must have pointer type");
670 Type *Ty = PTy->getElementType();
671 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000672
673 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000674 std::unique_ptr<GlobalAlias> GA(
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +0000675 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
676 Name, Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000677 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000678 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000679 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000680 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000681
Chris Lattnerac161bf2009-01-02 07:01:27 +0000682 // See if this value already exists in the symbol table. If so, it is either
683 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000684 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000685 // See if this was a redefinition. If so, there is no entry in
686 // ForwardRefVals.
687 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
688 I = ForwardRefVals.find(Name);
689 if (I == ForwardRefVals.end())
690 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
691
692 // Otherwise, this was a definition of forward ref. Verify that types
693 // agree.
694 if (Val->getType() != GA->getType())
695 return Error(NameLoc,
696 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000697
Chris Lattnerac161bf2009-01-02 07:01:27 +0000698 // If they agree, just RAUW the old value with the alias and remove the
699 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000700 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000701 Val->eraseFromParent();
702 ForwardRefVals.erase(I);
703 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000704
Chris Lattnerac161bf2009-01-02 07:01:27 +0000705 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000706 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000707 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000708
Rafael Espindolaaa273822014-05-09 21:49:17 +0000709 // The module owns this now
710 GA.release();
711
Chris Lattnerac161bf2009-01-02 07:01:27 +0000712 return false;
713}
714
715/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000716/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000717/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000718/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000719/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000720/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000721/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000722///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000723/// Everything up to and including OptionalUnNammedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000724/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000725///
726bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
727 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000728 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000729 GlobalVariable::ThreadLocalMode TLM,
730 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000731 if (!isValidVisibilityForLinkage(Visibility, Linkage))
732 return Error(NameLoc,
733 "symbol with local linkage must have default visibility");
734
Chris Lattnerac161bf2009-01-02 07:01:27 +0000735 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000736 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000737 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000738 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000739
Craig Topper2617dcc2014-04-15 06:32:26 +0000740 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000741 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000742 ParseOptionalToken(lltok::kw_externally_initialized,
743 IsExternallyInitialized,
744 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000745 ParseGlobalType(IsConstant) ||
746 ParseType(Ty, TyLoc))
747 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000748
Chris Lattnerac161bf2009-01-02 07:01:27 +0000749 // If the linkage is specified and is external, then no initializer is
750 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000751 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000752 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000753 Linkage != GlobalValue::ExternalLinkage)) {
754 if (ParseGlobalValue(Ty, Init))
755 return true;
756 }
757
Duncan Sands19d0b472010-02-16 11:11:14 +0000758 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000759 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000760
David Majnemer598bd052014-12-09 05:56:09 +0000761 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000762
763 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000764 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000765 GVal = M->getNamedValue(Name);
766 if (GVal) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000767 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
768 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000769 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000770 } else {
771 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
772 I = ForwardRefValIDs.find(NumberedVals.size());
773 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000774 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000775 ForwardRefValIDs.erase(I);
776 }
777 }
778
David Majnemer598bd052014-12-09 05:56:09 +0000779 GlobalVariable *GV;
780 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000781 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
782 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000783 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000784 } else {
David Majnemer598bd052014-12-09 05:56:09 +0000785 if (GVal->getType()->getElementType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000786 return Error(TyLoc,
787 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000788
David Majnemer598bd052014-12-09 05:56:09 +0000789 GV = cast<GlobalVariable>(GVal);
790
Chris Lattnerac161bf2009-01-02 07:01:27 +0000791 // Move the forward-reference to the correct spot in the module.
792 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
793 }
794
795 if (Name.empty())
796 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000797
Chris Lattnerac161bf2009-01-02 07:01:27 +0000798 // Set the parsed properties on the global.
799 if (Init)
800 GV->setInitializer(Init);
801 GV->setConstant(IsConstant);
802 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
803 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000804 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000805 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000806 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000807 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000808
Chris Lattnerac161bf2009-01-02 07:01:27 +0000809 // Parse attributes on the global.
810 while (Lex.getKind() == lltok::comma) {
811 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000812
Chris Lattnerac161bf2009-01-02 07:01:27 +0000813 if (Lex.getKind() == lltok::kw_section) {
814 Lex.Lex();
815 GV->setSection(Lex.getStrVal());
816 if (ParseToken(lltok::StringConstant, "expected global section string"))
817 return true;
818 } else if (Lex.getKind() == lltok::kw_align) {
819 unsigned Alignment;
820 if (ParseOptionalAlignment(Alignment)) return true;
821 GV->setAlignment(Alignment);
822 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000823 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000824 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000825 return true;
826 if (C)
827 GV->setComdat(C);
828 else
829 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000830 }
831 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000832
Chris Lattnerac161bf2009-01-02 07:01:27 +0000833 return false;
834}
835
Bill Wendling63b88192013-02-06 06:52:58 +0000836/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000837/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000838bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000839 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000840 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000841 Lex.Lex();
842
David Majnemerb39e22b2014-12-09 18:33:57 +0000843 if (Lex.getKind() != lltok::AttrGrpID)
844 return TokError("expected attribute group id");
845
Bill Wendling63b88192013-02-06 06:52:58 +0000846 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000847 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000848 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000849 Lex.Lex();
850
851 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000852 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000853 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000854 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000855 ParseToken(lltok::rbrace, "expected end of attribute group"))
856 return true;
857
Bill Wendlingb32b0412013-02-08 06:32:06 +0000858 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000859 return Error(AttrGrpLoc, "attribute group has no attributes");
860
861 return false;
862}
863
Bill Wendling8b0321d2013-02-08 00:52:31 +0000864/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000865/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000866bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
867 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000868 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000869 bool HaveError = false;
870
871 B.clear();
872
Bill Wendling63b88192013-02-06 06:52:58 +0000873 while (true) {
874 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000875 if (Token == lltok::kw_builtin)
876 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000877 switch (Token) {
878 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000879 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000880 return Error(Lex.getLoc(), "unterminated attribute group");
881 case lltok::rbrace:
882 // Finished.
883 return false;
884
Bill Wendlingb32b0412013-02-08 06:32:06 +0000885 case lltok::AttrGrpID: {
886 // Allow a function to reference an attribute group:
887 //
888 // define void @foo() #1 { ... }
889 if (inAttrGrp)
890 HaveError |=
891 Error(Lex.getLoc(),
892 "cannot have an attribute group reference in an attribute group");
893
894 unsigned AttrGrpNum = Lex.getUIntVal();
895 if (inAttrGrp) break;
896
897 // Save the reference to the attribute group. We'll fill it in later.
898 FwdRefAttrGrps.push_back(AttrGrpNum);
899 break;
900 }
Bill Wendling63b88192013-02-06 06:52:58 +0000901 // Target-dependent attributes:
902 case lltok::StringConstant: {
903 std::string Attr = Lex.getStrVal();
904 Lex.Lex();
905 std::string Val;
906 if (EatIfPresent(lltok::equal) &&
907 ParseStringConstant(Val))
908 return true;
909
910 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000911 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000912 }
913
914 // Target-independent attributes:
915 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000916 // As a hack, we allow function alignment to be initially parsed as an
917 // attribute on a function declaration/definition or added to an attribute
918 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000919 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000920 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000921 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000922 if (ParseToken(lltok::equal, "expected '=' here") ||
923 ParseUInt32(Alignment))
924 return true;
925 } else {
926 if (ParseOptionalAlignment(Alignment))
927 return true;
928 }
Bill Wendling63b88192013-02-06 06:52:58 +0000929 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000930 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000931 }
932 case lltok::kw_alignstack: {
933 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000934 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000935 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000936 if (ParseToken(lltok::equal, "expected '=' here") ||
937 ParseUInt32(Alignment))
938 return true;
939 } else {
940 if (ParseOptionalStackAlignment(Alignment))
941 return true;
942 }
Bill Wendling63b88192013-02-06 06:52:58 +0000943 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000944 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000945 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000946 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000947 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000948 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000949 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000950 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000951 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
952 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
953 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
954 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
955 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
956 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
957 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
958 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
959 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
960 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000961 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000962 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
963 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
964 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
965 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
966 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
967 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
968 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
969 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
970 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
971 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
972 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000973
974 // Error handling.
975 case lltok::kw_inreg:
976 case lltok::kw_signext:
977 case lltok::kw_zeroext:
978 HaveError |=
979 Error(Lex.getLoc(),
980 "invalid use of attribute on a function");
981 break;
982 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +0000983 case lltok::kw_dereferenceable:
Reid Klecknera534a382013-12-19 02:14:12 +0000984 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000985 case lltok::kw_nest:
986 case lltok::kw_noalias:
987 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000988 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +0000989 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000990 case lltok::kw_sret:
991 HaveError |=
992 Error(Lex.getLoc(),
993 "invalid use of parameter-only attribute on a function");
994 break;
Bill Wendling63b88192013-02-06 06:52:58 +0000995 }
996
997 Lex.Lex();
998 }
999}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001000
1001//===----------------------------------------------------------------------===//
1002// GlobalValue Reference/Resolution Routines.
1003//===----------------------------------------------------------------------===//
1004
1005/// GetGlobalVal - Get a value with the specified name or ID, creating a
1006/// forward reference record if needed. This can return null if the value
1007/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001008GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001009 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001010 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001011 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001012 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001013 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001014 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001015
Chris Lattnerac161bf2009-01-02 07:01:27 +00001016 // Look this name up in the normal function symbol table.
1017 GlobalValue *Val =
1018 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001019
Chris Lattnerac161bf2009-01-02 07:01:27 +00001020 // If this is a forward reference for the value, see if we already created a
1021 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001022 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001023 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1024 I = ForwardRefVals.find(Name);
1025 if (I != ForwardRefVals.end())
1026 Val = I->second.first;
1027 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001028
Chris Lattnerac161bf2009-01-02 07:01:27 +00001029 // If we have the value in the symbol table or fwd-ref table, return it.
1030 if (Val) {
1031 if (Val->getType() == Ty) return Val;
1032 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001033 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001034 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001035 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001036
Chris Lattnerac161bf2009-01-02 07:01:27 +00001037 // Otherwise, create a new forward reference for this value and remember it.
1038 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001039 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001040 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001041 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001042 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001043 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1044 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001045 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001046
Chris Lattnerac161bf2009-01-02 07:01:27 +00001047 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1048 return FwdVal;
1049}
1050
Chris Lattner229907c2011-07-18 04:54:35 +00001051GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1052 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001053 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001054 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001055 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001056 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001057
Craig Topper2617dcc2014-04-15 06:32:26 +00001058 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001059
Chris Lattnerac161bf2009-01-02 07:01:27 +00001060 // If this is a forward reference for the value, see if we already created a
1061 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001062 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001063 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1064 I = ForwardRefValIDs.find(ID);
1065 if (I != ForwardRefValIDs.end())
1066 Val = I->second.first;
1067 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001068
Chris Lattnerac161bf2009-01-02 07:01:27 +00001069 // If we have the value in the symbol table or fwd-ref table, return it.
1070 if (Val) {
1071 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001072 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001073 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001074 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001075 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001076
Chris Lattnerac161bf2009-01-02 07:01:27 +00001077 // Otherwise, create a new forward reference for this value and remember it.
1078 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001079 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001080 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001081 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001082 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001083 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001084
Chris Lattnerac161bf2009-01-02 07:01:27 +00001085 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1086 return FwdVal;
1087}
1088
1089
1090//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001091// Comdat Reference/Resolution Routines.
1092//===----------------------------------------------------------------------===//
1093
1094Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1095 // Look this name up in the comdat symbol table.
1096 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1097 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1098 if (I != ComdatSymTab.end())
1099 return &I->second;
1100
1101 // Otherwise, create a new forward reference for this value and remember it.
1102 Comdat *C = M->getOrInsertComdat(Name);
1103 ForwardRefComdats[Name] = Loc;
1104 return C;
1105}
1106
1107
1108//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001109// Helper Routines.
1110//===----------------------------------------------------------------------===//
1111
1112/// ParseToken - If the current token has the specified kind, eat it and return
1113/// success. Otherwise, emit the specified error and return failure.
1114bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1115 if (Lex.getKind() != T)
1116 return TokError(ErrMsg);
1117 Lex.Lex();
1118 return false;
1119}
1120
Chris Lattner3822f632009-01-02 08:05:26 +00001121/// ParseStringConstant
1122/// ::= StringConstant
1123bool LLParser::ParseStringConstant(std::string &Result) {
1124 if (Lex.getKind() != lltok::StringConstant)
1125 return TokError("expected string constant");
1126 Result = Lex.getStrVal();
1127 Lex.Lex();
1128 return false;
1129}
1130
1131/// ParseUInt32
1132/// ::= uint32
1133bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001134 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1135 return TokError("expected integer");
1136 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1137 if (Val64 != unsigned(Val64))
1138 return TokError("expected 32-bit integer (too large)");
1139 Val = Val64;
1140 Lex.Lex();
1141 return false;
1142}
1143
Hal Finkelb0407ba2014-07-18 15:51:28 +00001144/// ParseUInt64
1145/// ::= uint64
1146bool LLParser::ParseUInt64(uint64_t &Val) {
1147 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1148 return TokError("expected integer");
1149 Val = Lex.getAPSIntVal().getLimitedValue();
1150 Lex.Lex();
1151 return false;
1152}
1153
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001154/// ParseTLSModel
1155/// := 'localdynamic'
1156/// := 'initialexec'
1157/// := 'localexec'
1158bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1159 switch (Lex.getKind()) {
1160 default:
1161 return TokError("expected localdynamic, initialexec or localexec");
1162 case lltok::kw_localdynamic:
1163 TLM = GlobalVariable::LocalDynamicTLSModel;
1164 break;
1165 case lltok::kw_initialexec:
1166 TLM = GlobalVariable::InitialExecTLSModel;
1167 break;
1168 case lltok::kw_localexec:
1169 TLM = GlobalVariable::LocalExecTLSModel;
1170 break;
1171 }
1172
1173 Lex.Lex();
1174 return false;
1175}
1176
1177/// ParseOptionalThreadLocal
1178/// := /*empty*/
1179/// := 'thread_local'
1180/// := 'thread_local' '(' tlsmodel ')'
1181bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1182 TLM = GlobalVariable::NotThreadLocal;
1183 if (!EatIfPresent(lltok::kw_thread_local))
1184 return false;
1185
1186 TLM = GlobalVariable::GeneralDynamicTLSModel;
1187 if (Lex.getKind() == lltok::lparen) {
1188 Lex.Lex();
1189 return ParseTLSModel(TLM) ||
1190 ParseToken(lltok::rparen, "expected ')' after thread local model");
1191 }
1192 return false;
1193}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001194
1195/// ParseOptionalAddrSpace
1196/// := /*empty*/
1197/// := 'addrspace' '(' uint32 ')'
1198bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1199 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001200 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001201 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001202 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001203 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001204 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001205}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001206
Bill Wendling34c2eb22012-12-04 23:40:58 +00001207/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1208bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1209 bool HaveError = false;
1210
1211 B.clear();
1212
1213 while (1) {
1214 lltok::Kind Token = Lex.getKind();
1215 switch (Token) {
1216 default: // End of attributes.
1217 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001218 case lltok::kw_align: {
1219 unsigned Alignment;
1220 if (ParseOptionalAlignment(Alignment))
1221 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001222 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001223 continue;
1224 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001225 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001226 case lltok::kw_dereferenceable: {
1227 uint64_t Bytes;
1228 if (ParseOptionalDereferenceableBytes(Bytes))
1229 return true;
1230 B.addDereferenceableAttr(Bytes);
1231 continue;
1232 }
Reid Klecknera534a382013-12-19 02:14:12 +00001233 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001234 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1235 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1236 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1237 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001238 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001239 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1240 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001241 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001242 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1243 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1244 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001245
Stephen Lin7577ed52013-04-20 13:16:13 +00001246 case lltok::kw_alignstack:
1247 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001248 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001249 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001250 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001251 case lltok::kw_minsize:
1252 case lltok::kw_naked:
1253 case lltok::kw_nobuiltin:
1254 case lltok::kw_noduplicate:
1255 case lltok::kw_noimplicitfloat:
1256 case lltok::kw_noinline:
1257 case lltok::kw_nonlazybind:
1258 case lltok::kw_noredzone:
1259 case lltok::kw_noreturn:
1260 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001261 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001262 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001263 case lltok::kw_returns_twice:
1264 case lltok::kw_sanitize_address:
1265 case lltok::kw_sanitize_memory:
1266 case lltok::kw_sanitize_thread:
1267 case lltok::kw_ssp:
1268 case lltok::kw_sspreq:
1269 case lltok::kw_sspstrong:
1270 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001271 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1272 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001273 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001274
Bill Wendling34c2eb22012-12-04 23:40:58 +00001275 Lex.Lex();
1276 }
1277}
1278
1279/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1280bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1281 bool HaveError = false;
1282
1283 B.clear();
1284
1285 while (1) {
1286 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001287 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001288 default: // End of attributes.
1289 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001290 case lltok::kw_dereferenceable: {
1291 uint64_t Bytes;
1292 if (ParseOptionalDereferenceableBytes(Bytes))
1293 return true;
1294 B.addDereferenceableAttr(Bytes);
1295 continue;
1296 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001297 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1298 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001299 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001300 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1301 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001302
Bill Wendling34c2eb22012-12-04 23:40:58 +00001303 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001304 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001305 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001306 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001307 case lltok::kw_nest:
1308 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001309 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001310 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001311 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001312 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001313
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001314 case lltok::kw_alignstack:
1315 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001316 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001317 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001318 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001319 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001320 case lltok::kw_minsize:
1321 case lltok::kw_naked:
1322 case lltok::kw_nobuiltin:
1323 case lltok::kw_noduplicate:
1324 case lltok::kw_noimplicitfloat:
1325 case lltok::kw_noinline:
1326 case lltok::kw_nonlazybind:
1327 case lltok::kw_noredzone:
1328 case lltok::kw_noreturn:
1329 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001330 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001331 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001332 case lltok::kw_returns_twice:
1333 case lltok::kw_sanitize_address:
1334 case lltok::kw_sanitize_memory:
1335 case lltok::kw_sanitize_thread:
1336 case lltok::kw_ssp:
1337 case lltok::kw_sspreq:
1338 case lltok::kw_sspstrong:
1339 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001340 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001341 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001342
1343 case lltok::kw_readnone:
1344 case lltok::kw_readonly:
1345 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001346 }
1347
Chris Lattnerac161bf2009-01-02 07:01:27 +00001348 Lex.Lex();
1349 }
1350}
1351
1352/// ParseOptionalLinkage
1353/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001354/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001355/// ::= 'internal'
1356/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001357/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001358/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001359/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001360/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001361/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001362/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001363/// ::= 'extern_weak'
1364/// ::= 'external'
1365bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1366 HasLinkage = false;
1367 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001368 default: Res=GlobalValue::ExternalLinkage; return false;
1369 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001370 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1371 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1372 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1373 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1374 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001375 case lltok::kw_available_externally:
1376 Res = GlobalValue::AvailableExternallyLinkage;
1377 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001378 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001379 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001380 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1381 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001382 }
1383 Lex.Lex();
1384 HasLinkage = true;
1385 return false;
1386}
1387
1388/// ParseOptionalVisibility
1389/// ::= /*empty*/
1390/// ::= 'default'
1391/// ::= 'hidden'
1392/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001393///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001394bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1395 switch (Lex.getKind()) {
1396 default: Res = GlobalValue::DefaultVisibility; return false;
1397 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1398 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1399 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1400 }
1401 Lex.Lex();
1402 return false;
1403}
1404
Nico Rieck7157bb72014-01-14 15:22:47 +00001405/// ParseOptionalDLLStorageClass
1406/// ::= /*empty*/
1407/// ::= 'dllimport'
1408/// ::= 'dllexport'
1409///
1410bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1411 switch (Lex.getKind()) {
1412 default: Res = GlobalValue::DefaultStorageClass; return false;
1413 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1414 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1415 }
1416 Lex.Lex();
1417 return false;
1418}
1419
Chris Lattnerac161bf2009-01-02 07:01:27 +00001420/// ParseOptionalCallingConv
1421/// ::= /*empty*/
1422/// ::= 'ccc'
1423/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001424/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001425/// ::= 'coldcc'
1426/// ::= 'x86_stdcallcc'
1427/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001428/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001429/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001430/// ::= 'arm_apcscc'
1431/// ::= 'arm_aapcscc'
1432/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001433/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001434/// ::= 'ptx_kernel'
1435/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001436/// ::= 'spir_func'
1437/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001438/// ::= 'x86_64_sysvcc'
1439/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001440/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001441/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001442/// ::= 'preserve_mostcc'
1443/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001444/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001445/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001446///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001447bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001448 switch (Lex.getKind()) {
1449 default: CC = CallingConv::C; return false;
1450 case lltok::kw_ccc: CC = CallingConv::C; break;
1451 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1452 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1453 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1454 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001455 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001456 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001457 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1458 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1459 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001460 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001461 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1462 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001463 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1464 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001465 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001466 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1467 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001468 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001469 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001470 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1471 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001472 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001473 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001474 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001475 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001476 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001477 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001478
Chris Lattnerac161bf2009-01-02 07:01:27 +00001479 Lex.Lex();
1480 return false;
1481}
1482
Chris Lattner5c427632009-12-30 05:31:19 +00001483/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001484/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001485bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1486 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001487 do {
1488 if (Lex.getKind() != lltok::MetadataVar)
1489 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001490
Chris Lattner596760d2009-12-29 21:25:40 +00001491 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001492 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001493 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001494
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001495 MDNode *N;
1496 if (ParseMDNode(N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001497 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001498
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001499 Inst->setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001500 if (MDK == LLVMContext::MD_tbaa)
1501 InstsWithTBAATag.push_back(Inst);
1502
Chris Lattner596760d2009-12-29 21:25:40 +00001503 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001504 } while (EatIfPresent(lltok::comma));
1505 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001506}
1507
Chris Lattnerac161bf2009-01-02 07:01:27 +00001508/// ParseOptionalAlignment
1509/// ::= /* empty */
1510/// ::= 'align' 4
1511bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1512 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001513 if (!EatIfPresent(lltok::kw_align))
1514 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001515 LocTy AlignLoc = Lex.getLoc();
1516 if (ParseUInt32(Alignment)) return true;
1517 if (!isPowerOf2_32(Alignment))
1518 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001519 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001520 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001521 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001522}
1523
Hal Finkelb0407ba2014-07-18 15:51:28 +00001524/// ParseOptionalDereferenceableBytes
1525/// ::= /* empty */
1526/// ::= 'dereferenceable' '(' 4 ')'
1527bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1528 Bytes = 0;
1529 if (!EatIfPresent(lltok::kw_dereferenceable))
1530 return false;
1531 LocTy ParenLoc = Lex.getLoc();
1532 if (!EatIfPresent(lltok::lparen))
1533 return Error(ParenLoc, "expected '('");
1534 LocTy DerefLoc = Lex.getLoc();
1535 if (ParseUInt64(Bytes)) return true;
1536 ParenLoc = Lex.getLoc();
1537 if (!EatIfPresent(lltok::rparen))
1538 return Error(ParenLoc, "expected ')'");
1539 if (!Bytes)
1540 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1541 return false;
1542}
1543
Chris Lattnerb2f39502009-12-30 05:44:30 +00001544/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001545/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001546/// ::= ',' align 4
1547///
1548/// This returns with AteExtraComma set to true if it ate an excess comma at the
1549/// end.
1550bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1551 bool &AteExtraComma) {
1552 AteExtraComma = false;
1553 while (EatIfPresent(lltok::comma)) {
1554 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001555 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001556 AteExtraComma = true;
1557 return false;
1558 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001559
Chris Lattner95b0ff42010-04-23 00:50:50 +00001560 if (Lex.getKind() != lltok::kw_align)
1561 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001562
Chris Lattner95b0ff42010-04-23 00:50:50 +00001563 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001564 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001565
Devang Patelea8a4b92009-09-17 23:04:48 +00001566 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001567}
1568
Eli Friedmanfee02c62011-07-25 23:16:38 +00001569/// ParseScopeAndOrdering
1570/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1571/// else: ::=
1572///
1573/// This sets Scope and Ordering to the parsed values.
1574bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1575 AtomicOrdering &Ordering) {
1576 if (!isAtomic)
1577 return false;
1578
1579 Scope = CrossThread;
1580 if (EatIfPresent(lltok::kw_singlethread))
1581 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001582
1583 return ParseOrdering(Ordering);
1584}
1585
1586/// ParseOrdering
1587/// ::= AtomicOrdering
1588///
1589/// This sets Ordering to the parsed value.
1590bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001591 switch (Lex.getKind()) {
1592 default: return TokError("Expected ordering on atomic instruction");
1593 case lltok::kw_unordered: Ordering = Unordered; break;
1594 case lltok::kw_monotonic: Ordering = Monotonic; break;
1595 case lltok::kw_acquire: Ordering = Acquire; break;
1596 case lltok::kw_release: Ordering = Release; break;
1597 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1598 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1599 }
1600 Lex.Lex();
1601 return false;
1602}
1603
Charles Davisbe5557e2010-02-12 00:31:15 +00001604/// ParseOptionalStackAlignment
1605/// ::= /* empty */
1606/// ::= 'alignstack' '(' 4 ')'
1607bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1608 Alignment = 0;
1609 if (!EatIfPresent(lltok::kw_alignstack))
1610 return false;
1611 LocTy ParenLoc = Lex.getLoc();
1612 if (!EatIfPresent(lltok::lparen))
1613 return Error(ParenLoc, "expected '('");
1614 LocTy AlignLoc = Lex.getLoc();
1615 if (ParseUInt32(Alignment)) return true;
1616 ParenLoc = Lex.getLoc();
1617 if (!EatIfPresent(lltok::rparen))
1618 return Error(ParenLoc, "expected ')'");
1619 if (!isPowerOf2_32(Alignment))
1620 return Error(AlignLoc, "stack alignment is not a power of two");
1621 return false;
1622}
Devang Patelea8a4b92009-09-17 23:04:48 +00001623
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001624/// ParseIndexList - This parses the index list for an insert/extractvalue
1625/// instruction. This sets AteExtraComma in the case where we eat an extra
1626/// comma at the end of the line and find that it is followed by metadata.
1627/// Clients that don't allow metadata can call the version of this function that
1628/// only takes one argument.
1629///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001630/// ParseIndexList
1631/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001632///
1633bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1634 bool &AteExtraComma) {
1635 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001636
Chris Lattnerac161bf2009-01-02 07:01:27 +00001637 if (Lex.getKind() != lltok::comma)
1638 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001639
Chris Lattner3822f632009-01-02 08:05:26 +00001640 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001641 if (Lex.getKind() == lltok::MetadataVar) {
1642 AteExtraComma = true;
1643 return false;
1644 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001645 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001646 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001647 Indices.push_back(Idx);
1648 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001649
Chris Lattnerac161bf2009-01-02 07:01:27 +00001650 return false;
1651}
1652
1653//===----------------------------------------------------------------------===//
1654// Type Parsing.
1655//===----------------------------------------------------------------------===//
1656
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001657/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001658bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001659 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001660 switch (Lex.getKind()) {
1661 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001662 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001663 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001664 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001665 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001666 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001667 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001668 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001669 // Type ::= StructType
1670 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001671 return true;
1672 break;
1673 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001674 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001675 Lex.Lex(); // eat the lsquare.
1676 if (ParseArrayVectorType(Result, false))
1677 return true;
1678 break;
1679 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001680 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001681 Lex.Lex();
1682 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001683 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001684 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001685 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001686 } else if (ParseArrayVectorType(Result, true))
1687 return true;
1688 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001689 case lltok::LocalVar: {
1690 // Type ::= %foo
1691 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001692
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001693 // If the type hasn't been defined yet, create a forward definition and
1694 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001695 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001696 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001697 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001698 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001699 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001700 Lex.Lex();
1701 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001702 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001703
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001704 case lltok::LocalVarID: {
1705 // Type ::= %4
1706 if (Lex.getUIntVal() >= NumberedTypes.size())
1707 NumberedTypes.resize(Lex.getUIntVal()+1);
1708 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001709
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001710 // If the type hasn't been defined yet, create a forward definition and
1711 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001712 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001713 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001714 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001715 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001716 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001717 Lex.Lex();
1718 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001719 }
1720 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001721
1722 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001723 while (1) {
1724 switch (Lex.getKind()) {
1725 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001726 default:
1727 if (!AllowVoid && Result->isVoidTy())
1728 return Error(TypeLoc, "void type only allowed for function results");
1729 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001730
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001731 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001732 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001733 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001734 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001735 if (Result->isVoidTy())
1736 return TokError("pointers to void are invalid - use i8* instead");
1737 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001738 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001739 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001740 Lex.Lex();
1741 break;
1742
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001743 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001744 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001745 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001746 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001747 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001748 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001749 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001750 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001751 unsigned AddrSpace;
1752 if (ParseOptionalAddrSpace(AddrSpace) ||
1753 ParseToken(lltok::star, "expected '*' in address space"))
1754 return true;
1755
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001756 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001757 break;
1758 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001759
Chris Lattnerac161bf2009-01-02 07:01:27 +00001760 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1761 case lltok::lparen:
1762 if (ParseFunctionType(Result))
1763 return true;
1764 break;
1765 }
1766 }
1767}
1768
1769/// ParseParameterList
1770/// ::= '(' ')'
1771/// ::= '(' Arg (',' Arg)* ')'
1772/// Arg
1773/// ::= Type OptionalAttributes Value OptionalAttributes
1774bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001775 PerFunctionState &PFS, bool IsMustTailCall,
1776 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001777 if (ParseToken(lltok::lparen, "expected '(' in call"))
1778 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001779
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001780 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001781 while (Lex.getKind() != lltok::rparen) {
1782 // If this isn't the first argument, we need a comma.
1783 if (!ArgList.empty() &&
1784 ParseToken(lltok::comma, "expected ',' in argument list"))
1785 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001786
Reid Kleckner83498642014-08-26 00:33:28 +00001787 // Parse an ellipsis if this is a musttail call in a variadic function.
1788 if (Lex.getKind() == lltok::dotdotdot) {
1789 const char *Msg = "unexpected ellipsis in argument list for ";
1790 if (!IsMustTailCall)
1791 return TokError(Twine(Msg) + "non-musttail call");
1792 if (!InVarArgsFunc)
1793 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1794 Lex.Lex(); // Lex the '...', it is purely for readability.
1795 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1796 }
1797
Chris Lattnerac161bf2009-01-02 07:01:27 +00001798 // Parse the argument.
1799 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001800 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001801 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001802 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001803 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001804 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001805
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001806 if (ArgTy->isMetadataTy()) {
1807 if (ParseMetadataAsValue(V, PFS))
1808 return true;
1809 } else {
1810 // Otherwise, handle normal operands.
1811 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1812 return true;
1813 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001814 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1815 AttrIndex++,
1816 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001817 }
1818
Reid Kleckner83498642014-08-26 00:33:28 +00001819 if (IsMustTailCall && InVarArgsFunc)
1820 return TokError("expected '...' at end of argument list for musttail call "
1821 "in varargs function");
1822
Chris Lattnerac161bf2009-01-02 07:01:27 +00001823 Lex.Lex(); // Lex the ')'.
1824 return false;
1825}
1826
1827
1828
Chris Lattner2ed06b42009-01-05 18:34:07 +00001829/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001830/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001831/// ::= '(' ArgTypeListI ')'
1832/// ArgTypeListI
1833/// ::= /*empty*/
1834/// ::= '...'
1835/// ::= ArgTypeList ',' '...'
1836/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001837///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001838bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1839 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001840 isVarArg = false;
1841 assert(Lex.getKind() == lltok::lparen);
1842 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001843
Chris Lattnerac161bf2009-01-02 07:01:27 +00001844 if (Lex.getKind() == lltok::rparen) {
1845 // empty
1846 } else if (Lex.getKind() == lltok::dotdotdot) {
1847 isVarArg = true;
1848 Lex.Lex();
1849 } else {
1850 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001851 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001852 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001853 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001854
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001855 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001856 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001857
Chris Lattnerfdd87902009-10-05 05:54:46 +00001858 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001859 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001860
Chris Lattnerdef19492011-06-17 06:36:20 +00001861 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001862 Name = Lex.getStrVal();
1863 Lex.Lex();
1864 }
Chris Lattner3822f632009-01-02 08:05:26 +00001865
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001866 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001867 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001868
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001869 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001870 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001871 AttributeSet::get(ArgTy->getContext(),
1872 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001873
Chris Lattner3822f632009-01-02 08:05:26 +00001874 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001875 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001876 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001877 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001878 break;
1879 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001880
Chris Lattnerac161bf2009-01-02 07:01:27 +00001881 // Otherwise must be an argument type.
1882 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001883 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001884
Chris Lattnerfdd87902009-10-05 05:54:46 +00001885 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001886 return Error(TypeLoc, "argument can not have void type");
1887
Chris Lattnerdef19492011-06-17 06:36:20 +00001888 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001889 Name = Lex.getStrVal();
1890 Lex.Lex();
1891 } else {
1892 Name = "";
1893 }
Chris Lattner3822f632009-01-02 08:05:26 +00001894
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001895 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001896 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001897
Bill Wendlingd079a442012-10-15 04:46:55 +00001898 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001899 AttributeSet::get(ArgTy->getContext(),
1900 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001901 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001902 }
1903 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001904
Chris Lattner3822f632009-01-02 08:05:26 +00001905 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001906}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001907
Chris Lattnerac161bf2009-01-02 07:01:27 +00001908/// ParseFunctionType
1909/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001910bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001911 assert(Lex.getKind() == lltok::lparen);
1912
Chris Lattnerce473c72009-01-05 08:04:33 +00001913 if (!FunctionType::isValidReturnType(Result))
1914 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001915
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001916 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001917 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001918 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001919 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001920
Chris Lattnerac161bf2009-01-02 07:01:27 +00001921 // Reject names on the arguments lists.
1922 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1923 if (!ArgList[i].Name.empty())
1924 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001925 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001926 return Error(ArgList[i].Loc,
1927 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001928 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001929
Jay Foadb804a2b2011-07-12 14:06:48 +00001930 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001931 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001932 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001933
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001934 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001935 return false;
1936}
1937
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001938/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1939/// other structs.
1940bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1941 SmallVector<Type*, 8> Elts;
1942 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001943
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001944 Result = StructType::get(Context, Elts, Packed);
1945 return false;
1946}
1947
1948/// ParseStructDefinition - Parse a struct in a 'type' definition.
1949bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1950 std::pair<Type*, LocTy> &Entry,
1951 Type *&ResultTy) {
1952 // If the type was already defined, diagnose the redefinition.
1953 if (Entry.first && !Entry.second.isValid())
1954 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001955
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001956 // If we have opaque, just return without filling in the definition for the
1957 // struct. This counts as a definition as far as the .ll file goes.
1958 if (EatIfPresent(lltok::kw_opaque)) {
1959 // This type is being defined, so clear the location to indicate this.
1960 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001961
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001962 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00001963 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00001964 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001965 ResultTy = Entry.first;
1966 return false;
1967 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001968
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001969 // If the type starts with '<', then it is either a packed struct or a vector.
1970 bool isPacked = EatIfPresent(lltok::less);
1971
1972 // If we don't have a struct, then we have a random type alias, which we
1973 // accept for compatibility with old files. These types are not allowed to be
1974 // forward referenced and not allowed to be recursive.
1975 if (Lex.getKind() != lltok::lbrace) {
1976 if (Entry.first)
1977 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001978
Craig Topper2617dcc2014-04-15 06:32:26 +00001979 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001980 if (isPacked)
1981 return ParseArrayVectorType(ResultTy, true);
1982 return ParseType(ResultTy);
1983 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001984
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001985 // This type is being defined, so clear the location to indicate this.
1986 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001987
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001988 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00001989 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00001990 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001991
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001992 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001993
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001994 SmallVector<Type*, 8> Body;
1995 if (ParseStructBody(Body) ||
1996 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1997 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001998
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001999 STy->setBody(Body, isPacked);
2000 ResultTy = STy;
2001 return false;
2002}
2003
2004
Chris Lattnerac161bf2009-01-02 07:01:27 +00002005/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002006/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002007/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002008/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002009/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002010/// ::= '<' '{' Type (',' Type)* '}' '>'
2011bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002012 assert(Lex.getKind() == lltok::lbrace);
2013 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002014
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002015 // Handle the empty struct.
2016 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002017 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002018
Chris Lattnerf880ca22009-03-09 04:49:14 +00002019 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002020 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002021 if (ParseType(Ty)) return true;
2022 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002023
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002024 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002025 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002026
Chris Lattner3822f632009-01-02 08:05:26 +00002027 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002028 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002029 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002030
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002031 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002032 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002033
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002034 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002035 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002036
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002037 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002038}
2039
2040/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2041/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002042/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002043/// ::= '[' APSINTVAL 'x' Types ']'
2044/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002045bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002046 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2047 Lex.getAPSIntVal().getBitWidth() > 64)
2048 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002049
Chris Lattnerac161bf2009-01-02 07:01:27 +00002050 LocTy SizeLoc = Lex.getLoc();
2051 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002052 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002053
Chris Lattner3822f632009-01-02 08:05:26 +00002054 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2055 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002056
2057 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002058 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002059 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002060
Chris Lattner3822f632009-01-02 08:05:26 +00002061 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2062 "expected end of sequential type"))
2063 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002064
Chris Lattnerac161bf2009-01-02 07:01:27 +00002065 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002066 if (Size == 0)
2067 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002068 if ((unsigned)Size != Size)
2069 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002070 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002071 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002072 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002073 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002074 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002075 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002076 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002077 }
2078 return false;
2079}
2080
2081//===----------------------------------------------------------------------===//
2082// Function Semantic Analysis.
2083//===----------------------------------------------------------------------===//
2084
Chris Lattner3432c622009-10-28 03:39:23 +00002085LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2086 int functionNumber)
2087 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002088
2089 // Insert unnamed arguments into the NumberedVals list.
2090 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2091 AI != E; ++AI)
2092 if (!AI->hasName())
2093 NumberedVals.push_back(AI);
2094}
2095
2096LLParser::PerFunctionState::~PerFunctionState() {
2097 // If there were any forward referenced non-basicblock values, delete them.
2098 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2099 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2100 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002101 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002102 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002103 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002104 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002105 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002106
Chris Lattnerac161bf2009-01-02 07:01:27 +00002107 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2108 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2109 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002110 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002111 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002112 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002113 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002114 }
2115}
2116
Chris Lattner3432c622009-10-28 03:39:23 +00002117bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002118 if (!ForwardRefVals.empty())
2119 return P.Error(ForwardRefVals.begin()->second.second,
2120 "use of undefined value '%" + ForwardRefVals.begin()->first +
2121 "'");
2122 if (!ForwardRefValIDs.empty())
2123 return P.Error(ForwardRefValIDs.begin()->second.second,
2124 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002125 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002126 return false;
2127}
2128
2129
2130/// GetVal - Get a value with the specified name or ID, creating a
2131/// forward reference record if needed. This can return null if the value
2132/// exists but does not have the right type.
2133Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002134 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002135 // Look this name up in the normal function symbol table.
2136 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002137
Chris Lattnerac161bf2009-01-02 07:01:27 +00002138 // If this is a forward reference for the value, see if we already created a
2139 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002140 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002141 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2142 I = ForwardRefVals.find(Name);
2143 if (I != ForwardRefVals.end())
2144 Val = I->second.first;
2145 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002146
Chris Lattnerac161bf2009-01-02 07:01:27 +00002147 // If we have the value in the symbol table or fwd-ref table, return it.
2148 if (Val) {
2149 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002150 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002151 P.Error(Loc, "'%" + Name + "' is not a basic block");
2152 else
2153 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002154 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002155 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002156 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002157
Chris Lattnerac161bf2009-01-02 07:01:27 +00002158 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002159 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002160 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002161 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002162 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002163
Chris Lattnerac161bf2009-01-02 07:01:27 +00002164 // Otherwise, create a new forward reference for this value and remember it.
2165 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002166 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002167 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002168 else
2169 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002170
Chris Lattnerac161bf2009-01-02 07:01:27 +00002171 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2172 return FwdVal;
2173}
2174
Chris Lattner229907c2011-07-18 04:54:35 +00002175Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002176 LocTy Loc) {
2177 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002178 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002179
Chris Lattnerac161bf2009-01-02 07:01:27 +00002180 // If this is a forward reference for the value, see if we already created a
2181 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002182 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002183 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2184 I = ForwardRefValIDs.find(ID);
2185 if (I != ForwardRefValIDs.end())
2186 Val = I->second.first;
2187 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002188
Chris Lattnerac161bf2009-01-02 07:01:27 +00002189 // If we have the value in the symbol table or fwd-ref table, return it.
2190 if (Val) {
2191 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002192 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002193 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002194 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002195 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002196 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002197 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002198 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002199
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002200 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002201 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002202 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002203 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002204
Chris Lattnerac161bf2009-01-02 07:01:27 +00002205 // Otherwise, create a new forward reference for this value and remember it.
2206 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002207 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002208 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002209 else
2210 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002211
Chris Lattnerac161bf2009-01-02 07:01:27 +00002212 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2213 return FwdVal;
2214}
2215
2216/// SetInstName - After an instruction is parsed and inserted into its
2217/// basic block, this installs its name.
2218bool LLParser::PerFunctionState::SetInstName(int NameID,
2219 const std::string &NameStr,
2220 LocTy NameLoc, Instruction *Inst) {
2221 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002222 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002223 if (NameID != -1 || !NameStr.empty())
2224 return P.Error(NameLoc, "instructions returning void cannot have a name");
2225 return false;
2226 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002227
Chris Lattnerac161bf2009-01-02 07:01:27 +00002228 // If this was a numbered instruction, verify that the instruction is the
2229 // expected value and resolve any forward references.
2230 if (NameStr.empty()) {
2231 // If neither a name nor an ID was specified, just use the next ID.
2232 if (NameID == -1)
2233 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002234
Chris Lattnerac161bf2009-01-02 07:01:27 +00002235 if (unsigned(NameID) != NumberedVals.size())
2236 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002237 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002238
Chris Lattnerac161bf2009-01-02 07:01:27 +00002239 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2240 ForwardRefValIDs.find(NameID);
2241 if (FI != ForwardRefValIDs.end()) {
2242 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002243 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002244 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002245 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002246 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002247 ForwardRefValIDs.erase(FI);
2248 }
2249
2250 NumberedVals.push_back(Inst);
2251 return false;
2252 }
2253
2254 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2255 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2256 FI = ForwardRefVals.find(NameStr);
2257 if (FI != ForwardRefVals.end()) {
2258 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002259 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002260 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002261 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002262 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002263 ForwardRefVals.erase(FI);
2264 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002265
Chris Lattnerac161bf2009-01-02 07:01:27 +00002266 // Set the name on the instruction.
2267 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002268
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002269 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002270 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002271 NameStr + "'");
2272 return false;
2273}
2274
2275/// GetBB - Get a basic block with the specified name or ID, creating a
2276/// forward reference record if needed.
2277BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2278 LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002279 return cast_or_null<BasicBlock>(GetVal(Name,
2280 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002281}
2282
2283BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002284 return cast_or_null<BasicBlock>(GetVal(ID,
2285 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002286}
2287
2288/// DefineBB - Define the specified basic block, which is either named or
2289/// unnamed. If there is an error, this returns null otherwise it returns
2290/// the block being defined.
2291BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2292 LocTy Loc) {
2293 BasicBlock *BB;
2294 if (Name.empty())
2295 BB = GetBB(NumberedVals.size(), Loc);
2296 else
2297 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002298 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002299
Chris Lattnerac161bf2009-01-02 07:01:27 +00002300 // Move the block to the end of the function. Forward ref'd blocks are
2301 // inserted wherever they happen to be referenced.
2302 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002303
Chris Lattnerac161bf2009-01-02 07:01:27 +00002304 // Remove the block from forward ref sets.
2305 if (Name.empty()) {
2306 ForwardRefValIDs.erase(NumberedVals.size());
2307 NumberedVals.push_back(BB);
2308 } else {
2309 // BB forward references are already in the function symbol table.
2310 ForwardRefVals.erase(Name);
2311 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002312
Chris Lattnerac161bf2009-01-02 07:01:27 +00002313 return BB;
2314}
2315
2316//===----------------------------------------------------------------------===//
2317// Constants.
2318//===----------------------------------------------------------------------===//
2319
2320/// ParseValID - Parse an abstract value that doesn't necessarily have a
2321/// type implied. For example, if we parse "4" we don't know what integer type
2322/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002323/// sanity. PFS is used to convert function-local operands of metadata (since
2324/// metadata operands are not just parsed here but also converted to values).
2325/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002326bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002327 ID.Loc = Lex.getLoc();
2328 switch (Lex.getKind()) {
2329 default: return TokError("expected value token");
2330 case lltok::GlobalID: // @42
2331 ID.UIntVal = Lex.getUIntVal();
2332 ID.Kind = ValID::t_GlobalID;
2333 break;
2334 case lltok::GlobalVar: // @foo
2335 ID.StrVal = Lex.getStrVal();
2336 ID.Kind = ValID::t_GlobalName;
2337 break;
2338 case lltok::LocalVarID: // %42
2339 ID.UIntVal = Lex.getUIntVal();
2340 ID.Kind = ValID::t_LocalID;
2341 break;
2342 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002343 ID.StrVal = Lex.getStrVal();
2344 ID.Kind = ValID::t_LocalName;
2345 break;
2346 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002347 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002348 ID.Kind = ValID::t_APSInt;
2349 break;
2350 case lltok::APFloat:
2351 ID.APFloatVal = Lex.getAPFloatVal();
2352 ID.Kind = ValID::t_APFloat;
2353 break;
2354 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002355 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002356 ID.Kind = ValID::t_Constant;
2357 break;
2358 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002359 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002360 ID.Kind = ValID::t_Constant;
2361 break;
2362 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2363 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2364 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002365
Chris Lattnerac161bf2009-01-02 07:01:27 +00002366 case lltok::lbrace: {
2367 // ValID ::= '{' ConstVector '}'
2368 Lex.Lex();
2369 SmallVector<Constant*, 16> Elts;
2370 if (ParseGlobalValueVector(Elts) ||
2371 ParseToken(lltok::rbrace, "expected end of struct constant"))
2372 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002373
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002374 ID.ConstantStructElts = new Constant*[Elts.size()];
2375 ID.UIntVal = Elts.size();
2376 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2377 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002378 return false;
2379 }
2380 case lltok::less: {
2381 // ValID ::= '<' ConstVector '>' --> Vector.
2382 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2383 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002384 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002385
Chris Lattnerac161bf2009-01-02 07:01:27 +00002386 SmallVector<Constant*, 16> Elts;
2387 LocTy FirstEltLoc = Lex.getLoc();
2388 if (ParseGlobalValueVector(Elts) ||
2389 (isPackedStruct &&
2390 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2391 ParseToken(lltok::greater, "expected end of constant"))
2392 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002393
Chris Lattnerac161bf2009-01-02 07:01:27 +00002394 if (isPackedStruct) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002395 ID.ConstantStructElts = new Constant*[Elts.size()];
2396 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2397 ID.UIntVal = Elts.size();
2398 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002399 return false;
2400 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002401
Chris Lattnerac161bf2009-01-02 07:01:27 +00002402 if (Elts.empty())
2403 return Error(ID.Loc, "constant vector must not be empty");
2404
Duncan Sands9dff9be2010-02-15 16:12:20 +00002405 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002406 !Elts[0]->getType()->isFloatingPointTy() &&
2407 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002408 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002409 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002410
Chris Lattnerac161bf2009-01-02 07:01:27 +00002411 // Verify that all the vector elements have the same type.
2412 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2413 if (Elts[i]->getType() != Elts[0]->getType())
2414 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002415 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002416 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002417
Chris Lattner69229312011-02-15 00:14:00 +00002418 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002419 ID.Kind = ValID::t_Constant;
2420 return false;
2421 }
2422 case lltok::lsquare: { // Array Constant
2423 Lex.Lex();
2424 SmallVector<Constant*, 16> Elts;
2425 LocTy FirstEltLoc = Lex.getLoc();
2426 if (ParseGlobalValueVector(Elts) ||
2427 ParseToken(lltok::rsquare, "expected end of array constant"))
2428 return true;
2429
2430 // Handle empty element.
2431 if (Elts.empty()) {
2432 // Use undef instead of an array because it's inconvenient to determine
2433 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002434 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002435 return false;
2436 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002437
Chris Lattnerac161bf2009-01-02 07:01:27 +00002438 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002439 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002440 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002441
Owen Anderson4056ca92009-07-29 22:17:13 +00002442 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002443
Chris Lattnerac161bf2009-01-02 07:01:27 +00002444 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002445 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002446 if (Elts[i]->getType() != Elts[0]->getType())
2447 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002448 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002449 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002450 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002451
Jay Foad83be3612011-06-22 09:24:39 +00002452 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002453 ID.Kind = ValID::t_Constant;
2454 return false;
2455 }
2456 case lltok::kw_c: // c "foo"
2457 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002458 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2459 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002460 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2461 ID.Kind = ValID::t_Constant;
2462 return false;
2463
2464 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002465 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2466 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002467 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002468 Lex.Lex();
2469 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002470 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002471 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002472 ParseStringConstant(ID.StrVal) ||
2473 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002474 ParseToken(lltok::StringConstant, "expected constraint string"))
2475 return true;
2476 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002477 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002478 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002479 ID.Kind = ValID::t_InlineAsm;
2480 return false;
2481 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002482
Chris Lattner3432c622009-10-28 03:39:23 +00002483 case lltok::kw_blockaddress: {
2484 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2485 Lex.Lex();
2486
2487 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002488
Chris Lattner3432c622009-10-28 03:39:23 +00002489 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2490 ParseValID(Fn) ||
2491 ParseToken(lltok::comma, "expected comma in block address expression")||
2492 ParseValID(Label) ||
2493 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2494 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002495
Chris Lattner3432c622009-10-28 03:39:23 +00002496 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2497 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002498 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002499 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002500
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002501 // Try to find the function (but skip it if it's forward-referenced).
2502 GlobalValue *GV = nullptr;
2503 if (Fn.Kind == ValID::t_GlobalID) {
2504 if (Fn.UIntVal < NumberedVals.size())
2505 GV = NumberedVals[Fn.UIntVal];
2506 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2507 GV = M->getNamedValue(Fn.StrVal);
2508 }
2509 Function *F = nullptr;
2510 if (GV) {
2511 // Confirm that it's actually a function with a definition.
2512 if (!isa<Function>(GV))
2513 return Error(Fn.Loc, "expected function name in blockaddress");
2514 F = cast<Function>(GV);
2515 if (F->isDeclaration())
2516 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2517 }
2518
2519 if (!F) {
2520 // Make a global variable as a placeholder for this reference.
2521 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2522 if (!FwdRef)
2523 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2524 GlobalValue::InternalLinkage, nullptr, "");
2525 ID.ConstantVal = FwdRef;
2526 ID.Kind = ValID::t_Constant;
2527 return false;
2528 }
2529
2530 // We found the function; now find the basic block. Don't use PFS, since we
2531 // might be inside a constant expression.
2532 BasicBlock *BB;
2533 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2534 if (Label.Kind == ValID::t_LocalID)
2535 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2536 else
2537 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2538 if (!BB)
2539 return Error(Label.Loc, "referenced value is not a basic block");
2540 } else {
2541 if (Label.Kind == ValID::t_LocalID)
2542 return Error(Label.Loc, "cannot take address of numeric label after "
2543 "the function is defined");
2544 BB = dyn_cast_or_null<BasicBlock>(
2545 F->getValueSymbolTable().lookup(Label.StrVal));
2546 if (!BB)
2547 return Error(Label.Loc, "referenced value is not a basic block");
2548 }
2549
2550 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002551 ID.Kind = ValID::t_Constant;
2552 return false;
2553 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002554
Chris Lattnerac161bf2009-01-02 07:01:27 +00002555 case lltok::kw_trunc:
2556 case lltok::kw_zext:
2557 case lltok::kw_sext:
2558 case lltok::kw_fptrunc:
2559 case lltok::kw_fpext:
2560 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002561 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002562 case lltok::kw_uitofp:
2563 case lltok::kw_sitofp:
2564 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002565 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002566 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002567 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002568 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002569 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002570 Constant *SrcVal;
2571 Lex.Lex();
2572 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2573 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002574 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002575 ParseType(DestTy) ||
2576 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2577 return true;
2578 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2579 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002580 getTypeString(SrcVal->getType()) + "' to '" +
2581 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002582 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002583 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002584 ID.Kind = ValID::t_Constant;
2585 return false;
2586 }
2587 case lltok::kw_extractvalue: {
2588 Lex.Lex();
2589 Constant *Val;
2590 SmallVector<unsigned, 4> Indices;
2591 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2592 ParseGlobalTypeAndValue(Val) ||
2593 ParseIndexList(Indices) ||
2594 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2595 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002596
Chris Lattner392be582010-02-12 20:49:41 +00002597 if (!Val->getType()->isAggregateType())
2598 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002599 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002600 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002601 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002602 ID.Kind = ValID::t_Constant;
2603 return false;
2604 }
2605 case lltok::kw_insertvalue: {
2606 Lex.Lex();
2607 Constant *Val0, *Val1;
2608 SmallVector<unsigned, 4> Indices;
2609 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2610 ParseGlobalTypeAndValue(Val0) ||
2611 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2612 ParseGlobalTypeAndValue(Val1) ||
2613 ParseIndexList(Indices) ||
2614 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2615 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002616 if (!Val0->getType()->isAggregateType())
2617 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002618 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002619 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002620 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002621 ID.Kind = ValID::t_Constant;
2622 return false;
2623 }
2624 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002625 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002626 unsigned PredVal, Opc = Lex.getUIntVal();
2627 Constant *Val0, *Val1;
2628 Lex.Lex();
2629 if (ParseCmpPredicate(PredVal, Opc) ||
2630 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2631 ParseGlobalTypeAndValue(Val0) ||
2632 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2633 ParseGlobalTypeAndValue(Val1) ||
2634 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2635 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002636
Chris Lattnerac161bf2009-01-02 07:01:27 +00002637 if (Val0->getType() != Val1->getType())
2638 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002639
Chris Lattnerac161bf2009-01-02 07:01:27 +00002640 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002641
Chris Lattnerac161bf2009-01-02 07:01:27 +00002642 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002643 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002644 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002645 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002646 } else {
2647 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002648 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002649 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002650 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002651 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002652 }
2653 ID.Kind = ValID::t_Constant;
2654 return false;
2655 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002656
Chris Lattnerac161bf2009-01-02 07:01:27 +00002657 // Binary Operators.
2658 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002659 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002660 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002661 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002662 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002663 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002664 case lltok::kw_udiv:
2665 case lltok::kw_sdiv:
2666 case lltok::kw_fdiv:
2667 case lltok::kw_urem:
2668 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002669 case lltok::kw_frem:
2670 case lltok::kw_shl:
2671 case lltok::kw_lshr:
2672 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002673 bool NUW = false;
2674 bool NSW = false;
2675 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002676 unsigned Opc = Lex.getUIntVal();
2677 Constant *Val0, *Val1;
2678 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002679 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002680 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2681 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002682 if (EatIfPresent(lltok::kw_nuw))
2683 NUW = true;
2684 if (EatIfPresent(lltok::kw_nsw)) {
2685 NSW = true;
2686 if (EatIfPresent(lltok::kw_nuw))
2687 NUW = true;
2688 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002689 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2690 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002691 if (EatIfPresent(lltok::kw_exact))
2692 Exact = true;
2693 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002694 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2695 ParseGlobalTypeAndValue(Val0) ||
2696 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2697 ParseGlobalTypeAndValue(Val1) ||
2698 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2699 return true;
2700 if (Val0->getType() != Val1->getType())
2701 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002702 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002703 if (NUW)
2704 return Error(ModifierLoc, "nuw only applies to integer operations");
2705 if (NSW)
2706 return Error(ModifierLoc, "nsw only applies to integer operations");
2707 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002708 // Check that the type is valid for the operator.
2709 switch (Opc) {
2710 case Instruction::Add:
2711 case Instruction::Sub:
2712 case Instruction::Mul:
2713 case Instruction::UDiv:
2714 case Instruction::SDiv:
2715 case Instruction::URem:
2716 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002717 case Instruction::Shl:
2718 case Instruction::AShr:
2719 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002720 if (!Val0->getType()->isIntOrIntVectorTy())
2721 return Error(ID.Loc, "constexpr requires integer operands");
2722 break;
2723 case Instruction::FAdd:
2724 case Instruction::FSub:
2725 case Instruction::FMul:
2726 case Instruction::FDiv:
2727 case Instruction::FRem:
2728 if (!Val0->getType()->isFPOrFPVectorTy())
2729 return Error(ID.Loc, "constexpr requires fp operands");
2730 break;
2731 default: llvm_unreachable("Unknown binary operator!");
2732 }
Dan Gohman1b849082009-09-07 23:54:19 +00002733 unsigned Flags = 0;
2734 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2735 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002736 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002737 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002738 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002739 ID.Kind = ValID::t_Constant;
2740 return false;
2741 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002742
Chris Lattnerac161bf2009-01-02 07:01:27 +00002743 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002744 case lltok::kw_and:
2745 case lltok::kw_or:
2746 case lltok::kw_xor: {
2747 unsigned Opc = Lex.getUIntVal();
2748 Constant *Val0, *Val1;
2749 Lex.Lex();
2750 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2751 ParseGlobalTypeAndValue(Val0) ||
2752 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2753 ParseGlobalTypeAndValue(Val1) ||
2754 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2755 return true;
2756 if (Val0->getType() != Val1->getType())
2757 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002758 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002759 return Error(ID.Loc,
2760 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002761 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002762 ID.Kind = ValID::t_Constant;
2763 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002764 }
2765
Chris Lattnerac161bf2009-01-02 07:01:27 +00002766 case lltok::kw_getelementptr:
2767 case lltok::kw_shufflevector:
2768 case lltok::kw_insertelement:
2769 case lltok::kw_extractelement:
2770 case lltok::kw_select: {
2771 unsigned Opc = Lex.getUIntVal();
2772 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002773 bool InBounds = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002774 Lex.Lex();
Dan Gohman1639c392009-07-27 21:53:46 +00002775 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002776 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002777 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2778 ParseGlobalValueVector(Elts) ||
2779 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2780 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002781
Chris Lattnerac161bf2009-01-02 07:01:27 +00002782 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002783 if (Elts.size() == 0 ||
2784 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002785 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002786
Jay Foaded8db7d2011-07-21 14:31:17 +00002787 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foadd1b78492011-07-25 09:48:08 +00002788 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002789 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002790 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2791 InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002792 } else if (Opc == Instruction::Select) {
2793 if (Elts.size() != 3)
2794 return Error(ID.Loc, "expected three operands to select");
2795 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2796 Elts[2]))
2797 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002798 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002799 } else if (Opc == Instruction::ShuffleVector) {
2800 if (Elts.size() != 3)
2801 return Error(ID.Loc, "expected three operands to shufflevector");
2802 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2803 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002804 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002805 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002806 } else if (Opc == Instruction::ExtractElement) {
2807 if (Elts.size() != 2)
2808 return Error(ID.Loc, "expected two operands to extractelement");
2809 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2810 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002811 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002812 } else {
2813 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2814 if (Elts.size() != 3)
2815 return Error(ID.Loc, "expected three operands to insertelement");
2816 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2817 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002818 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002819 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002820 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002821
Chris Lattnerac161bf2009-01-02 07:01:27 +00002822 ID.Kind = ValID::t_Constant;
2823 return false;
2824 }
2825 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002826
Chris Lattnerac161bf2009-01-02 07:01:27 +00002827 Lex.Lex();
2828 return false;
2829}
2830
2831/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002832bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002833 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002834 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002835 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002836 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002837 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002838 if (V && !(C = dyn_cast<Constant>(V)))
2839 return Error(ID.Loc, "global values must be constants");
2840 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002841}
2842
Victor Hernandez9d75c962010-01-11 22:31:58 +00002843bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002844 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002845 return ParseType(Ty) ||
2846 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002847}
2848
Rafael Espindola83a362c2015-01-06 22:55:16 +00002849bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00002850 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002851
2852 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00002853 if (!EatIfPresent(lltok::kw_comdat))
2854 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002855
2856 if (EatIfPresent(lltok::lparen)) {
2857 if (Lex.getKind() != lltok::ComdatVar)
2858 return TokError("expected comdat variable");
2859 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2860 Lex.Lex();
2861 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2862 return true;
2863 } else {
2864 if (GlobalName.empty())
2865 return TokError("comdat cannot be unnamed");
2866 C = getComdat(GlobalName, KwLoc);
2867 }
2868
David Majnemerdad0a642014-06-27 18:19:56 +00002869 return false;
2870}
2871
Victor Hernandez9d75c962010-01-11 22:31:58 +00002872/// ParseGlobalValueVector
2873/// ::= /*empty*/
2874/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002875bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002876 // Empty list.
2877 if (Lex.getKind() == lltok::rbrace ||
2878 Lex.getKind() == lltok::rsquare ||
2879 Lex.getKind() == lltok::greater ||
2880 Lex.getKind() == lltok::rparen)
2881 return false;
2882
2883 Constant *C;
2884 if (ParseGlobalTypeAndValue(C)) return true;
2885 Elts.push_back(C);
2886
2887 while (EatIfPresent(lltok::comma)) {
2888 if (ParseGlobalTypeAndValue(C)) return true;
2889 Elts.push_back(C);
2890 }
2891
2892 return false;
2893}
2894
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00002895bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002896 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002897 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00002898 return true;
2899
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00002900 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002901 return false;
2902}
2903
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002904/// MDNode:
2905/// ::= !{ ... }
2906/// ::= !7
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002907/// ::= !MDLocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002908bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002909 if (Lex.getKind() == lltok::MetadataVar)
2910 return ParseSpecializedMDNode(N);
2911
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002912 return ParseToken(lltok::exclaim, "expected '!' here") ||
2913 ParseMDNodeTail(N);
2914}
2915
2916bool LLParser::ParseMDNodeTail(MDNode *&N) {
2917 // !{ ... }
2918 if (Lex.getKind() == lltok::lbrace)
2919 return ParseMDTuple(N);
2920
2921 // !42
2922 return ParseMDNodeID(N);
2923}
2924
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002925bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
2926 MDUnsignedField<uint32_t> &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002927 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
2928 return TokError("expected unsigned integer");
2929 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(Result.Max + 1ull);
2930
2931 if (Val64 > Result.Max)
2932 return TokError("value for '" + Name + "' too large, limit is " +
2933 Twine(Result.Max));
2934 Result.assign(Val64);
2935 Lex.Lex();
2936 return false;
2937}
2938
2939bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002940 Metadata *MD;
2941 if (ParseMetadata(MD, nullptr))
2942 return true;
2943
2944 Result.assign(MD);
2945 return false;
2946}
2947
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002948bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
2949 std::string S;
2950 if (ParseStringConstant(S))
2951 return true;
2952
2953 Result.assign(std::move(S));
2954 return false;
2955}
2956
2957bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
2958 SmallVector<Metadata *, 4> MDs;
2959 if (ParseMDNodeVector(MDs))
2960 return true;
2961
2962 Result.assign(std::move(MDs));
2963 return false;
2964}
2965
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002966template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00002967bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002968 do {
2969 if (Lex.getKind() != lltok::LabelStr)
2970 return TokError("expected field label here");
2971
2972 if (parseField())
2973 return true;
2974 } while (EatIfPresent(lltok::comma));
2975
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00002976 return false;
2977}
2978
2979template <class ParserTy>
2980bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
2981 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
2982 Lex.Lex();
2983
2984 if (ParseToken(lltok::lparen, "expected '(' here"))
2985 return true;
2986 if (Lex.getKind() != lltok::rparen)
2987 if (ParseMDFieldsImplBody(parseField))
2988 return true;
2989
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00002990 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002991 return ParseToken(lltok::rparen, "expected ')' here");
2992}
2993
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00002994template <class FieldTy>
2995bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
2996 if (Result.Seen)
2997 return TokError("field '" + Name + "' cannot be specified more than once");
2998
2999 LocTy Loc = Lex.getLoc();
3000 Lex.Lex();
3001 return ParseMDField(Loc, Name, Result);
3002}
3003
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003004bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3005 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3006#define DISPATCH_TO_PARSER(CLASS) \
3007 if (Lex.getStrVal() == #CLASS) \
3008 return Parse##CLASS(N, IsDistinct);
3009
3010 DISPATCH_TO_PARSER(MDLocation);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003011 DISPATCH_TO_PARSER(GenericDebugNode);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003012#undef DISPATCH_TO_PARSER
3013
3014 return TokError("expected metadata type");
3015}
3016
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003017#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3018#define NOP_FIELD(NAME, TYPE, INIT)
3019#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3020 if (!NAME.Seen) \
3021 return Error(ClosingLoc, "missing required field '" #NAME "'");
3022#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003023 if (Lex.getStrVal() == #NAME) \
3024 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003025#define PARSE_MD_FIELDS() \
3026 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3027 do { \
3028 LocTy ClosingLoc; \
3029 if (ParseMDFieldsImpl([&]() -> bool { \
3030 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3031 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3032 }, ClosingLoc)) \
3033 return true; \
3034 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3035 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003036#define GET_OR_DISTINCT(CLASS, ARGS) \
3037 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003038
3039/// ParseMDLocationFields:
3040/// ::= !MDLocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3041bool LLParser::ParseMDLocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003042#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3043 OPTIONAL(line, MDUnsignedField<uint32_t>, (0, ~0u >> 8)); \
3044 OPTIONAL(column, MDUnsignedField<uint32_t>, (0, ~0u >> 16)); \
3045 REQUIRED(scope, MDField, ); \
3046 OPTIONAL(inlinedAt, MDField, );
3047 PARSE_MD_FIELDS();
3048#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003049
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003050 auto get = (IsDistinct ? MDLocation::getDistinct : MDLocation::get);
3051 Result = get(Context, line.Val, column.Val, scope.Val, inlinedAt.Val);
3052 return false;
3053}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003054
3055/// ParseGenericDebugNode:
3056/// ::= !GenericDebugNode(tag: 15, header: "...", operands: {...})
3057bool LLParser::ParseGenericDebugNode(MDNode *&Result, bool IsDistinct) {
3058#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3059 REQUIRED(tag, MDUnsignedField<uint32_t>, (0, ~0u >> 16)); \
3060 OPTIONAL(header, MDStringField, ); \
3061 OPTIONAL(operands, MDFieldList, );
3062 PARSE_MD_FIELDS();
3063#undef VISIT_MD_FIELDS
3064
3065 Result = GET_OR_DISTINCT(GenericDebugNode,
3066 (Context, tag.Val, header.Val, operands.Val));
3067 return false;
3068}
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003069#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003070#undef NOP_FIELD
3071#undef REQUIRE_FIELD
3072#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003073
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003074/// ParseMetadataAsValue
3075/// ::= metadata i32 %local
3076/// ::= metadata i32 @global
3077/// ::= metadata i32 7
3078/// ::= metadata !0
3079/// ::= metadata !{...}
3080/// ::= metadata !"string"
3081bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3082 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003083 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003084 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003085 return true;
3086
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003087 V = MetadataAsValue::get(Context, MD);
3088 return false;
3089}
3090
3091/// ParseValueAsMetadata
3092/// ::= i32 %local
3093/// ::= i32 @global
3094/// ::= i32 7
3095bool LLParser::ParseValueAsMetadata(Metadata *&MD, PerFunctionState *PFS) {
3096 Type *Ty;
3097 LocTy Loc;
3098 if (ParseType(Ty, "expected metadata operand", Loc))
3099 return true;
3100 if (Ty->isMetadataTy())
3101 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3102
3103 Value *V;
3104 if (ParseValue(Ty, V, PFS))
3105 return true;
3106
3107 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003108 return false;
3109}
3110
3111/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003112/// ::= i32 %local
3113/// ::= i32 @global
3114/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00003115/// ::= !42
3116/// ::= !{...}
3117/// ::= !"string"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003118/// ::= !MDLocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003119bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003120 if (Lex.getKind() == lltok::MetadataVar) {
3121 MDNode *N;
3122 if (ParseSpecializedMDNode(N))
3123 return true;
3124 MD = N;
3125 return false;
3126 }
3127
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003128 // ValueAsMetadata:
3129 // <type> <value>
3130 if (Lex.getKind() != lltok::exclaim)
3131 return ParseValueAsMetadata(MD, PFS);
3132
3133 // '!'.
3134 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3135 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00003136
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003137 // MDString:
3138 // ::= '!' STRINGCONSTANT
3139 if (Lex.getKind() == lltok::StringConstant) {
3140 MDString *S;
3141 if (ParseMDString(S))
3142 return true;
3143 MD = S;
3144 return false;
3145 }
3146
Dan Gohman8939ba332010-07-14 18:26:50 +00003147 // MDNode:
3148 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003149 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003150 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003151 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003152 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003153 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00003154 return false;
3155}
3156
Victor Hernandez9d75c962010-01-11 22:31:58 +00003157
3158//===----------------------------------------------------------------------===//
3159// Function Parsing.
3160//===----------------------------------------------------------------------===//
3161
Chris Lattner229907c2011-07-18 04:54:35 +00003162bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003163 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003164 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003165 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003166
Chris Lattnerac161bf2009-01-02 07:01:27 +00003167 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003168 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003169 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3170 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003171 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003172 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003173 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3174 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003175 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003176 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00003177 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003178 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00003179 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003180 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3181 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003182 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003183 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003184 return false;
3185 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003186 case ValID::t_GlobalName:
3187 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003188 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003189 case ValID::t_GlobalID:
3190 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003191 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003192 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003193 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003194 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00003195 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00003196 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003197 return false;
3198 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00003199 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003200 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3201 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003202
Dan Gohman518cda42011-12-17 00:04:22 +00003203 // The lexer has no type info, so builds all half, float, and double FP
3204 // constants as double. Fix this here. Long double does not need this.
3205 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003206 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00003207 if (Ty->isHalfTy())
3208 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3209 &Ignored);
3210 else if (Ty->isFloatTy())
3211 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3212 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003213 }
Owen Anderson69c464d2009-07-27 20:59:43 +00003214 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003215
Chris Lattner8f57d29e2009-01-05 18:24:23 +00003216 if (V->getType() != Ty)
3217 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003218 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003219
Chris Lattnerac161bf2009-01-02 07:01:27 +00003220 return false;
3221 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00003222 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003223 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003224 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003225 return false;
3226 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00003227 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003228 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00003229 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003230 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003231 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00003232 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00003233 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00003234 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003235 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00003236 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003237 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00003238 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00003239 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003240 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00003241 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003242 return false;
3243 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00003244 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003245 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00003246
Chris Lattnerac161bf2009-01-02 07:01:27 +00003247 V = ID.ConstantVal;
3248 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003249 case ValID::t_ConstantStruct:
3250 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00003251 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003252 if (ST->getNumElements() != ID.UIntVal)
3253 return Error(ID.Loc,
3254 "initializer with struct type has wrong # elements");
3255 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3256 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003257
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003258 // Verify that the elements are compatible with the structtype.
3259 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3260 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3261 return Error(ID.Loc, "element " + Twine(i) +
3262 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003263
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003264 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3265 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003266 } else
3267 return Error(ID.Loc, "constant expression type mismatch");
3268 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003269 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00003270 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003271}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003272
Chris Lattner229907c2011-07-18 04:54:35 +00003273bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003274 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003275 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003276 return ParseValID(ID, PFS) ||
3277 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003278}
3279
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003280bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003281 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003282 return ParseType(Ty) ||
3283 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003284}
3285
Chris Lattner3ed871f2009-10-27 19:13:16 +00003286bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3287 PerFunctionState &PFS) {
3288 Value *V;
3289 Loc = Lex.getLoc();
3290 if (ParseTypeAndValue(V, PFS)) return true;
3291 if (!isa<BasicBlock>(V))
3292 return Error(Loc, "expected a basic block");
3293 BB = cast<BasicBlock>(V);
3294 return false;
3295}
3296
3297
Chris Lattnerac161bf2009-01-02 07:01:27 +00003298/// FunctionHeader
3299/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00003300/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003301/// OptionalAlign OptGC OptionalPrefix OptionalPrologue
Chris Lattnerac161bf2009-01-02 07:01:27 +00003302bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3303 // Parse the linkage.
3304 LocTy LinkageLoc = Lex.getLoc();
3305 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003306
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00003307 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00003308 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00003309 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003310 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003311 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003312 LocTy RetTypeLoc = Lex.getLoc();
3313 if (ParseOptionalLinkage(Linkage) ||
3314 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00003315 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003316 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003317 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003318 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003319 return true;
3320
3321 // Verify that the linkage is ok.
3322 switch ((GlobalValue::LinkageTypes)Linkage) {
3323 case GlobalValue::ExternalLinkage:
3324 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00003325 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003326 if (isDefine)
3327 return Error(LinkageLoc, "invalid linkage for function definition");
3328 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00003329 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003330 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00003331 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00003332 case GlobalValue::LinkOnceAnyLinkage:
3333 case GlobalValue::LinkOnceODRLinkage:
3334 case GlobalValue::WeakAnyLinkage:
3335 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003336 if (!isDefine)
3337 return Error(LinkageLoc, "invalid linkage for function declaration");
3338 break;
3339 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00003340 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003341 return Error(LinkageLoc, "invalid function linkage type");
3342 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003343
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003344 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3345 return Error(LinkageLoc,
3346 "symbol with local linkage must have default visibility");
3347
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003348 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003349 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003350
Chris Lattnerac161bf2009-01-02 07:01:27 +00003351 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00003352
3353 std::string FunctionName;
3354 if (Lex.getKind() == lltok::GlobalVar) {
3355 FunctionName = Lex.getStrVal();
3356 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3357 unsigned NameID = Lex.getUIntVal();
3358
3359 if (NameID != NumberedVals.size())
3360 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003361 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00003362 } else {
3363 return TokError("expected function name");
3364 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003365
Chris Lattner3822f632009-01-02 08:05:26 +00003366 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003367
Chris Lattner3822f632009-01-02 08:05:26 +00003368 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003369 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003370
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003371 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003372 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00003373 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003374 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003375 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003376 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003377 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00003378 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003379 bool UnnamedAddr;
3380 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00003381 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003382 Constant *Prologue = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00003383 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00003384
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003385 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003386 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3387 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003388 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00003389 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003390 (EatIfPresent(lltok::kw_section) &&
3391 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00003392 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003393 ParseOptionalAlignment(Alignment) ||
3394 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003395 ParseStringConstant(GC)) ||
3396 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003397 ParseGlobalTypeAndValue(Prefix)) ||
3398 (EatIfPresent(lltok::kw_prologue) &&
3399 ParseGlobalTypeAndValue(Prologue)))
Chris Lattner3822f632009-01-02 08:05:26 +00003400 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003401
Michael Gottesman41748d72013-06-27 00:25:01 +00003402 if (FuncAttrs.contains(Attribute::Builtin))
3403 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00003404
Chris Lattnerac161bf2009-01-02 07:01:27 +00003405 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00003406 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00003407 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003408 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003409 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003410
Chris Lattnerac161bf2009-01-02 07:01:27 +00003411 // Okay, if we got here, the function is syntactically valid. Convert types
3412 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00003413 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00003414 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003415
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003416 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003417 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3418 AttributeSet::ReturnIndex,
3419 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003420
Chris Lattnerac161bf2009-01-02 07:01:27 +00003421 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003422 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003423 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3424 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003425 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3426 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003427 }
3428
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003429 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003430 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3431 AttributeSet::FunctionIndex,
3432 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003433
Bill Wendlinge94d8432012-12-07 23:16:57 +00003434 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003435
Bill Wendling749a43d2012-12-30 13:50:49 +00003436 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003437 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3438
Chris Lattner229907c2011-07-18 04:54:35 +00003439 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00003440 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00003441 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003442
Craig Topper2617dcc2014-04-15 06:32:26 +00003443 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003444 if (!FunctionName.empty()) {
3445 // If this was a definition of a forward reference, remove the definition
3446 // from the forward reference table and fill in the forward ref.
3447 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3448 ForwardRefVals.find(FunctionName);
3449 if (FRVI != ForwardRefVals.end()) {
3450 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00003451 if (!Fn)
3452 return Error(FRVI->second.second, "invalid forward reference to "
3453 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00003454 if (Fn->getType() != PFT)
3455 return Error(FRVI->second.second, "invalid forward reference to "
3456 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003457
Chris Lattnerac161bf2009-01-02 07:01:27 +00003458 ForwardRefVals.erase(FRVI);
3459 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00003460 // Reject redefinitions.
3461 return Error(NameLoc, "invalid redefinition of function '" +
3462 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00003463 } else if (M->getNamedValue(FunctionName)) {
3464 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003465 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003466
Dan Gohman399d6ae2009-08-29 23:37:49 +00003467 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003468 // If this is a definition of a forward referenced function, make sure the
3469 // types agree.
3470 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3471 = ForwardRefValIDs.find(NumberedVals.size());
3472 if (I != ForwardRefValIDs.end()) {
3473 Fn = cast<Function>(I->second.first);
3474 if (Fn->getType() != PFT)
3475 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003476 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003477 ForwardRefValIDs.erase(I);
3478 }
3479 }
3480
Craig Topper2617dcc2014-04-15 06:32:26 +00003481 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003482 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3483 else // Move the forward-reference to the correct spot in the module.
3484 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3485
3486 if (FunctionName.empty())
3487 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003488
Chris Lattnerac161bf2009-01-02 07:01:27 +00003489 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3490 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00003491 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003492 Fn->setCallingConv(CC);
3493 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003494 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003495 Fn->setAlignment(Alignment);
3496 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00003497 Fn->setComdat(C);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003498 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003499 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003500 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003501 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003502
Chris Lattnerac161bf2009-01-02 07:01:27 +00003503 // Add all of the arguments we parsed to the function.
3504 Function::arg_iterator ArgIt = Fn->arg_begin();
3505 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3506 // If the argument has a name, insert it into the argument symbol table.
3507 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003508
Chris Lattnerac161bf2009-01-02 07:01:27 +00003509 // Set the name, if it conflicted, it will be auto-renamed.
3510 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003511
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00003512 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003513 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3514 ArgList[i].Name + "'");
3515 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003516
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003517 if (isDefine)
3518 return false;
3519
Robin Morisset039781e2014-08-29 21:53:01 +00003520 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003521 ValID ID;
3522 if (FunctionName.empty()) {
3523 ID.Kind = ValID::t_GlobalID;
3524 ID.UIntVal = NumberedVals.size() - 1;
3525 } else {
3526 ID.Kind = ValID::t_GlobalName;
3527 ID.StrVal = FunctionName;
3528 }
3529 auto Blocks = ForwardRefBlockAddresses.find(ID);
3530 if (Blocks != ForwardRefBlockAddresses.end())
3531 return Error(Blocks->first.Loc,
3532 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003533 return false;
3534}
3535
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003536bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
3537 ValID ID;
3538 if (FunctionNumber == -1) {
3539 ID.Kind = ValID::t_GlobalName;
3540 ID.StrVal = F.getName();
3541 } else {
3542 ID.Kind = ValID::t_GlobalID;
3543 ID.UIntVal = FunctionNumber;
3544 }
3545
3546 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
3547 if (Blocks == P.ForwardRefBlockAddresses.end())
3548 return false;
3549
3550 for (const auto &I : Blocks->second) {
3551 const ValID &BBID = I.first;
3552 GlobalValue *GV = I.second;
3553
3554 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
3555 "Expected local id or name");
3556 BasicBlock *BB;
3557 if (BBID.Kind == ValID::t_LocalName)
3558 BB = GetBB(BBID.StrVal, BBID.Loc);
3559 else
3560 BB = GetBB(BBID.UIntVal, BBID.Loc);
3561 if (!BB)
3562 return P.Error(BBID.Loc, "referenced value is not a basic block");
3563
3564 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
3565 GV->eraseFromParent();
3566 }
3567
3568 P.ForwardRefBlockAddresses.erase(Blocks);
3569 return false;
3570}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003571
3572/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003573/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00003574bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00003575 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003576 return TokError("expected '{' in function body");
3577 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003578
Chris Lattner3432c622009-10-28 03:39:23 +00003579 int FunctionNumber = -1;
3580 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003581
Chris Lattner3432c622009-10-28 03:39:23 +00003582 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003583
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003584 // Resolve block addresses and allow basic blocks to be forward-declared
3585 // within this function.
3586 if (PFS.resolveForwardRefBlockAddresses())
3587 return true;
3588 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
3589
Chris Lattnerbbddd962010-01-09 19:20:07 +00003590 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003591 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00003592 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003593
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003594 while (Lex.getKind() != lltok::rbrace &&
3595 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003596 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003597
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003598 while (Lex.getKind() != lltok::rbrace)
3599 if (ParseUseListOrder(&PFS))
3600 return true;
3601
Chris Lattnerac161bf2009-01-02 07:01:27 +00003602 // Eat the }.
3603 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003604
Chris Lattnerac161bf2009-01-02 07:01:27 +00003605 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00003606 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003607}
3608
3609/// ParseBasicBlock
3610/// ::= LabelStr? Instruction*
3611bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3612 // If this basic block starts out with a name, remember it.
3613 std::string Name;
3614 LocTy NameLoc = Lex.getLoc();
3615 if (Lex.getKind() == lltok::LabelStr) {
3616 Name = Lex.getStrVal();
3617 Lex.Lex();
3618 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003619
Chris Lattnerac161bf2009-01-02 07:01:27 +00003620 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003621 if (!BB) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003622
Chris Lattnerac161bf2009-01-02 07:01:27 +00003623 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003624
Chris Lattnerac161bf2009-01-02 07:01:27 +00003625 // Parse the instructions in this block until we get a terminator.
3626 Instruction *Inst;
3627 do {
3628 // This instruction may have three possibilities for a name: a) none
3629 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3630 LocTy NameLoc = Lex.getLoc();
3631 int NameID = -1;
3632 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003633
Chris Lattnerac161bf2009-01-02 07:01:27 +00003634 if (Lex.getKind() == lltok::LocalVarID) {
3635 NameID = Lex.getUIntVal();
3636 Lex.Lex();
3637 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3638 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00003639 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003640 NameStr = Lex.getStrVal();
3641 Lex.Lex();
3642 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3643 return true;
3644 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003645
Chris Lattner77b89dc2009-12-30 05:23:43 +00003646 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00003647 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00003648 case InstError: return true;
3649 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003650 BB->getInstList().push_back(Inst);
3651
Chris Lattner77b89dc2009-12-30 05:23:43 +00003652 // With a normal result, we check to see if the instruction is followed by
3653 // a comma and metadata.
3654 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00003655 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003656 return true;
3657 break;
3658 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003659 BB->getInstList().push_back(Inst);
3660
Chris Lattner77b89dc2009-12-30 05:23:43 +00003661 // If the instruction parser ate an extra comma at the end of it, it
3662 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00003663 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003664 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003665 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00003666 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003667
Chris Lattnerac161bf2009-01-02 07:01:27 +00003668 // Set the name on the instruction.
3669 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3670 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003671
Chris Lattnerac161bf2009-01-02 07:01:27 +00003672 return false;
3673}
3674
3675//===----------------------------------------------------------------------===//
3676// Instruction Parsing.
3677//===----------------------------------------------------------------------===//
3678
3679/// ParseInstruction - Parse one of the many different instructions.
3680///
Chris Lattner77b89dc2009-12-30 05:23:43 +00003681int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3682 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003683 lltok::Kind Token = Lex.getKind();
3684 if (Token == lltok::Eof)
3685 return TokError("found end of file when expecting more instructions");
3686 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00003687 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003688 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003689
Chris Lattnerac161bf2009-01-02 07:01:27 +00003690 switch (Token) {
3691 default: return Error(Loc, "expected instruction opcode");
3692 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00003693 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003694 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3695 case lltok::kw_br: return ParseBr(Inst, PFS);
3696 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003697 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003698 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003699 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003700 // Binary Operators.
3701 case lltok::kw_add:
3702 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003703 case lltok::kw_mul:
3704 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00003705 bool NUW = EatIfPresent(lltok::kw_nuw);
3706 bool NSW = EatIfPresent(lltok::kw_nsw);
3707 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003708
Chris Lattnera676c0f2011-02-07 16:40:21 +00003709 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003710
Chris Lattnera676c0f2011-02-07 16:40:21 +00003711 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3712 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3713 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003714 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003715 case lltok::kw_fadd:
3716 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00003717 case lltok::kw_fmul:
3718 case lltok::kw_fdiv:
3719 case lltok::kw_frem: {
3720 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3721 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3722 if (Res != 0)
3723 return Res;
3724 if (FMF.any())
3725 Inst->setFastMathFlags(FMF);
3726 return 0;
3727 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003728
Chris Lattner35315d02011-02-06 21:44:57 +00003729 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003730 case lltok::kw_udiv:
3731 case lltok::kw_lshr:
3732 case lltok::kw_ashr: {
3733 bool Exact = EatIfPresent(lltok::kw_exact);
3734
3735 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3736 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3737 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003738 }
3739
Chris Lattnerac161bf2009-01-02 07:01:27 +00003740 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00003741 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003742 case lltok::kw_and:
3743 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00003744 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003745 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003746 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003747 // Casts.
3748 case lltok::kw_trunc:
3749 case lltok::kw_zext:
3750 case lltok::kw_sext:
3751 case lltok::kw_fptrunc:
3752 case lltok::kw_fpext:
3753 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003754 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003755 case lltok::kw_uitofp:
3756 case lltok::kw_sitofp:
3757 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003758 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003759 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00003760 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003761 // Other.
3762 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00003763 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003764 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3765 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3766 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3767 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00003768 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00003769 // Call.
3770 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3771 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3772 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003773 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00003774 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00003775 case lltok::kw_load: return ParseLoad(Inst, PFS);
3776 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00003777 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3778 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003779 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003780 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3781 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3782 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3783 }
3784}
3785
3786/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3787bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003788 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003789 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003790 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003791 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3792 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3793 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3794 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3795 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3796 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3797 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3798 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3799 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3800 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3801 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3802 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3803 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3804 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3805 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3806 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3807 }
3808 } else {
3809 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003810 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003811 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3812 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3813 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3814 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3815 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3816 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3817 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3818 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3819 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3820 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3821 }
3822 }
3823 Lex.Lex();
3824 return false;
3825}
3826
3827//===----------------------------------------------------------------------===//
3828// Terminator Instructions.
3829//===----------------------------------------------------------------------===//
3830
3831/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00003832/// ::= 'ret' void (',' !dbg, !1)*
3833/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00003834bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003835 PerFunctionState &PFS) {
3836 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00003837 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00003838 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003839
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003840 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003841
Chris Lattnerfdd87902009-10-05 05:54:46 +00003842 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003843 if (!ResType->isVoidTy())
3844 return Error(TypeLoc, "value doesn't match function result type '" +
3845 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003846
Owen Anderson55f1c092009-08-13 21:58:54 +00003847 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003848 return false;
3849 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003850
Chris Lattnerac161bf2009-01-02 07:01:27 +00003851 Value *RV;
3852 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003853
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003854 if (ResType != RV->getType())
3855 return Error(TypeLoc, "value doesn't match function result type '" +
3856 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003857
Owen Anderson55f1c092009-08-13 21:58:54 +00003858 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00003859 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003860}
3861
3862
3863/// ParseBr
3864/// ::= 'br' TypeAndValue
3865/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3866bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3867 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003868 Value *Op0;
3869 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003870 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003871
Chris Lattnerac161bf2009-01-02 07:01:27 +00003872 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3873 Inst = BranchInst::Create(BB);
3874 return false;
3875 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003876
Owen Anderson55f1c092009-08-13 21:58:54 +00003877 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003878 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003879
Chris Lattnerac161bf2009-01-02 07:01:27 +00003880 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003881 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003882 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003883 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003884 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003885
Chris Lattner3ed871f2009-10-27 19:13:16 +00003886 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003887 return false;
3888}
3889
3890/// ParseSwitch
3891/// Instruction
3892/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3893/// JumpTable
3894/// ::= (TypeAndValue ',' TypeAndValue)*
3895bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3896 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003897 Value *Cond;
3898 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003899 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3900 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003901 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003902 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3903 return true;
3904
Duncan Sands19d0b472010-02-16 11:11:14 +00003905 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003906 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003907
Chris Lattnerac161bf2009-01-02 07:01:27 +00003908 // Parse the jump table pairs.
3909 SmallPtrSet<Value*, 32> SeenCases;
3910 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3911 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003912 Value *Constant;
3913 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003914
Chris Lattnerac161bf2009-01-02 07:01:27 +00003915 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3916 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003917 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003918 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003919
David Blaikie70573dc2014-11-19 07:49:26 +00003920 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003921 return Error(CondLoc, "duplicate case value in switch");
3922 if (!isa<ConstantInt>(Constant))
3923 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003924
Chris Lattner3ed871f2009-10-27 19:13:16 +00003925 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003926 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003927
Chris Lattnerac161bf2009-01-02 07:01:27 +00003928 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003929
Chris Lattner3ed871f2009-10-27 19:13:16 +00003930 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003931 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3932 SI->addCase(Table[i].first, Table[i].second);
3933 Inst = SI;
3934 return false;
3935}
3936
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003937/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00003938/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003939/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3940bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003941 LocTy AddrLoc;
3942 Value *Address;
3943 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003944 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3945 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00003946 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003947
Duncan Sands19d0b472010-02-16 11:11:14 +00003948 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003949 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003950
Chris Lattner3ed871f2009-10-27 19:13:16 +00003951 // Parse the destination list.
3952 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003953
Chris Lattner3ed871f2009-10-27 19:13:16 +00003954 if (Lex.getKind() != lltok::rsquare) {
3955 BasicBlock *DestBB;
3956 if (ParseTypeAndBasicBlock(DestBB, PFS))
3957 return true;
3958 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003959
Chris Lattner3ed871f2009-10-27 19:13:16 +00003960 while (EatIfPresent(lltok::comma)) {
3961 if (ParseTypeAndBasicBlock(DestBB, PFS))
3962 return true;
3963 DestList.push_back(DestBB);
3964 }
3965 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003966
Chris Lattner3ed871f2009-10-27 19:13:16 +00003967 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3968 return true;
3969
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003970 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00003971 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3972 IBI->addDestination(DestList[i]);
3973 Inst = IBI;
3974 return false;
3975}
3976
3977
Chris Lattnerac161bf2009-01-02 07:01:27 +00003978/// ParseInvoke
3979/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3980/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3981bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3982 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00003983 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003984 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00003985 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003986 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003987 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003988 LocTy RetTypeLoc;
3989 ValID CalleeID;
3990 SmallVector<ParamInfo, 16> ArgList;
3991
Chris Lattner3ed871f2009-10-27 19:13:16 +00003992 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003993 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003994 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003995 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003996 ParseValID(CalleeID) ||
3997 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003998 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3999 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004000 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004001 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004002 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004003 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004004 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004005
Chris Lattnerac161bf2009-01-02 07:01:27 +00004006 // If RetType is a non-function pointer type, then this is the short syntax
4007 // for the call, which means that RetType is just the return type. Infer the
4008 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00004009 PointerType *PFTy = nullptr;
4010 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004011 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4012 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4013 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004014 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004015 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4016 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004017
Chris Lattnerac161bf2009-01-02 07:01:27 +00004018 if (!FunctionType::isValidReturnType(RetType))
4019 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004020
Owen Anderson4056ca92009-07-29 22:17:13 +00004021 Ty = FunctionType::get(RetType, ParamTypes, false);
4022 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004023 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004024
Chris Lattnerac161bf2009-01-02 07:01:27 +00004025 // Look up the callee.
4026 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004027 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004028
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004029 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004030 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004031 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004032 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4033 AttributeSet::ReturnIndex,
4034 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004035
Chris Lattnerac161bf2009-01-02 07:01:27 +00004036 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004037
Chris Lattnerac161bf2009-01-02 07:01:27 +00004038 // Loop through FunctionType's arguments and ensure they are specified
4039 // correctly. Also, gather any parameter attributes.
4040 FunctionType::param_iterator I = Ty->param_begin();
4041 FunctionType::param_iterator E = Ty->param_end();
4042 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004043 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004044 if (I != E) {
4045 ExpectedTy = *I++;
4046 } else if (!Ty->isVarArg()) {
4047 return Error(ArgList[i].Loc, "too many arguments specified");
4048 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004049
Chris Lattnerac161bf2009-01-02 07:01:27 +00004050 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4051 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004052 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004053 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004054 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4055 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004056 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4057 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004058 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004059
Chris Lattnerac161bf2009-01-02 07:01:27 +00004060 if (I != E)
4061 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004062
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004063 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004064 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4065 AttributeSet::FunctionIndex,
4066 FnAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004067
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004068 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004069 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004070
Jay Foad5bd375a2011-07-15 08:37:34 +00004071 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004072 II->setCallingConv(CC);
4073 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004074 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004075 Inst = II;
4076 return false;
4077}
4078
Bill Wendlingf891bf82011-07-31 06:30:59 +00004079/// ParseResume
4080/// ::= 'resume' TypeAndValue
4081bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4082 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004083 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4084 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004085
Bill Wendlingf891bf82011-07-31 06:30:59 +00004086 ResumeInst *RI = ResumeInst::Create(Exn);
4087 Inst = RI;
4088 return false;
4089}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004090
4091//===----------------------------------------------------------------------===//
4092// Binary Operators.
4093//===----------------------------------------------------------------------===//
4094
4095/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004096/// ::= ArithmeticOps TypeAndValue ',' Value
4097///
4098/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4099/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00004100bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004101 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004102 LocTy Loc; Value *LHS, *RHS;
4103 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4104 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4105 ParseValue(LHS->getType(), RHS, PFS))
4106 return true;
4107
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004108 bool Valid;
4109 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00004110 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004111 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00004112 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4113 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004114 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00004115 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4116 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004117 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004118
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004119 if (!Valid)
4120 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004121
Chris Lattnerac161bf2009-01-02 07:01:27 +00004122 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4123 return false;
4124}
4125
4126/// ParseLogical
4127/// ::= ArithmeticOps TypeAndValue ',' Value {
4128bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4129 unsigned Opc) {
4130 LocTy Loc; Value *LHS, *RHS;
4131 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4132 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4133 ParseValue(LHS->getType(), RHS, PFS))
4134 return true;
4135
Duncan Sands9dff9be2010-02-15 16:12:20 +00004136 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004137 return Error(Loc,"instruction requires integer or integer vector operands");
4138
4139 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4140 return false;
4141}
4142
4143
4144/// ParseCompare
4145/// ::= 'icmp' IPredicates TypeAndValue ',' Value
4146/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004147bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4148 unsigned Opc) {
4149 // Parse the integer/fp comparison predicate.
4150 LocTy Loc;
4151 unsigned Pred;
4152 Value *LHS, *RHS;
4153 if (ParseCmpPredicate(Pred, Opc) ||
4154 ParseTypeAndValue(LHS, Loc, PFS) ||
4155 ParseToken(lltok::comma, "expected ',' after compare value") ||
4156 ParseValue(LHS->getType(), RHS, PFS))
4157 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004158
Chris Lattnerac161bf2009-01-02 07:01:27 +00004159 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00004160 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004161 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004162 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004163 } else {
4164 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00004165 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00004166 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004167 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004168 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004169 }
4170 return false;
4171}
4172
4173//===----------------------------------------------------------------------===//
4174// Other Instructions.
4175//===----------------------------------------------------------------------===//
4176
4177
4178/// ParseCast
4179/// ::= CastOpc TypeAndValue 'to' Type
4180bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4181 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004182 LocTy Loc;
4183 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004184 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004185 if (ParseTypeAndValue(Op, Loc, PFS) ||
4186 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4187 ParseType(DestTy))
4188 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004189
Chris Lattner89d856e2009-03-01 00:53:13 +00004190 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4191 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004192 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004193 getTypeString(Op->getType()) + "' to '" +
4194 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00004195 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004196 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4197 return false;
4198}
4199
4200/// ParseSelect
4201/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4202bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4203 LocTy Loc;
4204 Value *Op0, *Op1, *Op2;
4205 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4206 ParseToken(lltok::comma, "expected ',' after select condition") ||
4207 ParseTypeAndValue(Op1, PFS) ||
4208 ParseToken(lltok::comma, "expected ',' after select value") ||
4209 ParseTypeAndValue(Op2, PFS))
4210 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004211
Chris Lattnerac161bf2009-01-02 07:01:27 +00004212 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4213 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004214
Chris Lattnerac161bf2009-01-02 07:01:27 +00004215 Inst = SelectInst::Create(Op0, Op1, Op2);
4216 return false;
4217}
4218
Chris Lattnerb55ab542009-01-05 08:18:44 +00004219/// ParseVA_Arg
4220/// ::= 'va_arg' TypeAndValue ',' Type
4221bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004222 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004223 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00004224 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004225 if (ParseTypeAndValue(Op, PFS) ||
4226 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00004227 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004228 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004229
Chris Lattnerb55ab542009-01-05 08:18:44 +00004230 if (!EltTy->isFirstClassType())
4231 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004232
4233 Inst = new VAArgInst(Op, EltTy);
4234 return false;
4235}
4236
4237/// ParseExtractElement
4238/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4239bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4240 LocTy Loc;
4241 Value *Op0, *Op1;
4242 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4243 ParseToken(lltok::comma, "expected ',' after extract value") ||
4244 ParseTypeAndValue(Op1, PFS))
4245 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004246
Chris Lattnerac161bf2009-01-02 07:01:27 +00004247 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4248 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004249
Eric Christopherc9742252009-07-25 02:28:41 +00004250 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004251 return false;
4252}
4253
4254/// ParseInsertElement
4255/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4256bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4257 LocTy Loc;
4258 Value *Op0, *Op1, *Op2;
4259 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4260 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4261 ParseTypeAndValue(Op1, PFS) ||
4262 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4263 ParseTypeAndValue(Op2, PFS))
4264 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004265
Chris Lattnerac161bf2009-01-02 07:01:27 +00004266 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00004267 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004268
Chris Lattnerac161bf2009-01-02 07:01:27 +00004269 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4270 return false;
4271}
4272
4273/// ParseShuffleVector
4274/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4275bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4276 LocTy Loc;
4277 Value *Op0, *Op1, *Op2;
4278 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4279 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4280 ParseTypeAndValue(Op1, PFS) ||
4281 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4282 ParseTypeAndValue(Op2, PFS))
4283 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004284
Chris Lattnerac161bf2009-01-02 07:01:27 +00004285 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00004286 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004287
Chris Lattnerac161bf2009-01-02 07:01:27 +00004288 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4289 return false;
4290}
4291
4292/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00004293/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004294int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004295 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004296 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004297
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004298 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004299 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4300 ParseValue(Ty, Op0, PFS) ||
4301 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004302 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004303 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4304 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004305
Chris Lattnerf4f03422009-12-30 05:27:33 +00004306 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004307 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4308 while (1) {
4309 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004310
Chris Lattner3822f632009-01-02 08:05:26 +00004311 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004312 break;
4313
Chris Lattnerf4f03422009-12-30 05:27:33 +00004314 if (Lex.getKind() == lltok::MetadataVar) {
4315 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00004316 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004317 }
Devang Patel8f842d32009-10-16 18:45:49 +00004318
Chris Lattner3822f632009-01-02 08:05:26 +00004319 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004320 ParseValue(Ty, Op0, PFS) ||
4321 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004322 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004323 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4324 return true;
4325 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004326
Chris Lattnerac161bf2009-01-02 07:01:27 +00004327 if (!Ty->isFirstClassType())
4328 return Error(TypeLoc, "phi node must have first class type");
4329
Jay Foad52131342011-03-30 11:28:46 +00004330 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004331 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4332 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4333 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004334 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004335}
4336
Bill Wendlingfae14752011-08-12 20:24:12 +00004337/// ParseLandingPad
4338/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4339/// Clause
4340/// ::= 'catch' TypeAndValue
4341/// ::= 'filter'
4342/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4343bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004344 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004345 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004346
4347 if (ParseType(Ty, TyLoc) ||
4348 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4349 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4350 return true;
4351
4352 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4353 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4354
4355 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4356 LandingPadInst::ClauseType CT;
4357 if (EatIfPresent(lltok::kw_catch))
4358 CT = LandingPadInst::Catch;
4359 else if (EatIfPresent(lltok::kw_filter))
4360 CT = LandingPadInst::Filter;
4361 else
4362 return TokError("expected 'catch' or 'filter' clause type");
4363
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004364 Value *V;
4365 LocTy VLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004366 if (ParseTypeAndValue(V, VLoc, PFS)) {
4367 delete LP;
4368 return true;
4369 }
4370
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00004371 // A 'catch' type expects a non-array constant. A filter clause expects an
4372 // array constant.
4373 if (CT == LandingPadInst::Catch) {
4374 if (isa<ArrayType>(V->getType()))
4375 Error(VLoc, "'catch' clause has an invalid type");
4376 } else {
4377 if (!isa<ArrayType>(V->getType()))
4378 Error(VLoc, "'filter' clause has an invalid type");
4379 }
4380
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004381 LP->addClause(cast<Constant>(V));
Bill Wendlingfae14752011-08-12 20:24:12 +00004382 }
4383
4384 Inst = LP;
4385 return false;
4386}
4387
Chris Lattnerac161bf2009-01-02 07:01:27 +00004388/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00004389/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4390/// ParameterList OptionalAttrs
4391/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4392/// ParameterList OptionalAttrs
4393/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004394/// ParameterList OptionalAttrs
4395bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00004396 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00004397 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004398 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004399 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004400 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004401 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004402 LocTy RetTypeLoc;
4403 ValID CalleeID;
4404 SmallVector<ParamInfo, 16> ArgList;
4405 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004406
Reid Kleckner5772b772014-04-24 20:14:34 +00004407 if ((TCK != CallInst::TCK_None &&
4408 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004409 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004410 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004411 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004412 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00004413 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
4414 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004415 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004416 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004417 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004418
Chris Lattnerac161bf2009-01-02 07:01:27 +00004419 // If RetType is a non-function pointer type, then this is the short syntax
4420 // for the call, which means that RetType is just the return type. Infer the
4421 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00004422 PointerType *PFTy = nullptr;
4423 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004424 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4425 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4426 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004427 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00004428 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4429 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004430
Chris Lattnerac161bf2009-01-02 07:01:27 +00004431 if (!FunctionType::isValidReturnType(RetType))
4432 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004433
Owen Anderson4056ca92009-07-29 22:17:13 +00004434 Ty = FunctionType::get(RetType, ParamTypes, false);
4435 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004436 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004437
Chris Lattnerac161bf2009-01-02 07:01:27 +00004438 // Look up the callee.
4439 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004440 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004441
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004442 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004443 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004444 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004445 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4446 AttributeSet::ReturnIndex,
4447 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004448
Chris Lattnerac161bf2009-01-02 07:01:27 +00004449 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004450
Chris Lattnerac161bf2009-01-02 07:01:27 +00004451 // Loop through FunctionType's arguments and ensure they are specified
4452 // correctly. Also, gather any parameter attributes.
4453 FunctionType::param_iterator I = Ty->param_begin();
4454 FunctionType::param_iterator E = Ty->param_end();
4455 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004456 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004457 if (I != E) {
4458 ExpectedTy = *I++;
4459 } else if (!Ty->isVarArg()) {
4460 return Error(ArgList[i].Loc, "too many arguments specified");
4461 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004462
Chris Lattnerac161bf2009-01-02 07:01:27 +00004463 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4464 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004465 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004466 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004467 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4468 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004469 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4470 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004471 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004472
Chris Lattnerac161bf2009-01-02 07:01:27 +00004473 if (I != E)
4474 return Error(CallLoc, "not enough parameters specified for call");
4475
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004476 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004477 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4478 AttributeSet::FunctionIndex,
4479 FnAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004480
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004481 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004482 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004483
Jay Foad5bd375a2011-07-15 08:37:34 +00004484 CallInst *CI = CallInst::Create(Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00004485 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004486 CI->setCallingConv(CC);
4487 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004488 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004489 Inst = CI;
4490 return false;
4491}
4492
4493//===----------------------------------------------------------------------===//
4494// Memory Instructions.
4495//===----------------------------------------------------------------------===//
4496
4497/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00004498/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00004499int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004500 Value *Size = nullptr;
Chris Lattner200e0752009-07-02 23:08:13 +00004501 LocTy SizeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004502 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004503 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00004504
4505 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4506
Chris Lattner3822f632009-01-02 08:05:26 +00004507 if (ParseType(Ty)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004508
Chris Lattnerb2f39502009-12-30 05:44:30 +00004509 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004510 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00004511 if (Lex.getKind() == lltok::kw_align) {
4512 if (ParseOptionalAlignment(Alignment)) return true;
4513 } else if (Lex.getKind() == lltok::MetadataVar) {
4514 AteExtraComma = true;
4515 } else {
4516 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4517 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4518 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004519 }
4520 }
4521
Dan Gohman2140a742010-05-28 01:14:11 +00004522 if (Size && !Size->getType()->isIntegerTy())
4523 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004524
Reid Kleckner436c42e2014-01-17 23:58:17 +00004525 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4526 AI->setUsedWithInAlloca(IsInAlloca);
4527 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00004528 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004529}
4530
4531/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00004532/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004533/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00004534/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004535int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004536 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004537 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004538 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004539 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004540 AtomicOrdering Ordering = NotAtomic;
4541 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004542
4543 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004544 isAtomic = true;
4545 Lex.Lex();
4546 }
4547
Chris Lattnerbc639292011-11-27 06:56:53 +00004548 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004549 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004550 isVolatile = true;
4551 Lex.Lex();
4552 }
4553
Chris Lattnerb2f39502009-12-30 05:44:30 +00004554 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004555 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004556 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4557 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004558
Duncan Sands19d0b472010-02-16 11:11:14 +00004559 if (!Val->getType()->isPointerTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004560 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4561 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00004562 if (isAtomic && !Alignment)
4563 return Error(Loc, "atomic load must have explicit non-zero alignment");
4564 if (Ordering == Release || Ordering == AcquireRelease)
4565 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004566
Eli Friedman59b66882011-08-09 23:02:53 +00004567 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004568 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004569}
4570
4571/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00004572
4573/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4574/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00004575/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004576int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004577 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004578 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004579 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004580 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004581 AtomicOrdering Ordering = NotAtomic;
4582 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004583
4584 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004585 isAtomic = true;
4586 Lex.Lex();
4587 }
4588
Chris Lattnerbc639292011-11-27 06:56:53 +00004589 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004590 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004591 isVolatile = true;
4592 Lex.Lex();
4593 }
4594
Chris Lattnerac161bf2009-01-02 07:01:27 +00004595 if (ParseTypeAndValue(Val, Loc, PFS) ||
4596 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004597 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004598 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004599 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004600 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00004601
Duncan Sands19d0b472010-02-16 11:11:14 +00004602 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004603 return Error(PtrLoc, "store operand must be a pointer");
4604 if (!Val->getType()->isFirstClassType())
4605 return Error(Loc, "store operand must be a first class value");
4606 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4607 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00004608 if (isAtomic && !Alignment)
4609 return Error(Loc, "atomic store must have explicit non-zero alignment");
4610 if (Ordering == Acquire || Ordering == AcquireRelease)
4611 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004612
Eli Friedman59b66882011-08-09 23:02:53 +00004613 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004614 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004615}
4616
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004617/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00004618/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4619/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00004620int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004621 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4622 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00004623 AtomicOrdering SuccessOrdering = NotAtomic;
4624 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004625 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004626 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00004627 bool isWeak = false;
4628
4629 if (EatIfPresent(lltok::kw_weak))
4630 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00004631
4632 if (EatIfPresent(lltok::kw_volatile))
4633 isVolatile = true;
4634
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004635 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4636 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4637 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4638 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4639 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00004640 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4641 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004642 return true;
4643
Tim Northovere94a5182014-03-11 10:48:52 +00004644 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004645 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00004646 if (SuccessOrdering < FailureOrdering)
4647 return TokError("cmpxchg must be at least as ordered on success as failure");
4648 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4649 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004650 if (!Ptr->getType()->isPointerTy())
4651 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4652 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4653 return Error(CmpLoc, "compare value and pointer type do not match");
4654 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4655 return Error(NewLoc, "new value and pointer type do not match");
4656 if (!New->getType()->isIntegerTy())
4657 return Error(NewLoc, "cmpxchg operand must be an integer");
4658 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4659 if (Size < 8 || (Size & (Size - 1)))
4660 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4661 " integer");
4662
Tim Northover420a2162014-06-13 14:24:07 +00004663 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4664 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004665 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00004666 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004667 Inst = CXI;
4668 return AteExtraComma ? InstExtraComma : InstNormal;
4669}
4670
4671/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00004672/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4673/// 'singlethread'? AtomicOrdering
4674int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004675 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4676 bool AteExtraComma = false;
4677 AtomicOrdering Ordering = NotAtomic;
4678 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004679 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004680 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00004681
4682 if (EatIfPresent(lltok::kw_volatile))
4683 isVolatile = true;
4684
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004685 switch (Lex.getKind()) {
4686 default: return TokError("expected binary operation in atomicrmw");
4687 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4688 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4689 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4690 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4691 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4692 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4693 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4694 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4695 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4696 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4697 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4698 }
4699 Lex.Lex(); // Eat the operation.
4700
4701 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4702 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4703 ParseTypeAndValue(Val, ValLoc, PFS) ||
4704 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4705 return true;
4706
4707 if (Ordering == Unordered)
4708 return TokError("atomicrmw cannot be unordered");
4709 if (!Ptr->getType()->isPointerTy())
4710 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4711 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4712 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4713 if (!Val->getType()->isIntegerTy())
4714 return Error(ValLoc, "atomicrmw operand must be an integer");
4715 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4716 if (Size < 8 || (Size & (Size - 1)))
4717 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4718 " integer");
4719
4720 AtomicRMWInst *RMWI =
4721 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4722 RMWI->setVolatile(isVolatile);
4723 Inst = RMWI;
4724 return AteExtraComma ? InstExtraComma : InstNormal;
4725}
4726
Eli Friedmanfee02c62011-07-25 23:16:38 +00004727/// ParseFence
4728/// ::= 'fence' 'singlethread'? AtomicOrdering
4729int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4730 AtomicOrdering Ordering = NotAtomic;
4731 SynchronizationScope Scope = CrossThread;
4732 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4733 return true;
4734
4735 if (Ordering == Unordered)
4736 return TokError("fence cannot be unordered");
4737 if (Ordering == Monotonic)
4738 return TokError("fence cannot be monotonic");
4739
4740 Inst = new FenceInst(Context, Ordering, Scope);
4741 return InstNormal;
4742}
4743
Chris Lattnerac161bf2009-01-02 07:01:27 +00004744/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00004745/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004746int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004747 Value *Ptr = nullptr;
4748 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004749 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00004750
Dan Gohman16cbbe42009-07-29 15:58:36 +00004751 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00004752
Chris Lattner3822f632009-01-02 08:05:26 +00004753 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004754
Eli Benderskyd9806682013-04-22 17:03:42 +00004755 Type *BaseType = Ptr->getType();
4756 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4757 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004758 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004759
Chris Lattnerac161bf2009-01-02 07:01:27 +00004760 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004761 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004762 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00004763 if (Lex.getKind() == lltok::MetadataVar) {
4764 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00004765 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004766 }
Chris Lattner3822f632009-01-02 08:05:26 +00004767 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004768 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004769 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00004770 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4771 return Error(EltLoc, "getelementptr index type missmatch");
4772 if (Val->getType()->isVectorTy()) {
4773 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4774 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4775 if (ValNumEl != PtrNumEl)
4776 return Error(EltLoc,
4777 "getelementptr vector index has a wrong number of elements");
4778 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004779 Indices.push_back(Val);
4780 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004781
Eli Benderskyd9806682013-04-22 17:03:42 +00004782 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4783 return Error(Loc, "base element of getelementptr must be sized");
4784
4785 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004786 return Error(Loc, "invalid getelementptr indices");
Jay Foadd1b78492011-07-25 09:48:08 +00004787 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00004788 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004789 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004790 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004791}
4792
4793/// ParseExtractValue
4794/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004795int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004796 Value *Val; LocTy Loc;
4797 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004798 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004799 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004800 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004801 return true;
4802
Chris Lattner392be582010-02-12 20:49:41 +00004803 if (!Val->getType()->isAggregateType())
4804 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004805
Jay Foad57aa6362011-07-13 10:26:04 +00004806 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004807 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004808 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004809 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004810}
4811
4812/// ParseInsertValue
4813/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004814int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004815 Value *Val0, *Val1; LocTy Loc0, Loc1;
4816 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004817 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004818 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4819 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4820 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004821 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004822 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004823
Chris Lattner392be582010-02-12 20:49:41 +00004824 if (!Val0->getType()->isAggregateType())
4825 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004826
Jay Foad57aa6362011-07-13 10:26:04 +00004827 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004828 return Error(Loc0, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004829 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004830 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004831}
Nick Lewycky49f89192009-04-04 07:22:01 +00004832
4833//===----------------------------------------------------------------------===//
4834// Embedded metadata.
4835//===----------------------------------------------------------------------===//
4836
4837/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004838/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004839/// Element
4840/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004841bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00004842 if (ParseToken(lltok::lbrace, "expected '{' here"))
4843 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004844
Dan Gohman1e0213a2010-07-13 19:33:27 +00004845 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004846 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00004847 return false;
4848
Nick Lewycky49f89192009-04-04 07:22:01 +00004849 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004850 // Null is a special case since it is typeless.
4851 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004852 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004853 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004854 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004855
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004856 Metadata *MD;
4857 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004858 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004859 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00004860 } while (EatIfPresent(lltok::comma));
4861
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004862 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00004863}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004864
4865//===----------------------------------------------------------------------===//
4866// Use-list order directives.
4867//===----------------------------------------------------------------------===//
4868bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
4869 SMLoc Loc) {
4870 if (V->use_empty())
4871 return Error(Loc, "value has no uses");
4872
4873 unsigned NumUses = 0;
4874 SmallDenseMap<const Use *, unsigned, 16> Order;
4875 for (const Use &U : V->uses()) {
4876 if (++NumUses > Indexes.size())
4877 break;
4878 Order[&U] = Indexes[NumUses - 1];
4879 }
4880 if (NumUses < 2)
4881 return Error(Loc, "value only has one use");
4882 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
4883 return Error(Loc, "wrong number of indexes, expected " +
4884 Twine(std::distance(V->use_begin(), V->use_end())));
4885
4886 V->sortUseList([&](const Use &L, const Use &R) {
4887 return Order.lookup(&L) < Order.lookup(&R);
4888 });
4889 return false;
4890}
4891
4892/// ParseUseListOrderIndexes
4893/// ::= '{' uint32 (',' uint32)+ '}'
4894bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
4895 SMLoc Loc = Lex.getLoc();
4896 if (ParseToken(lltok::lbrace, "expected '{' here"))
4897 return true;
4898 if (Lex.getKind() == lltok::rbrace)
4899 return Lex.Error("expected non-empty list of uselistorder indexes");
4900
4901 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
4902 // indexes should be distinct numbers in the range [0, size-1], and should
4903 // not be in order.
4904 unsigned Offset = 0;
4905 unsigned Max = 0;
4906 bool IsOrdered = true;
4907 assert(Indexes.empty() && "Expected empty order vector");
4908 do {
4909 unsigned Index;
4910 if (ParseUInt32(Index))
4911 return true;
4912
4913 // Update consistency checks.
4914 Offset += Index - Indexes.size();
4915 Max = std::max(Max, Index);
4916 IsOrdered &= Index == Indexes.size();
4917
4918 Indexes.push_back(Index);
4919 } while (EatIfPresent(lltok::comma));
4920
4921 if (ParseToken(lltok::rbrace, "expected '}' here"))
4922 return true;
4923
4924 if (Indexes.size() < 2)
4925 return Error(Loc, "expected >= 2 uselistorder indexes");
4926 if (Offset != 0 || Max >= Indexes.size())
4927 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
4928 if (IsOrdered)
4929 return Error(Loc, "expected uselistorder indexes to change the order");
4930
4931 return false;
4932}
4933
4934/// ParseUseListOrder
4935/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
4936bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
4937 SMLoc Loc = Lex.getLoc();
4938 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
4939 return true;
4940
4941 Value *V;
4942 SmallVector<unsigned, 16> Indexes;
4943 if (ParseTypeAndValue(V, PFS) ||
4944 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
4945 ParseUseListOrderIndexes(Indexes))
4946 return true;
4947
4948 return sortUseListOrder(V, Indexes, Loc);
4949}
4950
4951/// ParseUseListOrderBB
4952/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
4953bool LLParser::ParseUseListOrderBB() {
4954 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
4955 SMLoc Loc = Lex.getLoc();
4956 Lex.Lex();
4957
4958 ValID Fn, Label;
4959 SmallVector<unsigned, 16> Indexes;
4960 if (ParseValID(Fn) ||
4961 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4962 ParseValID(Label) ||
4963 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4964 ParseUseListOrderIndexes(Indexes))
4965 return true;
4966
4967 // Check the function.
4968 GlobalValue *GV;
4969 if (Fn.Kind == ValID::t_GlobalName)
4970 GV = M->getNamedValue(Fn.StrVal);
4971 else if (Fn.Kind == ValID::t_GlobalID)
4972 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
4973 else
4974 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4975 if (!GV)
4976 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
4977 auto *F = dyn_cast<Function>(GV);
4978 if (!F)
4979 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4980 if (F->isDeclaration())
4981 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
4982
4983 // Check the basic block.
4984 if (Label.Kind == ValID::t_LocalID)
4985 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
4986 if (Label.Kind != ValID::t_LocalName)
4987 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
4988 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
4989 if (!V)
4990 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
4991 if (!isa<BasicBlock>(V))
4992 return Error(Label.Loc, "expected basic block in uselistorder_bb");
4993
4994 return sortUseListOrder(V, Indexes, Loc);
4995}