blob: 22e77b22892345ef918e6c1ff87c3af401053ad8 [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"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000016#include "llvm/AsmParser/SlotMapping.h"
Chandler Carruth91065212014-03-05 10:34:14 +000017#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/CallingConv.h"
19#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +000020#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000021#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DerivedTypes.h"
23#include "llvm/IR/InlineAsm.h"
24#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000025#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Module.h"
27#include "llvm/IR/Operator.h"
28#include "llvm/IR/ValueSymbolTable.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000029#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000031#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000032#include "llvm/Support/raw_ostream.h"
33using namespace llvm;
34
Chris Lattner229907c2011-07-18 04:54:35 +000035static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000036 std::string Result;
37 raw_string_ostream Tmp(Result);
38 Tmp << *T;
39 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000040}
41
Chris Lattner3822f632009-01-02 08:05:26 +000042/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000043bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000044 // Prime the lexer.
45 Lex.Lex();
46
Chris Lattnerad6f3352009-01-04 20:44:11 +000047 return ParseTopLevelEntities() ||
48 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000049}
50
Alex Lorenzd2255952015-07-17 22:07:03 +000051bool LLParser::parseStandaloneConstantValue(Constant *&C) {
52 Lex.Lex();
53
54 Type *Ty = nullptr;
55 if (ParseType(Ty) || parseConstantValue(Ty, C))
56 return true;
57 if (Lex.getKind() != lltok::Eof)
58 return Error(Lex.getLoc(), "expected end of string");
59 return false;
60}
61
Chris Lattnerac161bf2009-01-02 07:01:27 +000062/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
63/// module.
64bool LLParser::ValidateEndOfModule() {
Manman Ren209b17c2013-09-28 00:22:27 +000065 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
66 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
67
Bill Wendlingb32b0412013-02-08 06:32:06 +000068 // Handle any function attribute group forward references.
69 for (std::map<Value*, std::vector<unsigned> >::iterator
70 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
71 I != E; ++I) {
72 Value *V = I->first;
73 std::vector<unsigned> &Vec = I->second;
74 AttrBuilder B;
75
76 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
77 VI != VE; ++VI)
78 B.merge(NumberedAttrBuilders[*VI]);
79
80 if (Function *Fn = dyn_cast<Function>(V)) {
81 AttributeSet AS = Fn->getAttributes();
82 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
83 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
84 AS.getFnAttributes());
85
86 FnAttrs.merge(B);
87
88 // If the alignment was parsed as an attribute, move to the alignment
89 // field.
90 if (FnAttrs.hasAlignmentAttr()) {
91 Fn->setAlignment(FnAttrs.getAlignment());
92 FnAttrs.removeAttribute(Attribute::Alignment);
93 }
94
95 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
96 AttributeSet::get(Context,
97 AttributeSet::FunctionIndex,
98 FnAttrs));
99 Fn->setAttributes(AS);
100 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
101 AttributeSet AS = CI->getAttributes();
102 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
103 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
104 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000105 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000106 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
107 AttributeSet::get(Context,
108 AttributeSet::FunctionIndex,
109 FnAttrs));
110 CI->setAttributes(AS);
111 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
112 AttributeSet AS = II->getAttributes();
113 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
114 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
115 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000116 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000117 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
118 AttributeSet::get(Context,
119 AttributeSet::FunctionIndex,
120 FnAttrs));
121 II->setAttributes(AS);
122 } else {
123 llvm_unreachable("invalid object with forward attribute group reference");
124 }
125 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000126
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000127 // If there are entries in ForwardRefBlockAddresses at this point, the
128 // function was never defined.
129 if (!ForwardRefBlockAddresses.empty())
130 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
131 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000132
David Majnemer19b51052015-02-11 07:43:56 +0000133 for (const auto &NT : NumberedTypes)
134 if (NT.second.second.isValid())
135 return Error(NT.second.second,
136 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000137
138 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
139 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
140 if (I->second.second.isValid())
141 return Error(I->second.second,
142 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000143
David Majnemerdad0a642014-06-27 18:19:56 +0000144 if (!ForwardRefComdats.empty())
145 return Error(ForwardRefComdats.begin()->second,
146 "use of undefined comdat '$" +
147 ForwardRefComdats.begin()->first + "'");
148
Chris Lattnerac161bf2009-01-02 07:01:27 +0000149 if (!ForwardRefVals.empty())
150 return Error(ForwardRefVals.begin()->second.second,
151 "use of undefined value '@" + ForwardRefVals.begin()->first +
152 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000153
Chris Lattnerac161bf2009-01-02 07:01:27 +0000154 if (!ForwardRefValIDs.empty())
155 return Error(ForwardRefValIDs.begin()->second.second,
156 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000157 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000158
Devang Pateld2541152009-07-08 19:23:54 +0000159 if (!ForwardRefMDNodes.empty())
160 return Error(ForwardRefMDNodes.begin()->second.second,
161 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000162 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000163
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000164 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000165 for (auto &N : NumberedMetadata) {
166 if (N.second && !N.second->isResolved())
167 N.second->resolveCycles();
168 }
Devang Pateld2541152009-07-08 19:23:54 +0000169
Chris Lattnerac161bf2009-01-02 07:01:27 +0000170 // Look for intrinsic functions and CallInst that need to be upgraded
171 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
172 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000173
Manman Ren8b4306c2013-12-02 21:29:56 +0000174 UpgradeDebugInfo(*M);
175
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000176 if (!Slots)
177 return false;
178 // Initialize the slot mapping.
179 // Because by this point we've parsed and validated everything, we can "steal"
180 // the mapping from LLParser as it doesn't need it anymore.
181 Slots->GlobalValues = std::move(NumberedVals);
182 Slots->MetadataNodes = std::move(NumberedMetadata);
183
Chris Lattnerac161bf2009-01-02 07:01:27 +0000184 return false;
185}
186
187//===----------------------------------------------------------------------===//
188// Top-Level Entities
189//===----------------------------------------------------------------------===//
190
191bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000192 while (1) {
193 switch (Lex.getKind()) {
194 default: return TokError("expected top-level entity");
195 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000196 case lltok::kw_declare: if (ParseDeclare()) return true; break;
197 case lltok::kw_define: if (ParseDefine()) return true; break;
198 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
199 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000200 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000201 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000202 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000203 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000204 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000205 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000206 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000207 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000208
209 // The Global variable production with no name can have many different
210 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000211 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000212 // OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000213 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000214 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000215 case lltok::kw_internal: // OptionalLinkage
216 case lltok::kw_weak: // OptionalLinkage
217 case lltok::kw_weak_odr: // OptionalLinkage
218 case lltok::kw_linkonce: // OptionalLinkage
219 case lltok::kw_linkonce_odr: // OptionalLinkage
220 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000221 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000222 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000223 case lltok::kw_external: // OptionalLinkage
224 case lltok::kw_default: // OptionalVisibility
225 case lltok::kw_hidden: // OptionalVisibility
226 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000227 case lltok::kw_dllimport: // OptionalDLLStorageClass
228 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000229 case lltok::kw_thread_local: // OptionalThreadLocal
230 case lltok::kw_addrspace: // OptionalAddrSpace
231 case lltok::kw_constant: // GlobalType
232 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000233 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000234 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000235 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000236 bool HasLinkage;
237 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000238 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000239 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000240 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000241 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000242 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000243 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000244 return true;
245 break;
246 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000247
248 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000249 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
250 case lltok::kw_uselistorder_bb:
251 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000252 }
253 }
254}
255
256
257/// toplevelentity
258/// ::= 'module' 'asm' STRINGCONSTANT
259bool LLParser::ParseModuleAsm() {
260 assert(Lex.getKind() == lltok::kw_module);
261 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000262
263 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000264 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
265 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000266
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000267 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000268 return false;
269}
270
271/// toplevelentity
272/// ::= 'target' 'triple' '=' STRINGCONSTANT
273/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
274bool LLParser::ParseTargetDefinition() {
275 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000276 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000277 switch (Lex.Lex()) {
278 default: return TokError("unknown target property");
279 case lltok::kw_triple:
280 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000281 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
282 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000283 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000284 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000285 return false;
286 case lltok::kw_datalayout:
287 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000288 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
289 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000290 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000291 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000292 return false;
293 }
294}
295
Bill Wendling706d3d62012-11-28 08:41:48 +0000296/// toplevelentity
297/// ::= 'deplibs' '=' '[' ']'
298/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
299/// FIXME: Remove in 4.0. Currently parse, but ignore.
300bool LLParser::ParseDepLibs() {
301 assert(Lex.getKind() == lltok::kw_deplibs);
302 Lex.Lex();
303 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
304 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
305 return true;
306
307 if (EatIfPresent(lltok::rsquare))
308 return false;
309
310 do {
311 std::string Str;
312 if (ParseStringConstant(Str)) return true;
313 } while (EatIfPresent(lltok::comma));
314
315 return ParseToken(lltok::rsquare, "expected ']' at end of list");
316}
317
Dan Gohman466876b2009-08-12 23:32:33 +0000318/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000319/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000320bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000321 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000322 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000323 Lex.Lex(); // eat LocalVarID;
324
325 if (ParseToken(lltok::equal, "expected '=' after name") ||
326 ParseToken(lltok::kw_type, "expected 'type' after '='"))
327 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000328
Craig Topper2617dcc2014-04-15 06:32:26 +0000329 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000330 if (ParseStructDefinition(TypeLoc, "",
331 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000332
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000333 if (!isa<StructType>(Result)) {
334 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
335 if (Entry.first)
336 return Error(TypeLoc, "non-struct types may not be recursive");
337 Entry.first = Result;
338 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000339 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000340
Chris Lattnerac161bf2009-01-02 07:01:27 +0000341 return false;
342}
343
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000344
Chris Lattnerac161bf2009-01-02 07:01:27 +0000345/// toplevelentity
346/// ::= LocalVar '=' 'type' type
347bool LLParser::ParseNamedType() {
348 std::string Name = Lex.getStrVal();
349 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000350 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000351
Chris Lattner3822f632009-01-02 08:05:26 +0000352 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000353 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000354 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000355
Craig Topper2617dcc2014-04-15 06:32:26 +0000356 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000357 if (ParseStructDefinition(NameLoc, Name,
358 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000359
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000360 if (!isa<StructType>(Result)) {
361 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
362 if (Entry.first)
363 return Error(NameLoc, "non-struct types may not be recursive");
364 Entry.first = Result;
365 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000366 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000367
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000368 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000369}
370
371
372/// toplevelentity
373/// ::= 'declare' FunctionHeader
374bool LLParser::ParseDeclare() {
375 assert(Lex.getKind() == lltok::kw_declare);
376 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000377
Chris Lattnerac161bf2009-01-02 07:01:27 +0000378 Function *F;
379 return ParseFunctionHeader(F, false);
380}
381
382/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000383/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000384bool LLParser::ParseDefine() {
385 assert(Lex.getKind() == lltok::kw_define);
386 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000387
Chris Lattnerac161bf2009-01-02 07:01:27 +0000388 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000389 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000390 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000391 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000392}
393
Chris Lattner3822f632009-01-02 08:05:26 +0000394/// ParseGlobalType
395/// ::= 'constant'
396/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000397bool LLParser::ParseGlobalType(bool &IsConstant) {
398 if (Lex.getKind() == lltok::kw_constant)
399 IsConstant = true;
400 else if (Lex.getKind() == lltok::kw_global)
401 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000402 else {
403 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000404 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000405 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000406 Lex.Lex();
407 return false;
408}
409
Dan Gohman466876b2009-08-12 23:32:33 +0000410/// ParseUnnamedGlobal:
411/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000412/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
413/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000414/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000415/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
416/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000417bool LLParser::ParseUnnamedGlobal() {
418 unsigned VarID = NumberedVals.size();
419 std::string Name;
420 LocTy NameLoc = Lex.getLoc();
421
422 // Handle the GlobalID form.
423 if (Lex.getKind() == lltok::GlobalID) {
424 if (Lex.getUIntVal() != VarID)
425 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000426 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000427 Lex.Lex(); // eat GlobalID;
428
429 if (ParseToken(lltok::equal, "expected '=' after name"))
430 return true;
431 }
432
433 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000434 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000435 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000436 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000437 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000438 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000439 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000440 ParseOptionalThreadLocal(TLM) ||
441 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000442 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000443
Rafael Espindola464fe022014-07-30 22:51:54 +0000444 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000445 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000446 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000447 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000448 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000449}
450
Chris Lattnerac161bf2009-01-02 07:01:27 +0000451/// ParseNamedGlobal:
452/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000453/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
454/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000455bool LLParser::ParseNamedGlobal() {
456 assert(Lex.getKind() == lltok::GlobalVar);
457 LocTy NameLoc = Lex.getLoc();
458 std::string Name = Lex.getStrVal();
459 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000460
Chris Lattnerac161bf2009-01-02 07:01:27 +0000461 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000462 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000463 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000464 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000465 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
466 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000467 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000468 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000469 ParseOptionalThreadLocal(TLM) ||
470 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000471 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000472
Rafael Espindola464fe022014-07-30 22:51:54 +0000473 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000474 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000475 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000476
477 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000478 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000479}
480
David Majnemerdad0a642014-06-27 18:19:56 +0000481bool LLParser::parseComdat() {
482 assert(Lex.getKind() == lltok::ComdatVar);
483 std::string Name = Lex.getStrVal();
484 LocTy NameLoc = Lex.getLoc();
485 Lex.Lex();
486
487 if (ParseToken(lltok::equal, "expected '=' here"))
488 return true;
489
490 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
491 return TokError("expected comdat type");
492
493 Comdat::SelectionKind SK;
494 switch (Lex.getKind()) {
495 default:
496 return TokError("unknown selection kind");
497 case lltok::kw_any:
498 SK = Comdat::Any;
499 break;
500 case lltok::kw_exactmatch:
501 SK = Comdat::ExactMatch;
502 break;
503 case lltok::kw_largest:
504 SK = Comdat::Largest;
505 break;
506 case lltok::kw_noduplicates:
507 SK = Comdat::NoDuplicates;
508 break;
509 case lltok::kw_samesize:
510 SK = Comdat::SameSize;
511 break;
512 }
513 Lex.Lex();
514
515 // See if the comdat was forward referenced, if so, use the comdat.
516 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
517 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
518 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
519 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
520
521 Comdat *C;
522 if (I != ComdatSymTab.end())
523 C = &I->second;
524 else
525 C = M->getOrInsertComdat(Name);
526 C->setSelectionKind(SK);
527
528 return false;
529}
530
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000531// MDString:
532// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000533bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000534 std::string Str;
535 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000536 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000537 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000538 return false;
539}
540
541// MDNode:
542// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000543bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000544 // !{ ..., !42, ... }
545 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000546 if (ParseUInt32(MID))
547 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000548
Chris Lattner8eff0152010-04-01 05:14:45 +0000549 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000550 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000551 Result = NumberedMetadata[MID];
552 return false;
553 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000554
Chris Lattner8eff0152010-04-01 05:14:45 +0000555 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000556 auto &FwdRef = ForwardRefMDNodes[MID];
557 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000558
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000559 Result = FwdRef.first.get();
560 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000561 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000562}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000563
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000564/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000565/// !foo = !{ !1, !2 }
566bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000567 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000568 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000569 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000570
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000571 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000572 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000573 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000574 return true;
575
Dan Gohman2637cc12010-07-21 23:38:33 +0000576 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000577 if (Lex.getKind() != lltok::rbrace)
578 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000579 if (ParseToken(lltok::exclaim, "Expected '!' here"))
580 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000581
Craig Topper2617dcc2014-04-15 06:32:26 +0000582 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000583 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000584 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000585 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000586
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000587 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000588}
589
Devang Patel39e64d42009-07-01 19:21:12 +0000590/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000591/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000592bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000593 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000594 Lex.Lex();
595 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000596
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000597 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000598 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000599 ParseToken(lltok::equal, "expected '=' here"))
600 return true;
601
602 // Detect common error, from old metadata syntax.
603 if (Lex.getKind() == lltok::Type)
604 return TokError("unexpected type in metadata definition");
605
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000606 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000607 if (Lex.getKind() == lltok::MetadataVar) {
608 if (ParseSpecializedMDNode(Init, IsDistinct))
609 return true;
610 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
611 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000612 return true;
613
Chris Lattnerfc58af22009-12-30 04:51:58 +0000614 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000615 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000616 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000617 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000618 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000619
Chris Lattnerfc58af22009-12-30 04:51:58 +0000620 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
621 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000622 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000623 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000624 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000625 }
626
Devang Patel39e64d42009-07-01 19:21:12 +0000627 return false;
628}
629
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000630static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
631 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
632 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
633}
634
Chris Lattnerac161bf2009-01-02 07:01:27 +0000635/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000636/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
637/// OptionalDLLStorageClass OptionalThreadLocal
Eric Christopher536f0a92015-05-28 23:07:39 +0000638/// OptionalUnnamedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000639///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000640/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000641/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000642///
Eric Christopher536f0a92015-05-28 23:07:39 +0000643/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000644///
Rafael Espindola464fe022014-07-30 22:51:54 +0000645bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000646 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000647 GlobalVariable::ThreadLocalMode TLM,
648 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000649 assert(Lex.getKind() == lltok::kw_alias);
650 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000651
Rafael Espindola78527052013-10-06 15:10:43 +0000652 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
653
Rafael Espindolacaa43562013-10-09 16:07:32 +0000654 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000655 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000656
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000657 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000658 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000659 "symbol with local linkage must have default visibility");
660
Rafael Espindola64c1e182014-06-03 02:41:57 +0000661 Constant *Aliasee;
662 LocTy AliaseeLoc = Lex.getLoc();
663 if (Lex.getKind() != lltok::kw_bitcast &&
664 Lex.getKind() != lltok::kw_getelementptr &&
665 Lex.getKind() != lltok::kw_addrspacecast &&
666 Lex.getKind() != lltok::kw_inttoptr) {
667 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000668 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000669 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000670 // The bitcast dest type is not present, it is implied by the dest type.
671 ValID ID;
672 if (ParseValID(ID))
673 return true;
674 if (ID.Kind != ValID::t_Constant)
675 return Error(AliaseeLoc, "invalid aliasee");
676 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000677 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000678
Rafael Espindola64c1e182014-06-03 02:41:57 +0000679 Type *AliaseeType = Aliasee->getType();
680 auto *PTy = dyn_cast<PointerType>(AliaseeType);
681 if (!PTy)
682 return Error(AliaseeLoc, "An alias must have pointer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000683
684 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000685 std::unique_ptr<GlobalAlias> GA(
David Blaikief64246b2015-04-29 21:22:39 +0000686 GlobalAlias::create(PTy, (GlobalValue::LinkageTypes)Linkage, Name,
687 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000688 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000689 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000690 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000691 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000692
Rafael Espindola54fc2982015-06-17 17:53:31 +0000693 if (Name.empty())
694 NumberedVals.push_back(GA.get());
695
Chris Lattnerac161bf2009-01-02 07:01:27 +0000696 // See if this value already exists in the symbol table. If so, it is either
697 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000698 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000699 // See if this was a redefinition. If so, there is no entry in
700 // ForwardRefVals.
701 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
702 I = ForwardRefVals.find(Name);
703 if (I == ForwardRefVals.end())
704 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
705
706 // Otherwise, this was a definition of forward ref. Verify that types
707 // agree.
708 if (Val->getType() != GA->getType())
709 return Error(NameLoc,
710 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000711
Chris Lattnerac161bf2009-01-02 07:01:27 +0000712 // If they agree, just RAUW the old value with the alias and remove the
713 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000714 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000715 Val->eraseFromParent();
716 ForwardRefVals.erase(I);
717 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000718
Chris Lattnerac161bf2009-01-02 07:01:27 +0000719 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000720 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000721 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000722
Rafael Espindolaaa273822014-05-09 21:49:17 +0000723 // The module owns this now
724 GA.release();
725
Chris Lattnerac161bf2009-01-02 07:01:27 +0000726 return false;
727}
728
729/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000730/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000731/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000732/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000733/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000734/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000735/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000736///
Eric Christopher536f0a92015-05-28 23:07:39 +0000737/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000738/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000739///
740bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
741 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000742 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000743 GlobalVariable::ThreadLocalMode TLM,
744 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000745 if (!isValidVisibilityForLinkage(Visibility, Linkage))
746 return Error(NameLoc,
747 "symbol with local linkage must have default visibility");
748
Chris Lattnerac161bf2009-01-02 07:01:27 +0000749 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000750 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000751 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000752 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000753
Craig Topper2617dcc2014-04-15 06:32:26 +0000754 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000755 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000756 ParseOptionalToken(lltok::kw_externally_initialized,
757 IsExternallyInitialized,
758 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000759 ParseGlobalType(IsConstant) ||
760 ParseType(Ty, TyLoc))
761 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000762
Chris Lattnerac161bf2009-01-02 07:01:27 +0000763 // If the linkage is specified and is external, then no initializer is
764 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000765 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000766 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000767 Linkage != GlobalValue::ExternalLinkage)) {
768 if (ParseGlobalValue(Ty, Init))
769 return true;
770 }
771
David Majnemer49b3d9b2015-02-16 08:41:08 +0000772 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000773 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000774
David Majnemer598bd052014-12-09 05:56:09 +0000775 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000776
777 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000778 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000779 GVal = M->getNamedValue(Name);
780 if (GVal) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000781 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
782 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000783 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000784 } else {
785 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
786 I = ForwardRefValIDs.find(NumberedVals.size());
787 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000788 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000789 ForwardRefValIDs.erase(I);
790 }
791 }
792
David Majnemer598bd052014-12-09 05:56:09 +0000793 GlobalVariable *GV;
794 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000795 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
796 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000797 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000798 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000799 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000800 return Error(TyLoc,
801 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000802
David Majnemer598bd052014-12-09 05:56:09 +0000803 GV = cast<GlobalVariable>(GVal);
804
Chris Lattnerac161bf2009-01-02 07:01:27 +0000805 // Move the forward-reference to the correct spot in the module.
806 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
807 }
808
809 if (Name.empty())
810 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000811
Chris Lattnerac161bf2009-01-02 07:01:27 +0000812 // Set the parsed properties on the global.
813 if (Init)
814 GV->setInitializer(Init);
815 GV->setConstant(IsConstant);
816 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
817 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000818 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000819 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000820 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000821 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000822
Chris Lattnerac161bf2009-01-02 07:01:27 +0000823 // Parse attributes on the global.
824 while (Lex.getKind() == lltok::comma) {
825 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000826
Chris Lattnerac161bf2009-01-02 07:01:27 +0000827 if (Lex.getKind() == lltok::kw_section) {
828 Lex.Lex();
829 GV->setSection(Lex.getStrVal());
830 if (ParseToken(lltok::StringConstant, "expected global section string"))
831 return true;
832 } else if (Lex.getKind() == lltok::kw_align) {
833 unsigned Alignment;
834 if (ParseOptionalAlignment(Alignment)) return true;
835 GV->setAlignment(Alignment);
836 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000837 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000838 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000839 return true;
840 if (C)
841 GV->setComdat(C);
842 else
843 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000844 }
845 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000846
Chris Lattnerac161bf2009-01-02 07:01:27 +0000847 return false;
848}
849
Bill Wendling63b88192013-02-06 06:52:58 +0000850/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000851/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000852bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000853 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000854 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000855 Lex.Lex();
856
David Majnemerb39e22b2014-12-09 18:33:57 +0000857 if (Lex.getKind() != lltok::AttrGrpID)
858 return TokError("expected attribute group id");
859
Bill Wendling63b88192013-02-06 06:52:58 +0000860 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000861 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000862 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000863 Lex.Lex();
864
865 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000866 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000867 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000868 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000869 ParseToken(lltok::rbrace, "expected end of attribute group"))
870 return true;
871
Bill Wendlingb32b0412013-02-08 06:32:06 +0000872 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000873 return Error(AttrGrpLoc, "attribute group has no attributes");
874
875 return false;
876}
877
Bill Wendling8b0321d2013-02-08 00:52:31 +0000878/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000879/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000880bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
881 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000882 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000883 bool HaveError = false;
884
885 B.clear();
886
Bill Wendling63b88192013-02-06 06:52:58 +0000887 while (true) {
888 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000889 if (Token == lltok::kw_builtin)
890 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000891 switch (Token) {
892 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000893 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000894 return Error(Lex.getLoc(), "unterminated attribute group");
895 case lltok::rbrace:
896 // Finished.
897 return false;
898
Bill Wendlingb32b0412013-02-08 06:32:06 +0000899 case lltok::AttrGrpID: {
900 // Allow a function to reference an attribute group:
901 //
902 // define void @foo() #1 { ... }
903 if (inAttrGrp)
904 HaveError |=
905 Error(Lex.getLoc(),
906 "cannot have an attribute group reference in an attribute group");
907
908 unsigned AttrGrpNum = Lex.getUIntVal();
909 if (inAttrGrp) break;
910
911 // Save the reference to the attribute group. We'll fill it in later.
912 FwdRefAttrGrps.push_back(AttrGrpNum);
913 break;
914 }
Bill Wendling63b88192013-02-06 06:52:58 +0000915 // Target-dependent attributes:
916 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +0000917 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +0000918 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000919 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000920 }
921
922 // Target-independent attributes:
923 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000924 // As a hack, we allow function alignment to be initially parsed as an
925 // attribute on a function declaration/definition or added to an attribute
926 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000927 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000928 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000929 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000930 if (ParseToken(lltok::equal, "expected '=' here") ||
931 ParseUInt32(Alignment))
932 return true;
933 } else {
934 if (ParseOptionalAlignment(Alignment))
935 return true;
936 }
Bill Wendling63b88192013-02-06 06:52:58 +0000937 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000938 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000939 }
940 case lltok::kw_alignstack: {
941 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000942 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000943 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000944 if (ParseToken(lltok::equal, "expected '=' here") ||
945 ParseUInt32(Alignment))
946 return true;
947 } else {
948 if (ParseOptionalStackAlignment(Alignment))
949 return true;
950 }
Bill Wendling63b88192013-02-06 06:52:58 +0000951 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000952 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000953 }
Igor Laevsky39d662f2015-07-11 10:30:36 +0000954 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
955 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
956 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
957 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
958 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
959 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
960 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
961 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
962 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
963 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
964 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
965 case lltok::kw_noimplicitfloat:
966 B.addAttribute(Attribute::NoImplicitFloat); break;
967 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
968 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
969 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
970 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
971 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
972 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
973 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
974 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
975 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
976 case lltok::kw_returns_twice:
977 B.addAttribute(Attribute::ReturnsTwice); break;
978 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
979 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
980 case lltok::kw_sspstrong:
981 B.addAttribute(Attribute::StackProtectStrong); break;
982 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
983 case lltok::kw_sanitize_address:
984 B.addAttribute(Attribute::SanitizeAddress); break;
985 case lltok::kw_sanitize_thread:
986 B.addAttribute(Attribute::SanitizeThread); break;
987 case lltok::kw_sanitize_memory:
988 B.addAttribute(Attribute::SanitizeMemory); break;
989 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000990
991 // Error handling.
992 case lltok::kw_inreg:
993 case lltok::kw_signext:
994 case lltok::kw_zeroext:
995 HaveError |=
996 Error(Lex.getLoc(),
997 "invalid use of attribute on a function");
998 break;
999 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001000 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001001 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001002 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001003 case lltok::kw_nest:
1004 case lltok::kw_noalias:
1005 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001006 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001007 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001008 case lltok::kw_sret:
1009 HaveError |=
1010 Error(Lex.getLoc(),
1011 "invalid use of parameter-only attribute on a function");
1012 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001013 }
1014
1015 Lex.Lex();
1016 }
1017}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001018
1019//===----------------------------------------------------------------------===//
1020// GlobalValue Reference/Resolution Routines.
1021//===----------------------------------------------------------------------===//
1022
1023/// GetGlobalVal - Get a value with the specified name or ID, creating a
1024/// forward reference record if needed. This can return null if the value
1025/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001026GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001027 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001028 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001029 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001030 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001031 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001032 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001033
Chris Lattnerac161bf2009-01-02 07:01:27 +00001034 // Look this name up in the normal function symbol table.
1035 GlobalValue *Val =
1036 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001037
Chris Lattnerac161bf2009-01-02 07:01:27 +00001038 // If this is a forward reference for the value, see if we already created a
1039 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001040 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001041 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1042 I = ForwardRefVals.find(Name);
1043 if (I != ForwardRefVals.end())
1044 Val = I->second.first;
1045 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001046
Chris Lattnerac161bf2009-01-02 07:01:27 +00001047 // If we have the value in the symbol table or fwd-ref table, return it.
1048 if (Val) {
1049 if (Val->getType() == Ty) return Val;
1050 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001051 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001052 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001053 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001054
Chris Lattnerac161bf2009-01-02 07:01:27 +00001055 // Otherwise, create a new forward reference for this value and remember it.
1056 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001057 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001058 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001059 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001060 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001061 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1062 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001063 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001064
Chris Lattnerac161bf2009-01-02 07:01:27 +00001065 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1066 return FwdVal;
1067}
1068
Chris Lattner229907c2011-07-18 04:54:35 +00001069GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1070 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001071 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001072 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001073 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001074 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001075
Craig Topper2617dcc2014-04-15 06:32:26 +00001076 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001077
Chris Lattnerac161bf2009-01-02 07:01:27 +00001078 // If this is a forward reference for the value, see if we already created a
1079 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001080 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001081 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1082 I = ForwardRefValIDs.find(ID);
1083 if (I != ForwardRefValIDs.end())
1084 Val = I->second.first;
1085 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001086
Chris Lattnerac161bf2009-01-02 07:01:27 +00001087 // If we have the value in the symbol table or fwd-ref table, return it.
1088 if (Val) {
1089 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001090 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001091 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001092 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001093 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001094
Chris Lattnerac161bf2009-01-02 07:01:27 +00001095 // Otherwise, create a new forward reference for this value and remember it.
1096 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001097 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001098 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001099 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001100 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001101 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001102
Chris Lattnerac161bf2009-01-02 07:01:27 +00001103 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1104 return FwdVal;
1105}
1106
1107
1108//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001109// Comdat Reference/Resolution Routines.
1110//===----------------------------------------------------------------------===//
1111
1112Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1113 // Look this name up in the comdat symbol table.
1114 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1115 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1116 if (I != ComdatSymTab.end())
1117 return &I->second;
1118
1119 // Otherwise, create a new forward reference for this value and remember it.
1120 Comdat *C = M->getOrInsertComdat(Name);
1121 ForwardRefComdats[Name] = Loc;
1122 return C;
1123}
1124
1125
1126//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001127// Helper Routines.
1128//===----------------------------------------------------------------------===//
1129
1130/// ParseToken - If the current token has the specified kind, eat it and return
1131/// success. Otherwise, emit the specified error and return failure.
1132bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1133 if (Lex.getKind() != T)
1134 return TokError(ErrMsg);
1135 Lex.Lex();
1136 return false;
1137}
1138
Chris Lattner3822f632009-01-02 08:05:26 +00001139/// ParseStringConstant
1140/// ::= StringConstant
1141bool LLParser::ParseStringConstant(std::string &Result) {
1142 if (Lex.getKind() != lltok::StringConstant)
1143 return TokError("expected string constant");
1144 Result = Lex.getStrVal();
1145 Lex.Lex();
1146 return false;
1147}
1148
1149/// ParseUInt32
1150/// ::= uint32
1151bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001152 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1153 return TokError("expected integer");
1154 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1155 if (Val64 != unsigned(Val64))
1156 return TokError("expected 32-bit integer (too large)");
1157 Val = Val64;
1158 Lex.Lex();
1159 return false;
1160}
1161
Hal Finkelb0407ba2014-07-18 15:51:28 +00001162/// ParseUInt64
1163/// ::= uint64
1164bool LLParser::ParseUInt64(uint64_t &Val) {
1165 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1166 return TokError("expected integer");
1167 Val = Lex.getAPSIntVal().getLimitedValue();
1168 Lex.Lex();
1169 return false;
1170}
1171
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001172/// ParseTLSModel
1173/// := 'localdynamic'
1174/// := 'initialexec'
1175/// := 'localexec'
1176bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1177 switch (Lex.getKind()) {
1178 default:
1179 return TokError("expected localdynamic, initialexec or localexec");
1180 case lltok::kw_localdynamic:
1181 TLM = GlobalVariable::LocalDynamicTLSModel;
1182 break;
1183 case lltok::kw_initialexec:
1184 TLM = GlobalVariable::InitialExecTLSModel;
1185 break;
1186 case lltok::kw_localexec:
1187 TLM = GlobalVariable::LocalExecTLSModel;
1188 break;
1189 }
1190
1191 Lex.Lex();
1192 return false;
1193}
1194
1195/// ParseOptionalThreadLocal
1196/// := /*empty*/
1197/// := 'thread_local'
1198/// := 'thread_local' '(' tlsmodel ')'
1199bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1200 TLM = GlobalVariable::NotThreadLocal;
1201 if (!EatIfPresent(lltok::kw_thread_local))
1202 return false;
1203
1204 TLM = GlobalVariable::GeneralDynamicTLSModel;
1205 if (Lex.getKind() == lltok::lparen) {
1206 Lex.Lex();
1207 return ParseTLSModel(TLM) ||
1208 ParseToken(lltok::rparen, "expected ')' after thread local model");
1209 }
1210 return false;
1211}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001212
1213/// ParseOptionalAddrSpace
1214/// := /*empty*/
1215/// := 'addrspace' '(' uint32 ')'
1216bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1217 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001218 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001219 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001220 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001221 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001222 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001223}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001224
Artur Pilipenko17376c42015-08-03 14:31:49 +00001225/// ParseStringAttribute
1226/// := StringConstant
1227/// := StringConstant '=' StringConstant
1228bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1229 std::string Attr = Lex.getStrVal();
1230 Lex.Lex();
1231 std::string Val;
1232 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1233 return true;
1234 B.addAttribute(Attr, Val);
1235 return false;
1236}
1237
Bill Wendling34c2eb22012-12-04 23:40:58 +00001238/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1239bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1240 bool HaveError = false;
1241
1242 B.clear();
1243
1244 while (1) {
1245 lltok::Kind Token = Lex.getKind();
1246 switch (Token) {
1247 default: // End of attributes.
1248 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001249 case lltok::StringConstant: {
1250 if (ParseStringAttribute(B))
1251 return true;
1252 continue;
1253 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001254 case lltok::kw_align: {
1255 unsigned Alignment;
1256 if (ParseOptionalAlignment(Alignment))
1257 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001258 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001259 continue;
1260 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001261 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001262 case lltok::kw_dereferenceable: {
1263 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001264 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001265 return true;
1266 B.addDereferenceableAttr(Bytes);
1267 continue;
1268 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001269 case lltok::kw_dereferenceable_or_null: {
1270 uint64_t Bytes;
1271 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1272 return true;
1273 B.addDereferenceableOrNullAttr(Bytes);
1274 continue;
1275 }
Reid Klecknera534a382013-12-19 02:14:12 +00001276 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001277 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1278 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1279 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1280 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001281 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001282 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1283 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001284 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001285 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1286 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1287 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001288
Stephen Lin7577ed52013-04-20 13:16:13 +00001289 case lltok::kw_alignstack:
1290 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001291 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001292 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001293 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001294 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001295 case lltok::kw_minsize:
1296 case lltok::kw_naked:
1297 case lltok::kw_nobuiltin:
1298 case lltok::kw_noduplicate:
1299 case lltok::kw_noimplicitfloat:
1300 case lltok::kw_noinline:
1301 case lltok::kw_nonlazybind:
1302 case lltok::kw_noredzone:
1303 case lltok::kw_noreturn:
1304 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001305 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001306 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001307 case lltok::kw_returns_twice:
1308 case lltok::kw_sanitize_address:
1309 case lltok::kw_sanitize_memory:
1310 case lltok::kw_sanitize_thread:
1311 case lltok::kw_ssp:
1312 case lltok::kw_sspreq:
1313 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001314 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001315 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001316 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1317 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001318 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001319
Bill Wendling34c2eb22012-12-04 23:40:58 +00001320 Lex.Lex();
1321 }
1322}
1323
1324/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1325bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1326 bool HaveError = false;
1327
1328 B.clear();
1329
1330 while (1) {
1331 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001332 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001333 default: // End of attributes.
1334 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001335 case lltok::StringConstant: {
1336 if (ParseStringAttribute(B))
1337 return true;
1338 continue;
1339 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001340 case lltok::kw_dereferenceable: {
1341 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001342 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001343 return true;
1344 B.addDereferenceableAttr(Bytes);
1345 continue;
1346 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001347 case lltok::kw_dereferenceable_or_null: {
1348 uint64_t Bytes;
1349 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1350 return true;
1351 B.addDereferenceableOrNullAttr(Bytes);
1352 continue;
1353 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001354 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1355 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001356 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001357 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1358 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001359
Bill Wendling34c2eb22012-12-04 23:40:58 +00001360 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001361 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001362 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001363 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001364 case lltok::kw_nest:
1365 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001366 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001367 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001368 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001369 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001370
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001371 case lltok::kw_alignstack:
1372 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001373 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001374 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001375 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001376 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001377 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001378 case lltok::kw_minsize:
1379 case lltok::kw_naked:
1380 case lltok::kw_nobuiltin:
1381 case lltok::kw_noduplicate:
1382 case lltok::kw_noimplicitfloat:
1383 case lltok::kw_noinline:
1384 case lltok::kw_nonlazybind:
1385 case lltok::kw_noredzone:
1386 case lltok::kw_noreturn:
1387 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001388 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001389 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001390 case lltok::kw_returns_twice:
1391 case lltok::kw_sanitize_address:
1392 case lltok::kw_sanitize_memory:
1393 case lltok::kw_sanitize_thread:
1394 case lltok::kw_ssp:
1395 case lltok::kw_sspreq:
1396 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001397 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001398 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001399 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001400 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001401
1402 case lltok::kw_readnone:
1403 case lltok::kw_readonly:
1404 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001405 }
1406
Chris Lattnerac161bf2009-01-02 07:01:27 +00001407 Lex.Lex();
1408 }
1409}
1410
1411/// ParseOptionalLinkage
1412/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001413/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001414/// ::= 'internal'
1415/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001416/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001417/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001418/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001419/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001420/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001421/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001422/// ::= 'extern_weak'
1423/// ::= 'external'
1424bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1425 HasLinkage = false;
1426 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001427 default: Res=GlobalValue::ExternalLinkage; return false;
1428 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001429 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1430 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1431 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1432 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1433 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001434 case lltok::kw_available_externally:
1435 Res = GlobalValue::AvailableExternallyLinkage;
1436 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001437 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001438 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001439 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1440 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001441 }
1442 Lex.Lex();
1443 HasLinkage = true;
1444 return false;
1445}
1446
1447/// ParseOptionalVisibility
1448/// ::= /*empty*/
1449/// ::= 'default'
1450/// ::= 'hidden'
1451/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001452///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001453bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1454 switch (Lex.getKind()) {
1455 default: Res = GlobalValue::DefaultVisibility; return false;
1456 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1457 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1458 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1459 }
1460 Lex.Lex();
1461 return false;
1462}
1463
Nico Rieck7157bb72014-01-14 15:22:47 +00001464/// ParseOptionalDLLStorageClass
1465/// ::= /*empty*/
1466/// ::= 'dllimport'
1467/// ::= 'dllexport'
1468///
1469bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1470 switch (Lex.getKind()) {
1471 default: Res = GlobalValue::DefaultStorageClass; return false;
1472 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1473 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1474 }
1475 Lex.Lex();
1476 return false;
1477}
1478
Chris Lattnerac161bf2009-01-02 07:01:27 +00001479/// ParseOptionalCallingConv
1480/// ::= /*empty*/
1481/// ::= 'ccc'
1482/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001483/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001484/// ::= 'coldcc'
1485/// ::= 'x86_stdcallcc'
1486/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001487/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001488/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001489/// ::= 'arm_apcscc'
1490/// ::= 'arm_aapcscc'
1491/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001492/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001493/// ::= 'ptx_kernel'
1494/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001495/// ::= 'spir_func'
1496/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001497/// ::= 'x86_64_sysvcc'
1498/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001499/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001500/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001501/// ::= 'preserve_mostcc'
1502/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001503/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001504/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001505///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001506bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001507 switch (Lex.getKind()) {
1508 default: CC = CallingConv::C; return false;
1509 case lltok::kw_ccc: CC = CallingConv::C; break;
1510 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1511 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1512 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1513 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001514 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001515 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001516 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1517 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1518 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001519 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001520 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1521 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001522 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1523 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001524 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001525 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1526 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001527 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001528 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001529 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1530 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001531 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001532 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001533 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001534 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001535 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001536 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001537
Chris Lattnerac161bf2009-01-02 07:01:27 +00001538 Lex.Lex();
1539 return false;
1540}
1541
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001542/// ParseMetadataAttachment
1543/// ::= !dbg !42
1544bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1545 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1546
1547 std::string Name = Lex.getStrVal();
1548 Kind = M->getMDKindID(Name);
1549 Lex.Lex();
1550
1551 return ParseMDNode(MD);
1552}
1553
Chris Lattner5c427632009-12-30 05:31:19 +00001554/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001555/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001556bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001557 do {
1558 if (Lex.getKind() != lltok::MetadataVar)
1559 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001560
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001561 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001562 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001563 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001564 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001565
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001566 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001567 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001568 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001569
Chris Lattner596760d2009-12-29 21:25:40 +00001570 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001571 } while (EatIfPresent(lltok::comma));
1572 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001573}
1574
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001575/// ParseOptionalFunctionMetadata
1576/// ::= (!dbg !57)*
1577bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1578 while (Lex.getKind() == lltok::MetadataVar) {
1579 unsigned MDK;
1580 MDNode *N;
1581 if (ParseMetadataAttachment(MDK, N))
1582 return true;
1583
1584 F.setMetadata(MDK, N);
1585 }
1586 return false;
1587}
1588
Chris Lattnerac161bf2009-01-02 07:01:27 +00001589/// ParseOptionalAlignment
1590/// ::= /* empty */
1591/// ::= 'align' 4
1592bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1593 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001594 if (!EatIfPresent(lltok::kw_align))
1595 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001596 LocTy AlignLoc = Lex.getLoc();
1597 if (ParseUInt32(Alignment)) return true;
1598 if (!isPowerOf2_32(Alignment))
1599 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001600 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001601 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001602 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001603}
1604
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001605/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001606/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001607/// ::= AttrKind '(' 4 ')'
1608///
1609/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1610bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1611 uint64_t &Bytes) {
1612 assert((AttrKind == lltok::kw_dereferenceable ||
1613 AttrKind == lltok::kw_dereferenceable_or_null) &&
1614 "contract!");
1615
Hal Finkelb0407ba2014-07-18 15:51:28 +00001616 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001617 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001618 return false;
1619 LocTy ParenLoc = Lex.getLoc();
1620 if (!EatIfPresent(lltok::lparen))
1621 return Error(ParenLoc, "expected '('");
1622 LocTy DerefLoc = Lex.getLoc();
1623 if (ParseUInt64(Bytes)) return true;
1624 ParenLoc = Lex.getLoc();
1625 if (!EatIfPresent(lltok::rparen))
1626 return Error(ParenLoc, "expected ')'");
1627 if (!Bytes)
1628 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1629 return false;
1630}
1631
Chris Lattnerb2f39502009-12-30 05:44:30 +00001632/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001633/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001634/// ::= ',' align 4
1635///
1636/// This returns with AteExtraComma set to true if it ate an excess comma at the
1637/// end.
1638bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1639 bool &AteExtraComma) {
1640 AteExtraComma = false;
1641 while (EatIfPresent(lltok::comma)) {
1642 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001643 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001644 AteExtraComma = true;
1645 return false;
1646 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001647
Chris Lattner95b0ff42010-04-23 00:50:50 +00001648 if (Lex.getKind() != lltok::kw_align)
1649 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001650
Chris Lattner95b0ff42010-04-23 00:50:50 +00001651 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001652 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001653
Devang Patelea8a4b92009-09-17 23:04:48 +00001654 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001655}
1656
Eli Friedmanfee02c62011-07-25 23:16:38 +00001657/// ParseScopeAndOrdering
1658/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1659/// else: ::=
1660///
1661/// This sets Scope and Ordering to the parsed values.
1662bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1663 AtomicOrdering &Ordering) {
1664 if (!isAtomic)
1665 return false;
1666
1667 Scope = CrossThread;
1668 if (EatIfPresent(lltok::kw_singlethread))
1669 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001670
1671 return ParseOrdering(Ordering);
1672}
1673
1674/// ParseOrdering
1675/// ::= AtomicOrdering
1676///
1677/// This sets Ordering to the parsed value.
1678bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001679 switch (Lex.getKind()) {
1680 default: return TokError("Expected ordering on atomic instruction");
1681 case lltok::kw_unordered: Ordering = Unordered; break;
1682 case lltok::kw_monotonic: Ordering = Monotonic; break;
1683 case lltok::kw_acquire: Ordering = Acquire; break;
1684 case lltok::kw_release: Ordering = Release; break;
1685 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1686 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1687 }
1688 Lex.Lex();
1689 return false;
1690}
1691
Charles Davisbe5557e2010-02-12 00:31:15 +00001692/// ParseOptionalStackAlignment
1693/// ::= /* empty */
1694/// ::= 'alignstack' '(' 4 ')'
1695bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1696 Alignment = 0;
1697 if (!EatIfPresent(lltok::kw_alignstack))
1698 return false;
1699 LocTy ParenLoc = Lex.getLoc();
1700 if (!EatIfPresent(lltok::lparen))
1701 return Error(ParenLoc, "expected '('");
1702 LocTy AlignLoc = Lex.getLoc();
1703 if (ParseUInt32(Alignment)) return true;
1704 ParenLoc = Lex.getLoc();
1705 if (!EatIfPresent(lltok::rparen))
1706 return Error(ParenLoc, "expected ')'");
1707 if (!isPowerOf2_32(Alignment))
1708 return Error(AlignLoc, "stack alignment is not a power of two");
1709 return false;
1710}
Devang Patelea8a4b92009-09-17 23:04:48 +00001711
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001712/// ParseIndexList - This parses the index list for an insert/extractvalue
1713/// instruction. This sets AteExtraComma in the case where we eat an extra
1714/// comma at the end of the line and find that it is followed by metadata.
1715/// Clients that don't allow metadata can call the version of this function that
1716/// only takes one argument.
1717///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001718/// ParseIndexList
1719/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001720///
1721bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1722 bool &AteExtraComma) {
1723 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001724
Chris Lattnerac161bf2009-01-02 07:01:27 +00001725 if (Lex.getKind() != lltok::comma)
1726 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001727
Chris Lattner3822f632009-01-02 08:05:26 +00001728 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001729 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001730 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001731 AteExtraComma = true;
1732 return false;
1733 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001734 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001735 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001736 Indices.push_back(Idx);
1737 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001738
Chris Lattnerac161bf2009-01-02 07:01:27 +00001739 return false;
1740}
1741
1742//===----------------------------------------------------------------------===//
1743// Type Parsing.
1744//===----------------------------------------------------------------------===//
1745
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001746/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001747bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001748 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001749 switch (Lex.getKind()) {
1750 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001751 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001752 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001753 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001754 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001755 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001756 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001757 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001758 // Type ::= StructType
1759 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001760 return true;
1761 break;
1762 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001763 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001764 Lex.Lex(); // eat the lsquare.
1765 if (ParseArrayVectorType(Result, false))
1766 return true;
1767 break;
1768 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001769 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001770 Lex.Lex();
1771 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001772 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001773 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001774 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001775 } else if (ParseArrayVectorType(Result, true))
1776 return true;
1777 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001778 case lltok::LocalVar: {
1779 // Type ::= %foo
1780 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001781
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001782 // If the type hasn't been defined yet, create a forward definition and
1783 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001784 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001785 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001786 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001787 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001788 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001789 Lex.Lex();
1790 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001791 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001792
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001793 case lltok::LocalVarID: {
1794 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001795 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001796
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001797 // If the type hasn't been defined yet, create a forward definition and
1798 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001799 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001800 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001801 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001802 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001803 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001804 Lex.Lex();
1805 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001806 }
1807 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001808
1809 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001810 while (1) {
1811 switch (Lex.getKind()) {
1812 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001813 default:
1814 if (!AllowVoid && Result->isVoidTy())
1815 return Error(TypeLoc, "void type only allowed for function results");
1816 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001817
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001818 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001819 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001820 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001821 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001822 if (Result->isVoidTy())
1823 return TokError("pointers to void are invalid - use i8* instead");
1824 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001825 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001826 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001827 Lex.Lex();
1828 break;
1829
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001830 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001831 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001832 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001833 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001834 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001835 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001836 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001837 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001838 unsigned AddrSpace;
1839 if (ParseOptionalAddrSpace(AddrSpace) ||
1840 ParseToken(lltok::star, "expected '*' in address space"))
1841 return true;
1842
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001843 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001844 break;
1845 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001846
Chris Lattnerac161bf2009-01-02 07:01:27 +00001847 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1848 case lltok::lparen:
1849 if (ParseFunctionType(Result))
1850 return true;
1851 break;
1852 }
1853 }
1854}
1855
1856/// ParseParameterList
1857/// ::= '(' ')'
1858/// ::= '(' Arg (',' Arg)* ')'
1859/// Arg
1860/// ::= Type OptionalAttributes Value OptionalAttributes
1861bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001862 PerFunctionState &PFS, bool IsMustTailCall,
1863 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001864 if (ParseToken(lltok::lparen, "expected '(' in call"))
1865 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001866
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001867 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001868 while (Lex.getKind() != lltok::rparen) {
1869 // If this isn't the first argument, we need a comma.
1870 if (!ArgList.empty() &&
1871 ParseToken(lltok::comma, "expected ',' in argument list"))
1872 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001873
Reid Kleckner83498642014-08-26 00:33:28 +00001874 // Parse an ellipsis if this is a musttail call in a variadic function.
1875 if (Lex.getKind() == lltok::dotdotdot) {
1876 const char *Msg = "unexpected ellipsis in argument list for ";
1877 if (!IsMustTailCall)
1878 return TokError(Twine(Msg) + "non-musttail call");
1879 if (!InVarArgsFunc)
1880 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1881 Lex.Lex(); // Lex the '...', it is purely for readability.
1882 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1883 }
1884
Chris Lattnerac161bf2009-01-02 07:01:27 +00001885 // Parse the argument.
1886 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001887 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001888 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001889 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001890 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001891 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001892
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001893 if (ArgTy->isMetadataTy()) {
1894 if (ParseMetadataAsValue(V, PFS))
1895 return true;
1896 } else {
1897 // Otherwise, handle normal operands.
1898 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1899 return true;
1900 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001901 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1902 AttrIndex++,
1903 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001904 }
1905
Reid Kleckner83498642014-08-26 00:33:28 +00001906 if (IsMustTailCall && InVarArgsFunc)
1907 return TokError("expected '...' at end of argument list for musttail call "
1908 "in varargs function");
1909
Chris Lattnerac161bf2009-01-02 07:01:27 +00001910 Lex.Lex(); // Lex the ')'.
1911 return false;
1912}
1913
1914
1915
Chris Lattner2ed06b42009-01-05 18:34:07 +00001916/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001917/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001918/// ::= '(' ArgTypeListI ')'
1919/// ArgTypeListI
1920/// ::= /*empty*/
1921/// ::= '...'
1922/// ::= ArgTypeList ',' '...'
1923/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001924///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001925bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1926 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001927 isVarArg = false;
1928 assert(Lex.getKind() == lltok::lparen);
1929 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001930
Chris Lattnerac161bf2009-01-02 07:01:27 +00001931 if (Lex.getKind() == lltok::rparen) {
1932 // empty
1933 } else if (Lex.getKind() == lltok::dotdotdot) {
1934 isVarArg = true;
1935 Lex.Lex();
1936 } else {
1937 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001938 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001939 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001940 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001941
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001942 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001943 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001944
Chris Lattnerfdd87902009-10-05 05:54:46 +00001945 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001946 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001947
Chris Lattnerdef19492011-06-17 06:36:20 +00001948 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001949 Name = Lex.getStrVal();
1950 Lex.Lex();
1951 }
Chris Lattner3822f632009-01-02 08:05:26 +00001952
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001953 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001954 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001955
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001956 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001957 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
1958 AttrIndex++, Attrs),
1959 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001960
Chris Lattner3822f632009-01-02 08:05:26 +00001961 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001962 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001963 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001964 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001965 break;
1966 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001967
Chris Lattnerac161bf2009-01-02 07:01:27 +00001968 // Otherwise must be an argument type.
1969 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001970 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001971
Chris Lattnerfdd87902009-10-05 05:54:46 +00001972 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001973 return Error(TypeLoc, "argument can not have void type");
1974
Chris Lattnerdef19492011-06-17 06:36:20 +00001975 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001976 Name = Lex.getStrVal();
1977 Lex.Lex();
1978 } else {
1979 Name = "";
1980 }
Chris Lattner3822f632009-01-02 08:05:26 +00001981
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001982 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001983 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001984
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001985 ArgList.emplace_back(
1986 TypeLoc, ArgTy,
1987 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
1988 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001989 }
1990 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001991
Chris Lattner3822f632009-01-02 08:05:26 +00001992 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001993}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001994
Chris Lattnerac161bf2009-01-02 07:01:27 +00001995/// ParseFunctionType
1996/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001997bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001998 assert(Lex.getKind() == lltok::lparen);
1999
Chris Lattnerce473c72009-01-05 08:04:33 +00002000 if (!FunctionType::isValidReturnType(Result))
2001 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002002
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002003 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002004 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002005 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002006 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002007
Chris Lattnerac161bf2009-01-02 07:01:27 +00002008 // Reject names on the arguments lists.
2009 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2010 if (!ArgList[i].Name.empty())
2011 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002012 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002013 return Error(ArgList[i].Loc,
2014 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002015 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002016
Jay Foadb804a2b2011-07-12 14:06:48 +00002017 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002018 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002019 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002020
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002021 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002022 return false;
2023}
2024
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002025/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2026/// other structs.
2027bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2028 SmallVector<Type*, 8> Elts;
2029 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002030
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002031 Result = StructType::get(Context, Elts, Packed);
2032 return false;
2033}
2034
2035/// ParseStructDefinition - Parse a struct in a 'type' definition.
2036bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2037 std::pair<Type*, LocTy> &Entry,
2038 Type *&ResultTy) {
2039 // If the type was already defined, diagnose the redefinition.
2040 if (Entry.first && !Entry.second.isValid())
2041 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002042
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002043 // If we have opaque, just return without filling in the definition for the
2044 // struct. This counts as a definition as far as the .ll file goes.
2045 if (EatIfPresent(lltok::kw_opaque)) {
2046 // This type is being defined, so clear the location to indicate this.
2047 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002048
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002049 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002050 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002051 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002052 ResultTy = Entry.first;
2053 return false;
2054 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002055
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002056 // If the type starts with '<', then it is either a packed struct or a vector.
2057 bool isPacked = EatIfPresent(lltok::less);
2058
2059 // If we don't have a struct, then we have a random type alias, which we
2060 // accept for compatibility with old files. These types are not allowed to be
2061 // forward referenced and not allowed to be recursive.
2062 if (Lex.getKind() != lltok::lbrace) {
2063 if (Entry.first)
2064 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002065
Craig Topper2617dcc2014-04-15 06:32:26 +00002066 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002067 if (isPacked)
2068 return ParseArrayVectorType(ResultTy, true);
2069 return ParseType(ResultTy);
2070 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002071
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002072 // This type is being defined, so clear the location to indicate this.
2073 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002074
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002075 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002076 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002077 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002078
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002079 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002080
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002081 SmallVector<Type*, 8> Body;
2082 if (ParseStructBody(Body) ||
2083 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2084 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002085
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002086 STy->setBody(Body, isPacked);
2087 ResultTy = STy;
2088 return false;
2089}
2090
2091
Chris Lattnerac161bf2009-01-02 07:01:27 +00002092/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002093/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002094/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002095/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002096/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002097/// ::= '<' '{' Type (',' Type)* '}' '>'
2098bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002099 assert(Lex.getKind() == lltok::lbrace);
2100 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002101
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002102 // Handle the empty struct.
2103 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002104 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002105
Chris Lattnerf880ca22009-03-09 04:49:14 +00002106 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002107 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002108 if (ParseType(Ty)) return true;
2109 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002110
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002111 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002112 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002113
Chris Lattner3822f632009-01-02 08:05:26 +00002114 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002115 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002116 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002117
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002118 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002119 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002120
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002121 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002122 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002123
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002124 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002125}
2126
2127/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2128/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002129/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002130/// ::= '[' APSINTVAL 'x' Types ']'
2131/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002132bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002133 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2134 Lex.getAPSIntVal().getBitWidth() > 64)
2135 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002136
Chris Lattnerac161bf2009-01-02 07:01:27 +00002137 LocTy SizeLoc = Lex.getLoc();
2138 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002139 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002140
Chris Lattner3822f632009-01-02 08:05:26 +00002141 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2142 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002143
2144 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002145 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002146 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002147
Chris Lattner3822f632009-01-02 08:05:26 +00002148 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2149 "expected end of sequential type"))
2150 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002151
Chris Lattnerac161bf2009-01-02 07:01:27 +00002152 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002153 if (Size == 0)
2154 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002155 if ((unsigned)Size != Size)
2156 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002157 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002158 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002159 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002160 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002161 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002162 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002163 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002164 }
2165 return false;
2166}
2167
2168//===----------------------------------------------------------------------===//
2169// Function Semantic Analysis.
2170//===----------------------------------------------------------------------===//
2171
Chris Lattner3432c622009-10-28 03:39:23 +00002172LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2173 int functionNumber)
2174 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002175
2176 // Insert unnamed arguments into the NumberedVals list.
2177 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2178 AI != E; ++AI)
2179 if (!AI->hasName())
2180 NumberedVals.push_back(AI);
2181}
2182
2183LLParser::PerFunctionState::~PerFunctionState() {
2184 // If there were any forward referenced non-basicblock values, delete them.
2185 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2186 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2187 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002188 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002189 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002190 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002191 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002192 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002193
Chris Lattnerac161bf2009-01-02 07:01:27 +00002194 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2195 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2196 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002197 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002198 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002199 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002200 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002201 }
2202}
2203
Chris Lattner3432c622009-10-28 03:39:23 +00002204bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002205 if (!ForwardRefVals.empty())
2206 return P.Error(ForwardRefVals.begin()->second.second,
2207 "use of undefined value '%" + ForwardRefVals.begin()->first +
2208 "'");
2209 if (!ForwardRefValIDs.empty())
2210 return P.Error(ForwardRefValIDs.begin()->second.second,
2211 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002212 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002213 return false;
2214}
2215
2216
2217/// GetVal - Get a value with the specified name or ID, creating a
2218/// forward reference record if needed. This can return null if the value
2219/// exists but does not have the right type.
2220Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002221 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002222 // Look this name up in the normal function symbol table.
2223 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002224
Chris Lattnerac161bf2009-01-02 07:01:27 +00002225 // If this is a forward reference for the value, see if we already created a
2226 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002227 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002228 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2229 I = ForwardRefVals.find(Name);
2230 if (I != ForwardRefVals.end())
2231 Val = I->second.first;
2232 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002233
Chris Lattnerac161bf2009-01-02 07:01:27 +00002234 // If we have the value in the symbol table or fwd-ref table, return it.
2235 if (Val) {
2236 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002237 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002238 P.Error(Loc, "'%" + Name + "' is not a basic block");
2239 else
2240 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002241 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002242 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002243 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002244
Chris Lattnerac161bf2009-01-02 07:01:27 +00002245 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002246 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002247 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002248 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002249 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002250
Chris Lattnerac161bf2009-01-02 07:01:27 +00002251 // Otherwise, create a new forward reference for this value and remember it.
2252 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002253 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002254 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002255 else
2256 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002257
Chris Lattnerac161bf2009-01-02 07:01:27 +00002258 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2259 return FwdVal;
2260}
2261
Chris Lattner229907c2011-07-18 04:54:35 +00002262Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002263 LocTy Loc) {
2264 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002265 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002266
Chris Lattnerac161bf2009-01-02 07:01:27 +00002267 // If this is a forward reference for the value, see if we already created a
2268 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002269 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002270 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2271 I = ForwardRefValIDs.find(ID);
2272 if (I != ForwardRefValIDs.end())
2273 Val = I->second.first;
2274 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002275
Chris Lattnerac161bf2009-01-02 07:01:27 +00002276 // If we have the value in the symbol table or fwd-ref table, return it.
2277 if (Val) {
2278 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002279 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002280 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002281 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002282 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002283 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002284 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002285 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002286
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002287 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002288 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002289 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002290 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002291
Chris Lattnerac161bf2009-01-02 07:01:27 +00002292 // Otherwise, create a new forward reference for this value and remember it.
2293 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002294 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002295 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002296 else
2297 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002298
Chris Lattnerac161bf2009-01-02 07:01:27 +00002299 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2300 return FwdVal;
2301}
2302
2303/// SetInstName - After an instruction is parsed and inserted into its
2304/// basic block, this installs its name.
2305bool LLParser::PerFunctionState::SetInstName(int NameID,
2306 const std::string &NameStr,
2307 LocTy NameLoc, Instruction *Inst) {
2308 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002309 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002310 if (NameID != -1 || !NameStr.empty())
2311 return P.Error(NameLoc, "instructions returning void cannot have a name");
2312 return false;
2313 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002314
Chris Lattnerac161bf2009-01-02 07:01:27 +00002315 // If this was a numbered instruction, verify that the instruction is the
2316 // expected value and resolve any forward references.
2317 if (NameStr.empty()) {
2318 // If neither a name nor an ID was specified, just use the next ID.
2319 if (NameID == -1)
2320 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002321
Chris Lattnerac161bf2009-01-02 07:01:27 +00002322 if (unsigned(NameID) != NumberedVals.size())
2323 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002324 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002325
Chris Lattnerac161bf2009-01-02 07:01:27 +00002326 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2327 ForwardRefValIDs.find(NameID);
2328 if (FI != ForwardRefValIDs.end()) {
2329 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002330 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002331 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002332 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002333 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002334 ForwardRefValIDs.erase(FI);
2335 }
2336
2337 NumberedVals.push_back(Inst);
2338 return false;
2339 }
2340
2341 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2342 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2343 FI = ForwardRefVals.find(NameStr);
2344 if (FI != ForwardRefVals.end()) {
2345 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002346 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002347 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002348 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002349 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002350 ForwardRefVals.erase(FI);
2351 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002352
Chris Lattnerac161bf2009-01-02 07:01:27 +00002353 // Set the name on the instruction.
2354 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002355
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002356 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002357 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002358 NameStr + "'");
2359 return false;
2360}
2361
2362/// GetBB - Get a basic block with the specified name or ID, creating a
2363/// forward reference record if needed.
2364BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2365 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002366 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2367 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002368}
2369
2370BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002371 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2372 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002373}
2374
2375/// DefineBB - Define the specified basic block, which is either named or
2376/// unnamed. If there is an error, this returns null otherwise it returns
2377/// the block being defined.
2378BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2379 LocTy Loc) {
2380 BasicBlock *BB;
2381 if (Name.empty())
2382 BB = GetBB(NumberedVals.size(), Loc);
2383 else
2384 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002385 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002386
Chris Lattnerac161bf2009-01-02 07:01:27 +00002387 // Move the block to the end of the function. Forward ref'd blocks are
2388 // inserted wherever they happen to be referenced.
2389 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002390
Chris Lattnerac161bf2009-01-02 07:01:27 +00002391 // Remove the block from forward ref sets.
2392 if (Name.empty()) {
2393 ForwardRefValIDs.erase(NumberedVals.size());
2394 NumberedVals.push_back(BB);
2395 } else {
2396 // BB forward references are already in the function symbol table.
2397 ForwardRefVals.erase(Name);
2398 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002399
Chris Lattnerac161bf2009-01-02 07:01:27 +00002400 return BB;
2401}
2402
2403//===----------------------------------------------------------------------===//
2404// Constants.
2405//===----------------------------------------------------------------------===//
2406
2407/// ParseValID - Parse an abstract value that doesn't necessarily have a
2408/// type implied. For example, if we parse "4" we don't know what integer type
2409/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002410/// sanity. PFS is used to convert function-local operands of metadata (since
2411/// metadata operands are not just parsed here but also converted to values).
2412/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002413bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002414 ID.Loc = Lex.getLoc();
2415 switch (Lex.getKind()) {
2416 default: return TokError("expected value token");
2417 case lltok::GlobalID: // @42
2418 ID.UIntVal = Lex.getUIntVal();
2419 ID.Kind = ValID::t_GlobalID;
2420 break;
2421 case lltok::GlobalVar: // @foo
2422 ID.StrVal = Lex.getStrVal();
2423 ID.Kind = ValID::t_GlobalName;
2424 break;
2425 case lltok::LocalVarID: // %42
2426 ID.UIntVal = Lex.getUIntVal();
2427 ID.Kind = ValID::t_LocalID;
2428 break;
2429 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002430 ID.StrVal = Lex.getStrVal();
2431 ID.Kind = ValID::t_LocalName;
2432 break;
2433 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002434 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002435 ID.Kind = ValID::t_APSInt;
2436 break;
2437 case lltok::APFloat:
2438 ID.APFloatVal = Lex.getAPFloatVal();
2439 ID.Kind = ValID::t_APFloat;
2440 break;
2441 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002442 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002443 ID.Kind = ValID::t_Constant;
2444 break;
2445 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002446 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002447 ID.Kind = ValID::t_Constant;
2448 break;
2449 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2450 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2451 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002452
Chris Lattnerac161bf2009-01-02 07:01:27 +00002453 case lltok::lbrace: {
2454 // ValID ::= '{' ConstVector '}'
2455 Lex.Lex();
2456 SmallVector<Constant*, 16> Elts;
2457 if (ParseGlobalValueVector(Elts) ||
2458 ParseToken(lltok::rbrace, "expected end of struct constant"))
2459 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002460
Reid Klecknere28b9cb2015-08-03 17:36:22 +00002461 ID.ConstantStructElts = new Constant*[Elts.size()];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002462 ID.UIntVal = Elts.size();
Reid Klecknere28b9cb2015-08-03 17:36:22 +00002463 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002464 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002465 return false;
2466 }
2467 case lltok::less: {
2468 // ValID ::= '<' ConstVector '>' --> Vector.
2469 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2470 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002471 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002472
Chris Lattnerac161bf2009-01-02 07:01:27 +00002473 SmallVector<Constant*, 16> Elts;
2474 LocTy FirstEltLoc = Lex.getLoc();
2475 if (ParseGlobalValueVector(Elts) ||
2476 (isPackedStruct &&
2477 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2478 ParseToken(lltok::greater, "expected end of constant"))
2479 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002480
Chris Lattnerac161bf2009-01-02 07:01:27 +00002481 if (isPackedStruct) {
Reid Klecknere28b9cb2015-08-03 17:36:22 +00002482 ID.ConstantStructElts = new Constant*[Elts.size()];
2483 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002484 ID.UIntVal = Elts.size();
2485 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002486 return false;
2487 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002488
Chris Lattnerac161bf2009-01-02 07:01:27 +00002489 if (Elts.empty())
2490 return Error(ID.Loc, "constant vector must not be empty");
2491
Duncan Sands9dff9be2010-02-15 16:12:20 +00002492 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002493 !Elts[0]->getType()->isFloatingPointTy() &&
2494 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002495 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002496 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002497
Chris Lattnerac161bf2009-01-02 07:01:27 +00002498 // Verify that all the vector elements have the same type.
2499 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2500 if (Elts[i]->getType() != Elts[0]->getType())
2501 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002502 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002503 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002504
Chris Lattner69229312011-02-15 00:14:00 +00002505 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002506 ID.Kind = ValID::t_Constant;
2507 return false;
2508 }
2509 case lltok::lsquare: { // Array Constant
2510 Lex.Lex();
2511 SmallVector<Constant*, 16> Elts;
2512 LocTy FirstEltLoc = Lex.getLoc();
2513 if (ParseGlobalValueVector(Elts) ||
2514 ParseToken(lltok::rsquare, "expected end of array constant"))
2515 return true;
2516
2517 // Handle empty element.
2518 if (Elts.empty()) {
2519 // Use undef instead of an array because it's inconvenient to determine
2520 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002521 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002522 return false;
2523 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002524
Chris Lattnerac161bf2009-01-02 07:01:27 +00002525 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002526 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002527 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002528
Owen Anderson4056ca92009-07-29 22:17:13 +00002529 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002530
Chris Lattnerac161bf2009-01-02 07:01:27 +00002531 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002532 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002533 if (Elts[i]->getType() != Elts[0]->getType())
2534 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002535 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002536 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002537 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002538
Jay Foad83be3612011-06-22 09:24:39 +00002539 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002540 ID.Kind = ValID::t_Constant;
2541 return false;
2542 }
2543 case lltok::kw_c: // c "foo"
2544 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002545 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2546 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002547 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2548 ID.Kind = ValID::t_Constant;
2549 return false;
2550
2551 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002552 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2553 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002554 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002555 Lex.Lex();
2556 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002557 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002558 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002559 ParseStringConstant(ID.StrVal) ||
2560 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002561 ParseToken(lltok::StringConstant, "expected constraint string"))
2562 return true;
2563 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002564 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002565 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002566 ID.Kind = ValID::t_InlineAsm;
2567 return false;
2568 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002569
Chris Lattner3432c622009-10-28 03:39:23 +00002570 case lltok::kw_blockaddress: {
2571 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2572 Lex.Lex();
2573
2574 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002575
Chris Lattner3432c622009-10-28 03:39:23 +00002576 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2577 ParseValID(Fn) ||
2578 ParseToken(lltok::comma, "expected comma in block address expression")||
2579 ParseValID(Label) ||
2580 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2581 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002582
Chris Lattner3432c622009-10-28 03:39:23 +00002583 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2584 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002585 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002586 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002587
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002588 // Try to find the function (but skip it if it's forward-referenced).
2589 GlobalValue *GV = nullptr;
2590 if (Fn.Kind == ValID::t_GlobalID) {
2591 if (Fn.UIntVal < NumberedVals.size())
2592 GV = NumberedVals[Fn.UIntVal];
2593 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2594 GV = M->getNamedValue(Fn.StrVal);
2595 }
2596 Function *F = nullptr;
2597 if (GV) {
2598 // Confirm that it's actually a function with a definition.
2599 if (!isa<Function>(GV))
2600 return Error(Fn.Loc, "expected function name in blockaddress");
2601 F = cast<Function>(GV);
2602 if (F->isDeclaration())
2603 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2604 }
2605
2606 if (!F) {
2607 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002608 GlobalValue *&FwdRef =
2609 ForwardRefBlockAddresses.insert(std::make_pair(
2610 std::move(Fn),
2611 std::map<ValID, GlobalValue *>()))
2612 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2613 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002614 if (!FwdRef)
2615 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2616 GlobalValue::InternalLinkage, nullptr, "");
2617 ID.ConstantVal = FwdRef;
2618 ID.Kind = ValID::t_Constant;
2619 return false;
2620 }
2621
2622 // We found the function; now find the basic block. Don't use PFS, since we
2623 // might be inside a constant expression.
2624 BasicBlock *BB;
2625 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2626 if (Label.Kind == ValID::t_LocalID)
2627 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2628 else
2629 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2630 if (!BB)
2631 return Error(Label.Loc, "referenced value is not a basic block");
2632 } else {
2633 if (Label.Kind == ValID::t_LocalID)
2634 return Error(Label.Loc, "cannot take address of numeric label after "
2635 "the function is defined");
2636 BB = dyn_cast_or_null<BasicBlock>(
2637 F->getValueSymbolTable().lookup(Label.StrVal));
2638 if (!BB)
2639 return Error(Label.Loc, "referenced value is not a basic block");
2640 }
2641
2642 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002643 ID.Kind = ValID::t_Constant;
2644 return false;
2645 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002646
Chris Lattnerac161bf2009-01-02 07:01:27 +00002647 case lltok::kw_trunc:
2648 case lltok::kw_zext:
2649 case lltok::kw_sext:
2650 case lltok::kw_fptrunc:
2651 case lltok::kw_fpext:
2652 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002653 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002654 case lltok::kw_uitofp:
2655 case lltok::kw_sitofp:
2656 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002657 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002658 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002659 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002660 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002661 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002662 Constant *SrcVal;
2663 Lex.Lex();
2664 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2665 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002666 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002667 ParseType(DestTy) ||
2668 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2669 return true;
2670 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2671 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002672 getTypeString(SrcVal->getType()) + "' to '" +
2673 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002674 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002675 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002676 ID.Kind = ValID::t_Constant;
2677 return false;
2678 }
2679 case lltok::kw_extractvalue: {
2680 Lex.Lex();
2681 Constant *Val;
2682 SmallVector<unsigned, 4> Indices;
2683 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2684 ParseGlobalTypeAndValue(Val) ||
2685 ParseIndexList(Indices) ||
2686 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2687 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002688
Chris Lattner392be582010-02-12 20:49:41 +00002689 if (!Val->getType()->isAggregateType())
2690 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002691 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002692 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002693 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002694 ID.Kind = ValID::t_Constant;
2695 return false;
2696 }
2697 case lltok::kw_insertvalue: {
2698 Lex.Lex();
2699 Constant *Val0, *Val1;
2700 SmallVector<unsigned, 4> Indices;
2701 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2702 ParseGlobalTypeAndValue(Val0) ||
2703 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2704 ParseGlobalTypeAndValue(Val1) ||
2705 ParseIndexList(Indices) ||
2706 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2707 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002708 if (!Val0->getType()->isAggregateType())
2709 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002710 Type *IndexedType =
2711 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2712 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002713 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002714 if (IndexedType != Val1->getType())
2715 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2716 getTypeString(Val1->getType()) +
2717 "' instead of '" + getTypeString(IndexedType) +
2718 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002719 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002720 ID.Kind = ValID::t_Constant;
2721 return false;
2722 }
2723 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002724 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002725 unsigned PredVal, Opc = Lex.getUIntVal();
2726 Constant *Val0, *Val1;
2727 Lex.Lex();
2728 if (ParseCmpPredicate(PredVal, Opc) ||
2729 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2730 ParseGlobalTypeAndValue(Val0) ||
2731 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2732 ParseGlobalTypeAndValue(Val1) ||
2733 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2734 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002735
Chris Lattnerac161bf2009-01-02 07:01:27 +00002736 if (Val0->getType() != Val1->getType())
2737 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002738
Chris Lattnerac161bf2009-01-02 07:01:27 +00002739 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002740
Chris Lattnerac161bf2009-01-02 07:01:27 +00002741 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002742 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002743 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002744 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002745 } else {
2746 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002747 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002748 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002749 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002750 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002751 }
2752 ID.Kind = ValID::t_Constant;
2753 return false;
2754 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002755
Chris Lattnerac161bf2009-01-02 07:01:27 +00002756 // Binary Operators.
2757 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002758 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002759 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002760 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002761 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002762 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002763 case lltok::kw_udiv:
2764 case lltok::kw_sdiv:
2765 case lltok::kw_fdiv:
2766 case lltok::kw_urem:
2767 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002768 case lltok::kw_frem:
2769 case lltok::kw_shl:
2770 case lltok::kw_lshr:
2771 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002772 bool NUW = false;
2773 bool NSW = false;
2774 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002775 unsigned Opc = Lex.getUIntVal();
2776 Constant *Val0, *Val1;
2777 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002778 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002779 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2780 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002781 if (EatIfPresent(lltok::kw_nuw))
2782 NUW = true;
2783 if (EatIfPresent(lltok::kw_nsw)) {
2784 NSW = true;
2785 if (EatIfPresent(lltok::kw_nuw))
2786 NUW = true;
2787 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002788 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2789 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002790 if (EatIfPresent(lltok::kw_exact))
2791 Exact = true;
2792 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002793 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2794 ParseGlobalTypeAndValue(Val0) ||
2795 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2796 ParseGlobalTypeAndValue(Val1) ||
2797 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2798 return true;
2799 if (Val0->getType() != Val1->getType())
2800 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002801 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002802 if (NUW)
2803 return Error(ModifierLoc, "nuw only applies to integer operations");
2804 if (NSW)
2805 return Error(ModifierLoc, "nsw only applies to integer operations");
2806 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002807 // Check that the type is valid for the operator.
2808 switch (Opc) {
2809 case Instruction::Add:
2810 case Instruction::Sub:
2811 case Instruction::Mul:
2812 case Instruction::UDiv:
2813 case Instruction::SDiv:
2814 case Instruction::URem:
2815 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002816 case Instruction::Shl:
2817 case Instruction::AShr:
2818 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002819 if (!Val0->getType()->isIntOrIntVectorTy())
2820 return Error(ID.Loc, "constexpr requires integer operands");
2821 break;
2822 case Instruction::FAdd:
2823 case Instruction::FSub:
2824 case Instruction::FMul:
2825 case Instruction::FDiv:
2826 case Instruction::FRem:
2827 if (!Val0->getType()->isFPOrFPVectorTy())
2828 return Error(ID.Loc, "constexpr requires fp operands");
2829 break;
2830 default: llvm_unreachable("Unknown binary operator!");
2831 }
Dan Gohman1b849082009-09-07 23:54:19 +00002832 unsigned Flags = 0;
2833 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2834 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002835 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002836 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002837 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002838 ID.Kind = ValID::t_Constant;
2839 return false;
2840 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002841
Chris Lattnerac161bf2009-01-02 07:01:27 +00002842 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002843 case lltok::kw_and:
2844 case lltok::kw_or:
2845 case lltok::kw_xor: {
2846 unsigned Opc = Lex.getUIntVal();
2847 Constant *Val0, *Val1;
2848 Lex.Lex();
2849 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2850 ParseGlobalTypeAndValue(Val0) ||
2851 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2852 ParseGlobalTypeAndValue(Val1) ||
2853 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2854 return true;
2855 if (Val0->getType() != Val1->getType())
2856 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002857 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002858 return Error(ID.Loc,
2859 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002860 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002861 ID.Kind = ValID::t_Constant;
2862 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002863 }
2864
Chris Lattnerac161bf2009-01-02 07:01:27 +00002865 case lltok::kw_getelementptr:
2866 case lltok::kw_shufflevector:
2867 case lltok::kw_insertelement:
2868 case lltok::kw_extractelement:
2869 case lltok::kw_select: {
2870 unsigned Opc = Lex.getUIntVal();
2871 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002872 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00002873 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002874 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00002875
Dan Gohman1639c392009-07-27 21:53:46 +00002876 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002877 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00002878
2879 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2880 return true;
2881
2882 LocTy ExplicitTypeLoc = Lex.getLoc();
2883 if (Opc == Instruction::GetElementPtr) {
2884 if (ParseType(Ty) ||
2885 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2886 return true;
2887 }
2888
2889 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002890 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2891 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002892
Chris Lattnerac161bf2009-01-02 07:01:27 +00002893 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002894 if (Elts.size() == 0 ||
2895 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00002896 return Error(ID.Loc, "base of getelementptr must be a pointer");
2897
2898 Type *BaseType = Elts[0]->getType();
2899 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00002900 if (Ty != BasePointerType->getElementType())
2901 return Error(
2902 ExplicitTypeLoc,
2903 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002904
Jay Foaded8db7d2011-07-21 14:31:17 +00002905 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00002906 for (Constant *Val : Indices) {
2907 Type *ValTy = Val->getType();
2908 if (!ValTy->getScalarType()->isIntegerTy())
2909 return Error(ID.Loc, "getelementptr index must be an integer");
2910 if (ValTy->isVectorTy() != BaseType->isVectorTy())
2911 return Error(ID.Loc, "getelementptr index type missmatch");
2912 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00002913 unsigned ValNumEl = ValTy->getVectorNumElements();
2914 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00002915 if (ValNumEl != PtrNumEl)
2916 return Error(
2917 ID.Loc,
2918 "getelementptr vector index has a wrong number of elements");
2919 }
2920 }
2921
Craig Toppere3dcce92015-08-01 22:20:21 +00002922 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00002923 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00002924 return Error(ID.Loc, "base element of getelementptr must be sized");
2925
David Blaikie4a2e73b2015-04-02 18:55:32 +00002926 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00002927 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002928 ID.ConstantVal =
2929 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002930 } else if (Opc == Instruction::Select) {
2931 if (Elts.size() != 3)
2932 return Error(ID.Loc, "expected three operands to select");
2933 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2934 Elts[2]))
2935 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002936 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002937 } else if (Opc == Instruction::ShuffleVector) {
2938 if (Elts.size() != 3)
2939 return Error(ID.Loc, "expected three operands to shufflevector");
2940 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2941 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002942 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002943 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002944 } else if (Opc == Instruction::ExtractElement) {
2945 if (Elts.size() != 2)
2946 return Error(ID.Loc, "expected two operands to extractelement");
2947 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2948 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002949 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002950 } else {
2951 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2952 if (Elts.size() != 3)
2953 return Error(ID.Loc, "expected three operands to insertelement");
2954 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2955 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002956 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002957 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002958 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002959
Chris Lattnerac161bf2009-01-02 07:01:27 +00002960 ID.Kind = ValID::t_Constant;
2961 return false;
2962 }
2963 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002964
Chris Lattnerac161bf2009-01-02 07:01:27 +00002965 Lex.Lex();
2966 return false;
2967}
2968
2969/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002970bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002971 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002972 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002973 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002974 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002975 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002976 if (V && !(C = dyn_cast<Constant>(V)))
2977 return Error(ID.Loc, "global values must be constants");
2978 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002979}
2980
Victor Hernandez9d75c962010-01-11 22:31:58 +00002981bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002982 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002983 return ParseType(Ty) ||
2984 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002985}
2986
Rafael Espindola83a362c2015-01-06 22:55:16 +00002987bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00002988 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002989
2990 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00002991 if (!EatIfPresent(lltok::kw_comdat))
2992 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002993
2994 if (EatIfPresent(lltok::lparen)) {
2995 if (Lex.getKind() != lltok::ComdatVar)
2996 return TokError("expected comdat variable");
2997 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2998 Lex.Lex();
2999 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3000 return true;
3001 } else {
3002 if (GlobalName.empty())
3003 return TokError("comdat cannot be unnamed");
3004 C = getComdat(GlobalName, KwLoc);
3005 }
3006
David Majnemerdad0a642014-06-27 18:19:56 +00003007 return false;
3008}
3009
Victor Hernandez9d75c962010-01-11 22:31:58 +00003010/// ParseGlobalValueVector
3011/// ::= /*empty*/
3012/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003013bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003014 // Empty list.
3015 if (Lex.getKind() == lltok::rbrace ||
3016 Lex.getKind() == lltok::rsquare ||
3017 Lex.getKind() == lltok::greater ||
3018 Lex.getKind() == lltok::rparen)
3019 return false;
3020
3021 Constant *C;
3022 if (ParseGlobalTypeAndValue(C)) return true;
3023 Elts.push_back(C);
3024
3025 while (EatIfPresent(lltok::comma)) {
3026 if (ParseGlobalTypeAndValue(C)) return true;
3027 Elts.push_back(C);
3028 }
3029
3030 return false;
3031}
3032
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003033bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003034 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003035 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003036 return true;
3037
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003038 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003039 return false;
3040}
3041
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003042/// MDNode:
3043/// ::= !{ ... }
3044/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003045/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003046bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003047 if (Lex.getKind() == lltok::MetadataVar)
3048 return ParseSpecializedMDNode(N);
3049
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003050 return ParseToken(lltok::exclaim, "expected '!' here") ||
3051 ParseMDNodeTail(N);
3052}
3053
3054bool LLParser::ParseMDNodeTail(MDNode *&N) {
3055 // !{ ... }
3056 if (Lex.getKind() == lltok::lbrace)
3057 return ParseMDTuple(N);
3058
3059 // !42
3060 return ParseMDNodeID(N);
3061}
3062
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003063namespace {
3064
3065/// Structure to represent an optional metadata field.
3066template <class FieldTy> struct MDFieldImpl {
3067 typedef MDFieldImpl ImplTy;
3068 FieldTy Val;
3069 bool Seen;
3070
3071 void assign(FieldTy Val) {
3072 Seen = true;
3073 this->Val = std::move(Val);
3074 }
3075
3076 explicit MDFieldImpl(FieldTy Default)
3077 : Val(std::move(Default)), Seen(false) {}
3078};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003079
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003080struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3081 uint64_t Max;
3082
3083 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3084 : ImplTy(Default), Max(Max) {}
3085};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003086struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003087 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003088};
3089struct ColumnField : public MDUnsignedField {
3090 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3091};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003092struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003093 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003094 DwarfTagField(dwarf::Tag DefaultTag)
3095 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003096};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003097struct DwarfAttEncodingField : public MDUnsignedField {
3098 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3099};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003100struct DwarfVirtualityField : public MDUnsignedField {
3101 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3102};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003103struct DwarfLangField : public MDUnsignedField {
3104 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3105};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003106
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003107struct DIFlagField : public MDUnsignedField {
3108 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3109};
3110
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003111struct MDSignedField : public MDFieldImpl<int64_t> {
3112 int64_t Min;
3113 int64_t Max;
3114
3115 MDSignedField(int64_t Default = 0)
3116 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3117 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3118 : ImplTy(Default), Min(Min), Max(Max) {}
3119};
3120
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003121struct MDBoolField : public MDFieldImpl<bool> {
3122 MDBoolField(bool Default = false) : ImplTy(Default) {}
3123};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003124struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003125 bool AllowNull;
3126
3127 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003128};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003129struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3130 MDConstant() : ImplTy(nullptr) {}
3131};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003132struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003133 bool AllowEmpty;
3134 MDStringField(bool AllowEmpty = true)
3135 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003136};
3137struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3138 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3139};
3140
3141} // end namespace
3142
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003143namespace llvm {
3144
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003145template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003146bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003147 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003148 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3149 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003150
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003151 auto &U = Lex.getAPSIntVal();
3152 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003153 return TokError("value for '" + Name + "' too large, limit is " +
3154 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003155 Result.assign(U.getZExtValue());
3156 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003157 Lex.Lex();
3158 return false;
3159}
3160
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003161template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003162bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3163 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3164}
3165template <>
3166bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3167 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3168}
3169
3170template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003171bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3172 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003173 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003174
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003175 if (Lex.getKind() != lltok::DwarfTag)
3176 return TokError("expected DWARF tag");
3177
3178 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3179 if (Tag == dwarf::DW_TAG_invalid)
3180 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003181 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003182
3183 Result.assign(Tag);
3184 Lex.Lex();
3185 return false;
3186}
3187
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003188template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003189bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3190 DwarfVirtualityField &Result) {
3191 if (Lex.getKind() == lltok::APSInt)
3192 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3193
3194 if (Lex.getKind() != lltok::DwarfVirtuality)
3195 return TokError("expected DWARF virtuality code");
3196
3197 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3198 if (!Virtuality)
3199 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3200 Lex.getStrVal() + "'");
3201 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3202 Result.assign(Virtuality);
3203 Lex.Lex();
3204 return false;
3205}
3206
3207template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003208bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3209 if (Lex.getKind() == lltok::APSInt)
3210 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3211
3212 if (Lex.getKind() != lltok::DwarfLang)
3213 return TokError("expected DWARF language");
3214
3215 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3216 if (!Lang)
3217 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3218 "'");
3219 assert(Lang <= Result.Max && "Expected valid DWARF language");
3220 Result.assign(Lang);
3221 Lex.Lex();
3222 return false;
3223}
3224
3225template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003226bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003227 DwarfAttEncodingField &Result) {
3228 if (Lex.getKind() == lltok::APSInt)
3229 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3230
3231 if (Lex.getKind() != lltok::DwarfAttEncoding)
3232 return TokError("expected DWARF type attribute encoding");
3233
3234 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3235 if (!Encoding)
3236 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3237 Lex.getStrVal() + "'");
3238 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3239 Result.assign(Encoding);
3240 Lex.Lex();
3241 return false;
3242}
3243
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003244/// DIFlagField
3245/// ::= uint32
3246/// ::= DIFlagVector
3247/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3248template <>
3249bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3250 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3251
3252 // Parser for a single flag.
3253 auto parseFlag = [&](unsigned &Val) {
3254 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3255 return ParseUInt32(Val);
3256
3257 if (Lex.getKind() != lltok::DIFlag)
3258 return TokError("expected debug info flag");
3259
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003260 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003261 if (!Val)
3262 return TokError(Twine("invalid debug info flag flag '") +
3263 Lex.getStrVal() + "'");
3264 Lex.Lex();
3265 return false;
3266 };
3267
3268 // Parse the flags and combine them together.
3269 unsigned Combined = 0;
3270 do {
3271 unsigned Val;
3272 if (parseFlag(Val))
3273 return true;
3274 Combined |= Val;
3275 } while (EatIfPresent(lltok::bar));
3276
3277 Result.assign(Combined);
3278 return false;
3279}
3280
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003281template <>
3282bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003283 MDSignedField &Result) {
3284 if (Lex.getKind() != lltok::APSInt)
3285 return TokError("expected signed integer");
3286
3287 auto &S = Lex.getAPSIntVal();
3288 if (S < Result.Min)
3289 return TokError("value for '" + Name + "' too small, limit is " +
3290 Twine(Result.Min));
3291 if (S > Result.Max)
3292 return TokError("value for '" + Name + "' too large, limit is " +
3293 Twine(Result.Max));
3294 Result.assign(S.getExtValue());
3295 assert(Result.Val >= Result.Min && "Expected value in range");
3296 assert(Result.Val <= Result.Max && "Expected value in range");
3297 Lex.Lex();
3298 return false;
3299}
3300
3301template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003302bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3303 switch (Lex.getKind()) {
3304 default:
3305 return TokError("expected 'true' or 'false'");
3306 case lltok::kw_true:
3307 Result.assign(true);
3308 break;
3309 case lltok::kw_false:
3310 Result.assign(false);
3311 break;
3312 }
3313 Lex.Lex();
3314 return false;
3315}
3316
3317template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003318bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003319 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003320 if (!Result.AllowNull)
3321 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003322 Lex.Lex();
3323 Result.assign(nullptr);
3324 return false;
3325 }
3326
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003327 Metadata *MD;
3328 if (ParseMetadata(MD, nullptr))
3329 return true;
3330
3331 Result.assign(MD);
3332 return false;
3333}
3334
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003335template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003336bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3337 Metadata *MD;
3338 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3339 return true;
3340
3341 Result.assign(cast<ConstantAsMetadata>(MD));
3342 return false;
3343}
3344
3345template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003346bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003347 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003348 std::string S;
3349 if (ParseStringConstant(S))
3350 return true;
3351
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003352 if (!Result.AllowEmpty && S.empty())
3353 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3354
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003355 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003356 return false;
3357}
3358
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003359template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003360bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3361 SmallVector<Metadata *, 4> MDs;
3362 if (ParseMDNodeVector(MDs))
3363 return true;
3364
3365 Result.assign(std::move(MDs));
3366 return false;
3367}
3368
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003369} // end namespace llvm
3370
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003371template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003372bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003373 do {
3374 if (Lex.getKind() != lltok::LabelStr)
3375 return TokError("expected field label here");
3376
3377 if (parseField())
3378 return true;
3379 } while (EatIfPresent(lltok::comma));
3380
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003381 return false;
3382}
3383
3384template <class ParserTy>
3385bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3386 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3387 Lex.Lex();
3388
3389 if (ParseToken(lltok::lparen, "expected '(' here"))
3390 return true;
3391 if (Lex.getKind() != lltok::rparen)
3392 if (ParseMDFieldsImplBody(parseField))
3393 return true;
3394
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003395 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003396 return ParseToken(lltok::rparen, "expected ')' here");
3397}
3398
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003399template <class FieldTy>
3400bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3401 if (Result.Seen)
3402 return TokError("field '" + Name + "' cannot be specified more than once");
3403
3404 LocTy Loc = Lex.getLoc();
3405 Lex.Lex();
3406 return ParseMDField(Loc, Name, Result);
3407}
3408
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003409bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3410 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003411
3412#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003413 if (Lex.getStrVal() == #CLASS) \
3414 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003415#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003416
3417 return TokError("expected metadata type");
3418}
3419
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003420#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3421#define NOP_FIELD(NAME, TYPE, INIT)
3422#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3423 if (!NAME.Seen) \
3424 return Error(ClosingLoc, "missing required field '" #NAME "'");
3425#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003426 if (Lex.getStrVal() == #NAME) \
3427 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003428#define PARSE_MD_FIELDS() \
3429 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3430 do { \
3431 LocTy ClosingLoc; \
3432 if (ParseMDFieldsImpl([&]() -> bool { \
3433 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3434 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3435 }, ClosingLoc)) \
3436 return true; \
3437 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3438 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003439#define GET_OR_DISTINCT(CLASS, ARGS) \
3440 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003441
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003442/// ParseDILocationFields:
3443/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3444bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003445#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003446 OPTIONAL(line, LineField, ); \
3447 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003448 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003449 OPTIONAL(inlinedAt, MDField, );
3450 PARSE_MD_FIELDS();
3451#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003452
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003453 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003454 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003455 return false;
3456}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003457
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003458/// ParseGenericDINode:
3459/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3460bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003461#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003462 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003463 OPTIONAL(header, MDStringField, ); \
3464 OPTIONAL(operands, MDFieldList, );
3465 PARSE_MD_FIELDS();
3466#undef VISIT_MD_FIELDS
3467
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003468 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003469 (Context, tag.Val, header.Val, operands.Val));
3470 return false;
3471}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003472
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003473/// ParseDISubrange:
3474/// ::= !DISubrange(count: 30, lowerBound: 2)
3475bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003476#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003477 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003478 OPTIONAL(lowerBound, MDSignedField, );
3479 PARSE_MD_FIELDS();
3480#undef VISIT_MD_FIELDS
3481
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003482 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003483 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003484}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003485
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003486/// ParseDIEnumerator:
3487/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3488bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003489#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003490 REQUIRED(name, MDStringField, ); \
3491 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003492 PARSE_MD_FIELDS();
3493#undef VISIT_MD_FIELDS
3494
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003495 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003496 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003497}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003498
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003499/// ParseDIBasicType:
3500/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3501bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003502#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003503 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003504 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003505 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3506 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003507 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003508 PARSE_MD_FIELDS();
3509#undef VISIT_MD_FIELDS
3510
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003511 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003512 align.Val, encoding.Val));
3513 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003514}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003515
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003516/// ParseDIDerivedType:
3517/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003518/// line: 7, scope: !1, baseType: !2, size: 32,
3519/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003520bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003521#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3522 REQUIRED(tag, DwarfTagField, ); \
3523 OPTIONAL(name, MDStringField, ); \
3524 OPTIONAL(file, MDField, ); \
3525 OPTIONAL(line, LineField, ); \
3526 OPTIONAL(scope, MDField, ); \
3527 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003528 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3529 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3530 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003531 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003532 OPTIONAL(extraData, MDField, );
3533 PARSE_MD_FIELDS();
3534#undef VISIT_MD_FIELDS
3535
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003536 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003537 (Context, tag.Val, name.Val, file.Val, line.Val,
3538 scope.Val, baseType.Val, size.Val, align.Val,
3539 offset.Val, flags.Val, extraData.Val));
3540 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003541}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003542
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003543bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003544#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3545 REQUIRED(tag, DwarfTagField, ); \
3546 OPTIONAL(name, MDStringField, ); \
3547 OPTIONAL(file, MDField, ); \
3548 OPTIONAL(line, LineField, ); \
3549 OPTIONAL(scope, MDField, ); \
3550 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003551 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3552 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3553 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003554 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003555 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003556 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003557 OPTIONAL(vtableHolder, MDField, ); \
3558 OPTIONAL(templateParams, MDField, ); \
3559 OPTIONAL(identifier, MDStringField, );
3560 PARSE_MD_FIELDS();
3561#undef VISIT_MD_FIELDS
3562
3563 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003564 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003565 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3566 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3567 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3568 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003569}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003570
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003571bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003572#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003573 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003574 REQUIRED(types, MDField, );
3575 PARSE_MD_FIELDS();
3576#undef VISIT_MD_FIELDS
3577
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003578 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003579 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003580}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003581
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003582/// ParseDIFileType:
3583/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3584bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003585#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3586 REQUIRED(filename, MDStringField, ); \
3587 REQUIRED(directory, MDStringField, );
3588 PARSE_MD_FIELDS();
3589#undef VISIT_MD_FIELDS
3590
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003591 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003592 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003593}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003594
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003595/// ParseDICompileUnit:
3596/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003597/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3598/// splitDebugFilename: "abc.debug", emissionKind: 1,
3599/// enums: !1, retainedTypes: !2, subprograms: !3,
Adrian Prantl1f599f92015-05-21 20:37:30 +00003600/// globals: !4, imports: !5, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003601bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003602 if (!IsDistinct)
3603 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3604
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003605#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3606 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003607 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003608 OPTIONAL(producer, MDStringField, ); \
3609 OPTIONAL(isOptimized, MDBoolField, ); \
3610 OPTIONAL(flags, MDStringField, ); \
3611 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3612 OPTIONAL(splitDebugFilename, MDStringField, ); \
3613 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3614 OPTIONAL(enums, MDField, ); \
3615 OPTIONAL(retainedTypes, MDField, ); \
3616 OPTIONAL(subprograms, MDField, ); \
3617 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003618 OPTIONAL(imports, MDField, ); \
3619 OPTIONAL(dwoId, MDUnsignedField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003620 PARSE_MD_FIELDS();
3621#undef VISIT_MD_FIELDS
3622
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003623 Result = DICompileUnit::getDistinct(
3624 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3625 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
3626 retainedTypes.Val, subprograms.Val, globals.Val, imports.Val, dwoId.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003627 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003628}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003629
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003630/// ParseDISubprogram:
3631/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003632/// file: !1, line: 7, type: !2, isLocal: false,
3633/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003634/// virtuality: DW_VIRTUALTIY_pure_virtual,
3635/// virtualIndex: 10, flags: 11,
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003636/// isOptimized: false, function: void ()* @_Z3foov,
3637/// templateParams: !4, declaration: !5, variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003638bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003639#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3640 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003641 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003642 OPTIONAL(linkageName, MDStringField, ); \
3643 OPTIONAL(file, MDField, ); \
3644 OPTIONAL(line, LineField, ); \
3645 OPTIONAL(type, MDField, ); \
3646 OPTIONAL(isLocal, MDBoolField, ); \
3647 OPTIONAL(isDefinition, MDBoolField, (true)); \
3648 OPTIONAL(scopeLine, LineField, ); \
3649 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003650 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003651 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003652 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003653 OPTIONAL(isOptimized, MDBoolField, ); \
3654 OPTIONAL(function, MDConstant, ); \
3655 OPTIONAL(templateParams, MDField, ); \
3656 OPTIONAL(declaration, MDField, ); \
3657 OPTIONAL(variables, MDField, );
3658 PARSE_MD_FIELDS();
3659#undef VISIT_MD_FIELDS
3660
3661 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003662 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003663 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3664 scopeLine.Val, containingType.Val, virtuality.Val,
3665 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3666 templateParams.Val, declaration.Val, variables.Val));
3667 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003668}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003669
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003670/// ParseDILexicalBlock:
3671/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3672bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003673#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003674 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003675 OPTIONAL(file, MDField, ); \
3676 OPTIONAL(line, LineField, ); \
3677 OPTIONAL(column, ColumnField, );
3678 PARSE_MD_FIELDS();
3679#undef VISIT_MD_FIELDS
3680
3681 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003682 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003683 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003684}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003685
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003686/// ParseDILexicalBlockFile:
3687/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3688bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003689#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003690 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003691 OPTIONAL(file, MDField, ); \
3692 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3693 PARSE_MD_FIELDS();
3694#undef VISIT_MD_FIELDS
3695
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003696 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003697 (Context, scope.Val, file.Val, discriminator.Val));
3698 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003699}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003700
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003701/// ParseDINamespace:
3702/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3703bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003704#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3705 REQUIRED(scope, MDField, ); \
3706 OPTIONAL(file, MDField, ); \
3707 OPTIONAL(name, MDStringField, ); \
3708 OPTIONAL(line, LineField, );
3709 PARSE_MD_FIELDS();
3710#undef VISIT_MD_FIELDS
3711
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003712 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003713 (Context, scope.Val, file.Val, name.Val, line.Val));
3714 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003715}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003716
Adrian Prantlab1243f2015-06-29 23:03:47 +00003717/// ParseDIModule:
3718/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
3719/// includePath: "/usr/include", isysroot: "/")
3720bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
3721#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3722 REQUIRED(scope, MDField, ); \
3723 REQUIRED(name, MDStringField, ); \
3724 OPTIONAL(configMacros, MDStringField, ); \
3725 OPTIONAL(includePath, MDStringField, ); \
3726 OPTIONAL(isysroot, MDStringField, );
3727 PARSE_MD_FIELDS();
3728#undef VISIT_MD_FIELDS
3729
3730 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
3731 configMacros.Val, includePath.Val, isysroot.Val));
3732 return false;
3733}
3734
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003735/// ParseDITemplateTypeParameter:
3736/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3737bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003738#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003739 OPTIONAL(name, MDStringField, ); \
3740 REQUIRED(type, MDField, );
3741 PARSE_MD_FIELDS();
3742#undef VISIT_MD_FIELDS
3743
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003744 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003745 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003746 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003747}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003748
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003749/// ParseDITemplateValueParameter:
3750/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003751/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003752bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003753#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003754 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003755 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003756 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003757 REQUIRED(value, MDField, );
3758 PARSE_MD_FIELDS();
3759#undef VISIT_MD_FIELDS
3760
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003761 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003762 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003763 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003764}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003765
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003766/// ParseDIGlobalVariable:
3767/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003768/// file: !1, line: 7, type: !2, isLocal: false,
3769/// isDefinition: true, variable: i32* @foo,
3770/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003771bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003772#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003773 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003774 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003775 OPTIONAL(linkageName, MDStringField, ); \
3776 OPTIONAL(file, MDField, ); \
3777 OPTIONAL(line, LineField, ); \
3778 OPTIONAL(type, MDField, ); \
3779 OPTIONAL(isLocal, MDBoolField, ); \
3780 OPTIONAL(isDefinition, MDBoolField, (true)); \
3781 OPTIONAL(variable, MDConstant, ); \
3782 OPTIONAL(declaration, MDField, );
3783 PARSE_MD_FIELDS();
3784#undef VISIT_MD_FIELDS
3785
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003786 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003787 (Context, scope.Val, name.Val, linkageName.Val,
3788 file.Val, line.Val, type.Val, isLocal.Val,
3789 isDefinition.Val, variable.Val, declaration.Val));
3790 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003791}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003792
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003793/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00003794/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
3795/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3796/// ::= !DILocalVariable(scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003797/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003798bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003799#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003800 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003801 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00003802 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003803 OPTIONAL(file, MDField, ); \
3804 OPTIONAL(line, LineField, ); \
3805 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003806 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003807 PARSE_MD_FIELDS();
3808#undef VISIT_MD_FIELDS
3809
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003810 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00003811 (Context, scope.Val, name.Val, file.Val, line.Val,
3812 type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003813 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003814}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003815
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003816/// ParseDIExpression:
3817/// ::= !DIExpression(0, 7, -1)
3818bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003819 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3820 Lex.Lex();
3821
3822 if (ParseToken(lltok::lparen, "expected '(' here"))
3823 return true;
3824
3825 SmallVector<uint64_t, 8> Elements;
3826 if (Lex.getKind() != lltok::rparen)
3827 do {
3828 if (Lex.getKind() == lltok::DwarfOp) {
3829 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3830 Lex.Lex();
3831 Elements.push_back(Op);
3832 continue;
3833 }
3834 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3835 }
3836
3837 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3838 return TokError("expected unsigned integer");
3839
3840 auto &U = Lex.getAPSIntVal();
3841 if (U.ugt(UINT64_MAX))
3842 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3843 Elements.push_back(U.getZExtValue());
3844 Lex.Lex();
3845 } while (EatIfPresent(lltok::comma));
3846
3847 if (ParseToken(lltok::rparen, "expected ')' here"))
3848 return true;
3849
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003850 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003851 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003852}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003853
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003854/// ParseDIObjCProperty:
3855/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003856/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003857bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003858#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003859 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003860 OPTIONAL(file, MDField, ); \
3861 OPTIONAL(line, LineField, ); \
3862 OPTIONAL(setter, MDStringField, ); \
3863 OPTIONAL(getter, MDStringField, ); \
3864 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3865 OPTIONAL(type, MDField, );
3866 PARSE_MD_FIELDS();
3867#undef VISIT_MD_FIELDS
3868
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003869 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003870 (Context, name.Val, file.Val, line.Val, setter.Val,
3871 getter.Val, attributes.Val, type.Val));
3872 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003873}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003874
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003875/// ParseDIImportedEntity:
3876/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003877/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003878bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003879#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3880 REQUIRED(tag, DwarfTagField, ); \
3881 REQUIRED(scope, MDField, ); \
3882 OPTIONAL(entity, MDField, ); \
3883 OPTIONAL(line, LineField, ); \
3884 OPTIONAL(name, MDStringField, );
3885 PARSE_MD_FIELDS();
3886#undef VISIT_MD_FIELDS
3887
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003888 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003889 entity.Val, line.Val, name.Val));
3890 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003891}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003892
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003893#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003894#undef NOP_FIELD
3895#undef REQUIRE_FIELD
3896#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003897
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003898/// ParseMetadataAsValue
3899/// ::= metadata i32 %local
3900/// ::= metadata i32 @global
3901/// ::= metadata i32 7
3902/// ::= metadata !0
3903/// ::= metadata !{...}
3904/// ::= metadata !"string"
3905bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3906 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003907 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003908 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003909 return true;
3910
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003911 V = MetadataAsValue::get(Context, MD);
3912 return false;
3913}
3914
3915/// ParseValueAsMetadata
3916/// ::= i32 %local
3917/// ::= i32 @global
3918/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003919bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3920 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003921 Type *Ty;
3922 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003923 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003924 return true;
3925 if (Ty->isMetadataTy())
3926 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3927
3928 Value *V;
3929 if (ParseValue(Ty, V, PFS))
3930 return true;
3931
3932 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003933 return false;
3934}
3935
3936/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003937/// ::= i32 %local
3938/// ::= i32 @global
3939/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00003940/// ::= !42
3941/// ::= !{...}
3942/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003943/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003944bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003945 if (Lex.getKind() == lltok::MetadataVar) {
3946 MDNode *N;
3947 if (ParseSpecializedMDNode(N))
3948 return true;
3949 MD = N;
3950 return false;
3951 }
3952
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003953 // ValueAsMetadata:
3954 // <type> <value>
3955 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003956 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003957
3958 // '!'.
3959 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3960 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00003961
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003962 // MDString:
3963 // ::= '!' STRINGCONSTANT
3964 if (Lex.getKind() == lltok::StringConstant) {
3965 MDString *S;
3966 if (ParseMDString(S))
3967 return true;
3968 MD = S;
3969 return false;
3970 }
3971
Dan Gohman8939ba332010-07-14 18:26:50 +00003972 // MDNode:
3973 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003974 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003975 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003976 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003977 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003978 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00003979 return false;
3980}
3981
Victor Hernandez9d75c962010-01-11 22:31:58 +00003982
3983//===----------------------------------------------------------------------===//
3984// Function Parsing.
3985//===----------------------------------------------------------------------===//
3986
Chris Lattner229907c2011-07-18 04:54:35 +00003987bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003988 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003989 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003990 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003991
Chris Lattnerac161bf2009-01-02 07:01:27 +00003992 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003993 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003994 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3995 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003996 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003997 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003998 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3999 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004000 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004001 case ValID::t_InlineAsm: {
David Blaikie41ba2b42015-07-27 23:32:19 +00004002 assert(ID.FTy);
4003 if (!InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004004 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004005 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4006 (ID.UIntVal >> 1) & 1,
4007 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004008 return false;
4009 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004010 case ValID::t_GlobalName:
4011 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004012 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004013 case ValID::t_GlobalID:
4014 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004015 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004016 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004017 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004018 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004019 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004020 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004021 return false;
4022 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004023 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004024 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4025 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004026
Dan Gohman518cda42011-12-17 00:04:22 +00004027 // The lexer has no type info, so builds all half, float, and double FP
4028 // constants as double. Fix this here. Long double does not need this.
4029 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004030 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004031 if (Ty->isHalfTy())
4032 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4033 &Ignored);
4034 else if (Ty->isFloatTy())
4035 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4036 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004037 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004038 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004039
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004040 if (V->getType() != Ty)
4041 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004042 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004043
Chris Lattnerac161bf2009-01-02 07:01:27 +00004044 return false;
4045 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004046 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004047 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004048 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004049 return false;
4050 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004051 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004052 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004053 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004054 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004055 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004056 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004057 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004058 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004059 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004060 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004061 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004062 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004063 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004064 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004065 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004066 return false;
4067 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004068 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004069 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004070
Chris Lattnerac161bf2009-01-02 07:01:27 +00004071 V = ID.ConstantVal;
4072 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004073 case ValID::t_ConstantStruct:
4074 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004075 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004076 if (ST->getNumElements() != ID.UIntVal)
4077 return Error(ID.Loc,
4078 "initializer with struct type has wrong # elements");
4079 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4080 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004081
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004082 // Verify that the elements are compatible with the structtype.
4083 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4084 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4085 return Error(ID.Loc, "element " + Twine(i) +
4086 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004087
Reid Klecknere28b9cb2015-08-03 17:36:22 +00004088 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
4089 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004090 } else
4091 return Error(ID.Loc, "constant expression type mismatch");
4092 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004093 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004094 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004095}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004096
Alex Lorenzd2255952015-07-17 22:07:03 +00004097bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4098 C = nullptr;
4099 ValID ID;
4100 auto Loc = Lex.getLoc();
4101 if (ParseValID(ID, /*PFS=*/nullptr))
4102 return true;
4103 switch (ID.Kind) {
4104 case ValID::t_APSInt:
4105 case ValID::t_APFloat:
4106 case ValID::t_Constant:
4107 case ValID::t_ConstantStruct:
4108 case ValID::t_PackedConstantStruct: {
4109 Value *V;
4110 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4111 return true;
4112 assert(isa<Constant>(V) && "Expected a constant value");
4113 C = cast<Constant>(V);
4114 return false;
4115 }
4116 default:
4117 return Error(Loc, "expected a constant value");
4118 }
4119}
4120
Chris Lattner229907c2011-07-18 04:54:35 +00004121bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004122 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004123 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004124 return ParseValID(ID, PFS) ||
4125 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004126}
4127
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004128bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004129 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004130 return ParseType(Ty) ||
4131 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004132}
4133
Chris Lattner3ed871f2009-10-27 19:13:16 +00004134bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4135 PerFunctionState &PFS) {
4136 Value *V;
4137 Loc = Lex.getLoc();
4138 if (ParseTypeAndValue(V, PFS)) return true;
4139 if (!isa<BasicBlock>(V))
4140 return Error(Loc, "expected a basic block");
4141 BB = cast<BasicBlock>(V);
4142 return false;
4143}
4144
4145
Chris Lattnerac161bf2009-01-02 07:01:27 +00004146/// FunctionHeader
4147/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004148/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004149/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004150bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4151 // Parse the linkage.
4152 LocTy LinkageLoc = Lex.getLoc();
4153 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004154
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004155 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004156 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004157 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004158 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004159 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004160 LocTy RetTypeLoc = Lex.getLoc();
4161 if (ParseOptionalLinkage(Linkage) ||
4162 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00004163 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004164 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004165 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004166 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004167 return true;
4168
4169 // Verify that the linkage is ok.
4170 switch ((GlobalValue::LinkageTypes)Linkage) {
4171 case GlobalValue::ExternalLinkage:
4172 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004173 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004174 if (isDefine)
4175 return Error(LinkageLoc, "invalid linkage for function definition");
4176 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004177 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004178 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004179 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004180 case GlobalValue::LinkOnceAnyLinkage:
4181 case GlobalValue::LinkOnceODRLinkage:
4182 case GlobalValue::WeakAnyLinkage:
4183 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004184 if (!isDefine)
4185 return Error(LinkageLoc, "invalid linkage for function declaration");
4186 break;
4187 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004188 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004189 return Error(LinkageLoc, "invalid function linkage type");
4190 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004191
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004192 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4193 return Error(LinkageLoc,
4194 "symbol with local linkage must have default visibility");
4195
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004196 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004197 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004198
Chris Lattnerac161bf2009-01-02 07:01:27 +00004199 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004200
4201 std::string FunctionName;
4202 if (Lex.getKind() == lltok::GlobalVar) {
4203 FunctionName = Lex.getStrVal();
4204 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4205 unsigned NameID = Lex.getUIntVal();
4206
4207 if (NameID != NumberedVals.size())
4208 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004209 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004210 } else {
4211 return TokError("expected function name");
4212 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004213
Chris Lattner3822f632009-01-02 08:05:26 +00004214 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004215
Chris Lattner3822f632009-01-02 08:05:26 +00004216 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004217 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004218
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004219 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004220 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004221 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004222 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004223 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004224 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004225 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004226 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004227 bool UnnamedAddr;
4228 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004229 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004230 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004231 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004232 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004233
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004234 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004235 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4236 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004237 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004238 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004239 (EatIfPresent(lltok::kw_section) &&
4240 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004241 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004242 ParseOptionalAlignment(Alignment) ||
4243 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004244 ParseStringConstant(GC)) ||
4245 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004246 ParseGlobalTypeAndValue(Prefix)) ||
4247 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004248 ParseGlobalTypeAndValue(Prologue)) ||
4249 (EatIfPresent(lltok::kw_personality) &&
4250 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004251 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004252
Michael Gottesman41748d72013-06-27 00:25:01 +00004253 if (FuncAttrs.contains(Attribute::Builtin))
4254 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004255
Chris Lattnerac161bf2009-01-02 07:01:27 +00004256 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004257 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004258 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004259 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004260 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004261
Chris Lattnerac161bf2009-01-02 07:01:27 +00004262 // Okay, if we got here, the function is syntactically valid. Convert types
4263 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004264 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004265 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004266
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004267 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004268 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4269 AttributeSet::ReturnIndex,
4270 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004271
Chris Lattnerac161bf2009-01-02 07:01:27 +00004272 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004273 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004274 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4275 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004276 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4277 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004278 }
4279
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004280 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004281 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4282 AttributeSet::FunctionIndex,
4283 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004284
Bill Wendlinge94d8432012-12-07 23:16:57 +00004285 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004286
Bill Wendling749a43d2012-12-30 13:50:49 +00004287 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004288 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4289
Chris Lattner229907c2011-07-18 04:54:35 +00004290 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004291 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004292 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004293
Craig Topper2617dcc2014-04-15 06:32:26 +00004294 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004295 if (!FunctionName.empty()) {
4296 // If this was a definition of a forward reference, remove the definition
4297 // from the forward reference table and fill in the forward ref.
4298 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4299 ForwardRefVals.find(FunctionName);
4300 if (FRVI != ForwardRefVals.end()) {
4301 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004302 if (!Fn)
4303 return Error(FRVI->second.second, "invalid forward reference to "
4304 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004305 if (Fn->getType() != PFT)
4306 return Error(FRVI->second.second, "invalid forward reference to "
4307 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004308
Chris Lattnerac161bf2009-01-02 07:01:27 +00004309 ForwardRefVals.erase(FRVI);
4310 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004311 // Reject redefinitions.
4312 return Error(NameLoc, "invalid redefinition of function '" +
4313 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004314 } else if (M->getNamedValue(FunctionName)) {
4315 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004316 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004317
Dan Gohman399d6ae2009-08-29 23:37:49 +00004318 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004319 // If this is a definition of a forward referenced function, make sure the
4320 // types agree.
4321 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4322 = ForwardRefValIDs.find(NumberedVals.size());
4323 if (I != ForwardRefValIDs.end()) {
4324 Fn = cast<Function>(I->second.first);
4325 if (Fn->getType() != PFT)
4326 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004327 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004328 ForwardRefValIDs.erase(I);
4329 }
4330 }
4331
Craig Topper2617dcc2014-04-15 06:32:26 +00004332 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004333 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4334 else // Move the forward-reference to the correct spot in the module.
4335 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4336
4337 if (FunctionName.empty())
4338 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004339
Chris Lattnerac161bf2009-01-02 07:01:27 +00004340 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4341 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004342 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004343 Fn->setCallingConv(CC);
4344 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004345 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004346 Fn->setAlignment(Alignment);
4347 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004348 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004349 Fn->setPersonalityFn(PersonalityFn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004350 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004351 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004352 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004353 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004354
Chris Lattnerac161bf2009-01-02 07:01:27 +00004355 // Add all of the arguments we parsed to the function.
4356 Function::arg_iterator ArgIt = Fn->arg_begin();
4357 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4358 // If the argument has a name, insert it into the argument symbol table.
4359 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004360
Chris Lattnerac161bf2009-01-02 07:01:27 +00004361 // Set the name, if it conflicted, it will be auto-renamed.
4362 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004363
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004364 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004365 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4366 ArgList[i].Name + "'");
4367 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004368
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004369 if (isDefine)
4370 return false;
4371
Robin Morisset039781e2014-08-29 21:53:01 +00004372 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004373 ValID ID;
4374 if (FunctionName.empty()) {
4375 ID.Kind = ValID::t_GlobalID;
4376 ID.UIntVal = NumberedVals.size() - 1;
4377 } else {
4378 ID.Kind = ValID::t_GlobalName;
4379 ID.StrVal = FunctionName;
4380 }
4381 auto Blocks = ForwardRefBlockAddresses.find(ID);
4382 if (Blocks != ForwardRefBlockAddresses.end())
4383 return Error(Blocks->first.Loc,
4384 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004385 return false;
4386}
4387
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004388bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4389 ValID ID;
4390 if (FunctionNumber == -1) {
4391 ID.Kind = ValID::t_GlobalName;
4392 ID.StrVal = F.getName();
4393 } else {
4394 ID.Kind = ValID::t_GlobalID;
4395 ID.UIntVal = FunctionNumber;
4396 }
4397
4398 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4399 if (Blocks == P.ForwardRefBlockAddresses.end())
4400 return false;
4401
4402 for (const auto &I : Blocks->second) {
4403 const ValID &BBID = I.first;
4404 GlobalValue *GV = I.second;
4405
4406 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4407 "Expected local id or name");
4408 BasicBlock *BB;
4409 if (BBID.Kind == ValID::t_LocalName)
4410 BB = GetBB(BBID.StrVal, BBID.Loc);
4411 else
4412 BB = GetBB(BBID.UIntVal, BBID.Loc);
4413 if (!BB)
4414 return P.Error(BBID.Loc, "referenced value is not a basic block");
4415
4416 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4417 GV->eraseFromParent();
4418 }
4419
4420 P.ForwardRefBlockAddresses.erase(Blocks);
4421 return false;
4422}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004423
4424/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004425/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004426bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004427 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004428 return TokError("expected '{' in function body");
4429 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004430
Chris Lattner3432c622009-10-28 03:39:23 +00004431 int FunctionNumber = -1;
4432 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004433
Chris Lattner3432c622009-10-28 03:39:23 +00004434 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004435
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004436 // Resolve block addresses and allow basic blocks to be forward-declared
4437 // within this function.
4438 if (PFS.resolveForwardRefBlockAddresses())
4439 return true;
4440 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4441
Chris Lattnerbbddd962010-01-09 19:20:07 +00004442 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004443 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004444 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004445
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004446 while (Lex.getKind() != lltok::rbrace &&
4447 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004448 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004449
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004450 while (Lex.getKind() != lltok::rbrace)
4451 if (ParseUseListOrder(&PFS))
4452 return true;
4453
Chris Lattnerac161bf2009-01-02 07:01:27 +00004454 // Eat the }.
4455 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004456
Chris Lattnerac161bf2009-01-02 07:01:27 +00004457 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004458 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004459}
4460
4461/// ParseBasicBlock
4462/// ::= LabelStr? Instruction*
4463bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4464 // If this basic block starts out with a name, remember it.
4465 std::string Name;
4466 LocTy NameLoc = Lex.getLoc();
4467 if (Lex.getKind() == lltok::LabelStr) {
4468 Name = Lex.getStrVal();
4469 Lex.Lex();
4470 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004471
Chris Lattnerac161bf2009-01-02 07:01:27 +00004472 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004473 if (!BB)
4474 return Error(NameLoc,
4475 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004476
Chris Lattnerac161bf2009-01-02 07:01:27 +00004477 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004478
Chris Lattnerac161bf2009-01-02 07:01:27 +00004479 // Parse the instructions in this block until we get a terminator.
4480 Instruction *Inst;
4481 do {
4482 // This instruction may have three possibilities for a name: a) none
4483 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4484 LocTy NameLoc = Lex.getLoc();
4485 int NameID = -1;
4486 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004487
Chris Lattnerac161bf2009-01-02 07:01:27 +00004488 if (Lex.getKind() == lltok::LocalVarID) {
4489 NameID = Lex.getUIntVal();
4490 Lex.Lex();
4491 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4492 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004493 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004494 NameStr = Lex.getStrVal();
4495 Lex.Lex();
4496 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4497 return true;
4498 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004499
Chris Lattner77b89dc2009-12-30 05:23:43 +00004500 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004501 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004502 case InstError: return true;
4503 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004504 BB->getInstList().push_back(Inst);
4505
Chris Lattner77b89dc2009-12-30 05:23:43 +00004506 // With a normal result, we check to see if the instruction is followed by
4507 // a comma and metadata.
4508 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004509 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004510 return true;
4511 break;
4512 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004513 BB->getInstList().push_back(Inst);
4514
Chris Lattner77b89dc2009-12-30 05:23:43 +00004515 // If the instruction parser ate an extra comma at the end of it, it
4516 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004517 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004518 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004519 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004520 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004521
Chris Lattnerac161bf2009-01-02 07:01:27 +00004522 // Set the name on the instruction.
4523 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4524 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004525
Chris Lattnerac161bf2009-01-02 07:01:27 +00004526 return false;
4527}
4528
4529//===----------------------------------------------------------------------===//
4530// Instruction Parsing.
4531//===----------------------------------------------------------------------===//
4532
4533/// ParseInstruction - Parse one of the many different instructions.
4534///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004535int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4536 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004537 lltok::Kind Token = Lex.getKind();
4538 if (Token == lltok::Eof)
4539 return TokError("found end of file when expecting more instructions");
4540 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004541 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004542 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004543
Chris Lattnerac161bf2009-01-02 07:01:27 +00004544 switch (Token) {
4545 default: return Error(Loc, "expected instruction opcode");
4546 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004547 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004548 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4549 case lltok::kw_br: return ParseBr(Inst, PFS);
4550 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004551 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004552 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004553 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00004554 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4555 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
4556 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
4557 case lltok::kw_terminatepad: return ParseTerminatePad(Inst, PFS);
4558 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
4559 case lltok::kw_catchendpad: return ParseCatchEndPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004560 // Binary Operators.
4561 case lltok::kw_add:
4562 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004563 case lltok::kw_mul:
4564 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004565 bool NUW = EatIfPresent(lltok::kw_nuw);
4566 bool NSW = EatIfPresent(lltok::kw_nsw);
4567 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004568
Chris Lattnera676c0f2011-02-07 16:40:21 +00004569 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004570
Chris Lattnera676c0f2011-02-07 16:40:21 +00004571 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4572 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4573 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004574 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004575 case lltok::kw_fadd:
4576 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004577 case lltok::kw_fmul:
4578 case lltok::kw_fdiv:
4579 case lltok::kw_frem: {
4580 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4581 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4582 if (Res != 0)
4583 return Res;
4584 if (FMF.any())
4585 Inst->setFastMathFlags(FMF);
4586 return 0;
4587 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004588
Chris Lattner35315d02011-02-06 21:44:57 +00004589 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004590 case lltok::kw_udiv:
4591 case lltok::kw_lshr:
4592 case lltok::kw_ashr: {
4593 bool Exact = EatIfPresent(lltok::kw_exact);
4594
4595 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4596 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4597 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004598 }
4599
Chris Lattnerac161bf2009-01-02 07:01:27 +00004600 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004601 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004602 case lltok::kw_and:
4603 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004604 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00004605 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4606 case lltok::kw_fcmp: {
4607 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4608 int Res = ParseCompare(Inst, PFS, KeywordVal);
4609 if (Res != 0)
4610 return Res;
4611 if (FMF.any())
4612 Inst->setFastMathFlags(FMF);
4613 return 0;
4614 }
4615
Chris Lattnerac161bf2009-01-02 07:01:27 +00004616 // Casts.
4617 case lltok::kw_trunc:
4618 case lltok::kw_zext:
4619 case lltok::kw_sext:
4620 case lltok::kw_fptrunc:
4621 case lltok::kw_fpext:
4622 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004623 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004624 case lltok::kw_uitofp:
4625 case lltok::kw_sitofp:
4626 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004627 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004628 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004629 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004630 // Other.
4631 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004632 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004633 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4634 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4635 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4636 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004637 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004638 // Call.
4639 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4640 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4641 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004642 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004643 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004644 case lltok::kw_load: return ParseLoad(Inst, PFS);
4645 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004646 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4647 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004648 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004649 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4650 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4651 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4652 }
4653}
4654
4655/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4656bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004657 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004658 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004659 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004660 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4661 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4662 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4663 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4664 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4665 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4666 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4667 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4668 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4669 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4670 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4671 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4672 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4673 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4674 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4675 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4676 }
4677 } else {
4678 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004679 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004680 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4681 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4682 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4683 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4684 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4685 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4686 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4687 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4688 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4689 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4690 }
4691 }
4692 Lex.Lex();
4693 return false;
4694}
4695
4696//===----------------------------------------------------------------------===//
4697// Terminator Instructions.
4698//===----------------------------------------------------------------------===//
4699
4700/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00004701/// ::= 'ret' void (',' !dbg, !1)*
4702/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00004703bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004704 PerFunctionState &PFS) {
4705 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00004706 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00004707 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004708
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004709 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004710
Chris Lattnerfdd87902009-10-05 05:54:46 +00004711 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004712 if (!ResType->isVoidTy())
4713 return Error(TypeLoc, "value doesn't match function result type '" +
4714 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004715
Owen Anderson55f1c092009-08-13 21:58:54 +00004716 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004717 return false;
4718 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004719
Chris Lattnerac161bf2009-01-02 07:01:27 +00004720 Value *RV;
4721 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004722
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004723 if (ResType != RV->getType())
4724 return Error(TypeLoc, "value doesn't match function result type '" +
4725 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004726
Owen Anderson55f1c092009-08-13 21:58:54 +00004727 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00004728 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004729}
4730
4731
4732/// ParseBr
4733/// ::= 'br' TypeAndValue
4734/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4735bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4736 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004737 Value *Op0;
4738 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004739 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004740
Chris Lattnerac161bf2009-01-02 07:01:27 +00004741 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4742 Inst = BranchInst::Create(BB);
4743 return false;
4744 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004745
Owen Anderson55f1c092009-08-13 21:58:54 +00004746 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004747 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004748
Chris Lattnerac161bf2009-01-02 07:01:27 +00004749 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004750 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004751 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004752 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004753 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004754
Chris Lattner3ed871f2009-10-27 19:13:16 +00004755 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004756 return false;
4757}
4758
4759/// ParseSwitch
4760/// Instruction
4761/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4762/// JumpTable
4763/// ::= (TypeAndValue ',' TypeAndValue)*
4764bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4765 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004766 Value *Cond;
4767 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004768 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4769 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004770 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004771 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4772 return true;
4773
Duncan Sands19d0b472010-02-16 11:11:14 +00004774 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004775 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004776
Chris Lattnerac161bf2009-01-02 07:01:27 +00004777 // Parse the jump table pairs.
4778 SmallPtrSet<Value*, 32> SeenCases;
4779 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4780 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004781 Value *Constant;
4782 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004783
Chris Lattnerac161bf2009-01-02 07:01:27 +00004784 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4785 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004786 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004787 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004788
David Blaikie70573dc2014-11-19 07:49:26 +00004789 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004790 return Error(CondLoc, "duplicate case value in switch");
4791 if (!isa<ConstantInt>(Constant))
4792 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004793
Chris Lattner3ed871f2009-10-27 19:13:16 +00004794 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004795 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004796
Chris Lattnerac161bf2009-01-02 07:01:27 +00004797 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004798
Chris Lattner3ed871f2009-10-27 19:13:16 +00004799 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004800 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4801 SI->addCase(Table[i].first, Table[i].second);
4802 Inst = SI;
4803 return false;
4804}
4805
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004806/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00004807/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004808/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4809bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004810 LocTy AddrLoc;
4811 Value *Address;
4812 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004813 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4814 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00004815 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004816
Duncan Sands19d0b472010-02-16 11:11:14 +00004817 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004818 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004819
Chris Lattner3ed871f2009-10-27 19:13:16 +00004820 // Parse the destination list.
4821 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004822
Chris Lattner3ed871f2009-10-27 19:13:16 +00004823 if (Lex.getKind() != lltok::rsquare) {
4824 BasicBlock *DestBB;
4825 if (ParseTypeAndBasicBlock(DestBB, PFS))
4826 return true;
4827 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004828
Chris Lattner3ed871f2009-10-27 19:13:16 +00004829 while (EatIfPresent(lltok::comma)) {
4830 if (ParseTypeAndBasicBlock(DestBB, PFS))
4831 return true;
4832 DestList.push_back(DestBB);
4833 }
4834 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004835
Chris Lattner3ed871f2009-10-27 19:13:16 +00004836 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4837 return true;
4838
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004839 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00004840 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4841 IBI->addDestination(DestList[i]);
4842 Inst = IBI;
4843 return false;
4844}
4845
4846
Chris Lattnerac161bf2009-01-02 07:01:27 +00004847/// ParseInvoke
4848/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4849/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4850bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4851 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00004852 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004853 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00004854 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004855 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004856 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004857 LocTy RetTypeLoc;
4858 ValID CalleeID;
4859 SmallVector<ParamInfo, 16> ArgList;
4860
Chris Lattner3ed871f2009-10-27 19:13:16 +00004861 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004862 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004863 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004864 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004865 ParseValID(CalleeID) ||
4866 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004867 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4868 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004869 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004870 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004871 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004872 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004873 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004874
Chris Lattnerac161bf2009-01-02 07:01:27 +00004875 // If RetType is a non-function pointer type, then this is the short syntax
4876 // for the call, which means that RetType is just the return type. Infer the
4877 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00004878 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4879 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004880 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004881 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004882 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4883 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004884
Chris Lattnerac161bf2009-01-02 07:01:27 +00004885 if (!FunctionType::isValidReturnType(RetType))
4886 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004887
Owen Anderson4056ca92009-07-29 22:17:13 +00004888 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004889 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004890
David Blaikie41ba2b42015-07-27 23:32:19 +00004891 CalleeID.FTy = Ty;
4892
Chris Lattnerac161bf2009-01-02 07:01:27 +00004893 // Look up the callee.
4894 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00004895 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4896 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004897
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004898 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004899 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004900 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004901 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4902 AttributeSet::ReturnIndex,
4903 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004904
Chris Lattnerac161bf2009-01-02 07:01:27 +00004905 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004906
Chris Lattnerac161bf2009-01-02 07:01:27 +00004907 // Loop through FunctionType's arguments and ensure they are specified
4908 // correctly. Also, gather any parameter attributes.
4909 FunctionType::param_iterator I = Ty->param_begin();
4910 FunctionType::param_iterator E = Ty->param_end();
4911 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004912 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004913 if (I != E) {
4914 ExpectedTy = *I++;
4915 } else if (!Ty->isVarArg()) {
4916 return Error(ArgList[i].Loc, "too many arguments specified");
4917 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004918
Chris Lattnerac161bf2009-01-02 07:01:27 +00004919 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4920 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004921 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004922 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004923 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4924 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004925 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4926 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004927 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004928
Chris Lattnerac161bf2009-01-02 07:01:27 +00004929 if (I != E)
4930 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004931
David Majnemer8d22abd2015-02-23 00:01:32 +00004932 if (FnAttrs.hasAttributes()) {
4933 if (FnAttrs.hasAlignmentAttr())
4934 return Error(CallLoc, "invoke instructions may not have an alignment");
4935
Bill Wendlingf5075a42013-01-27 02:24:02 +00004936 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4937 AttributeSet::FunctionIndex,
4938 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00004939 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004940
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004941 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004942 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004943
David Blaikie3e807092015-05-13 18:35:26 +00004944 InvokeInst *II = InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004945 II->setCallingConv(CC);
4946 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004947 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004948 Inst = II;
4949 return false;
4950}
4951
Bill Wendlingf891bf82011-07-31 06:30:59 +00004952/// ParseResume
4953/// ::= 'resume' TypeAndValue
4954bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4955 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004956 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4957 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004958
Bill Wendlingf891bf82011-07-31 06:30:59 +00004959 ResumeInst *RI = ResumeInst::Create(Exn);
4960 Inst = RI;
4961 return false;
4962}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004963
David Majnemer654e1302015-07-31 17:58:14 +00004964bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
4965 PerFunctionState &PFS) {
4966 if (ParseToken(lltok::lsquare, "expected '[' in cleanuppad"))
4967 return true;
4968
4969 while (Lex.getKind() != lltok::rsquare) {
4970 // If this isn't the first argument, we need a comma.
4971 if (!Args.empty() &&
4972 ParseToken(lltok::comma, "expected ',' in argument list"))
4973 return true;
4974
4975 // Parse the argument.
4976 LocTy ArgLoc;
4977 Type *ArgTy = nullptr;
4978 if (ParseType(ArgTy, ArgLoc))
4979 return true;
4980
4981 Value *V;
4982 if (ArgTy->isMetadataTy()) {
4983 if (ParseMetadataAsValue(V, PFS))
4984 return true;
4985 } else {
4986 if (ParseValue(ArgTy, V, PFS))
4987 return true;
4988 }
4989 Args.push_back(V);
4990 }
4991
4992 Lex.Lex(); // Lex the ']'.
4993 return false;
4994}
4995
4996/// ParseCleanupRet
4997/// ::= 'cleanupret' ('void' | TypeAndValue) unwind ('to' 'caller' | TypeAndValue)
4998bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
4999 Type *RetTy = nullptr;
5000 Value *RetVal = nullptr;
5001 if (ParseType(RetTy, /*AllowVoid=*/true))
5002 return true;
5003
5004 if (!RetTy->isVoidTy())
5005 if (ParseValue(RetTy, RetVal, PFS))
5006 return true;
5007
5008 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5009 return true;
5010
5011 BasicBlock *UnwindBB = nullptr;
5012 if (Lex.getKind() == lltok::kw_to) {
5013 Lex.Lex();
5014 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5015 return true;
5016 } else {
5017 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5018 return true;
5019 }
5020 }
5021
5022 Inst = CleanupReturnInst::Create(Context, RetVal, UnwindBB);
5023 return false;
5024}
5025
5026/// ParseCatchRet
5027/// ::= 'catchret' TypeAndValue
5028bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
5029 BasicBlock *BB;
5030 if (ParseTypeAndBasicBlock(BB, PFS))
5031 return true;
5032
5033 Inst = CatchReturnInst::Create(BB);
5034 return false;
5035}
5036
5037/// ParseCatchPad
5038/// ::= 'catchpad' Type ParamList 'to' TypeAndValue 'unwind' TypeAndValue
5039bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
5040 Type *RetType = nullptr;
5041
5042 SmallVector<Value *, 8> Args;
5043 if (ParseType(RetType, /*AllowVoid=*/true) || ParseExceptionArgs(Args, PFS))
5044 return true;
5045
5046 BasicBlock *NormalBB, *UnwindBB;
5047 if (ParseToken(lltok::kw_to, "expected 'to' in catchpad") ||
5048 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5049 ParseToken(lltok::kw_unwind, "expected 'unwind' in catchpad") ||
5050 ParseTypeAndBasicBlock(UnwindBB, PFS))
5051 return true;
5052
5053 Inst = CatchPadInst::Create(RetType, NormalBB, UnwindBB, Args);
5054 return false;
5055}
5056
5057/// ParseTerminatePad
5058/// ::= 'terminatepad' ParamList 'to' TypeAndValue
5059bool LLParser::ParseTerminatePad(Instruction *&Inst, PerFunctionState &PFS) {
5060 SmallVector<Value *, 8> Args;
5061 if (ParseExceptionArgs(Args, PFS))
5062 return true;
5063
5064 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in terminatepad"))
5065 return true;
5066
5067 BasicBlock *UnwindBB = nullptr;
5068 if (Lex.getKind() == lltok::kw_to) {
5069 Lex.Lex();
5070 if (ParseToken(lltok::kw_caller, "expected 'caller' in terminatepad"))
5071 return true;
5072 } else {
5073 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5074 return true;
5075 }
5076 }
5077
5078 Inst = TerminatePadInst::Create(Context, UnwindBB, Args);
5079 return false;
5080}
5081
5082/// ParseCleanupPad
5083/// ::= 'cleanuppad' ParamList
5084bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
5085 Type *RetType = nullptr;
5086
5087 SmallVector<Value *, 8> Args;
5088 if (ParseType(RetType, /*AllowVoid=*/true) || ParseExceptionArgs(Args, PFS))
5089 return true;
5090
5091 Inst = CleanupPadInst::Create(RetType, Args);
5092 return false;
5093}
5094
5095/// ParseCatchEndPad
5096/// ::= 'catchendpad' unwind ('to' 'caller' | TypeAndValue)
5097bool LLParser::ParseCatchEndPad(Instruction *&Inst, PerFunctionState &PFS) {
5098 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in catchendpad"))
5099 return true;
5100
5101 BasicBlock *UnwindBB = nullptr;
5102 if (Lex.getKind() == lltok::kw_to) {
5103 Lex.Lex();
5104 if (Lex.getKind() == lltok::kw_caller) {
5105 Lex.Lex();
5106 } else {
5107 return true;
5108 }
5109 } else {
5110 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5111 return true;
5112 }
5113 }
5114
5115 Inst = CatchEndPadInst::Create(Context, UnwindBB);
5116 return false;
5117}
5118
Chris Lattnerac161bf2009-01-02 07:01:27 +00005119//===----------------------------------------------------------------------===//
5120// Binary Operators.
5121//===----------------------------------------------------------------------===//
5122
5123/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005124/// ::= ArithmeticOps TypeAndValue ',' Value
5125///
5126/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5127/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005128bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005129 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005130 LocTy Loc; Value *LHS, *RHS;
5131 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5132 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5133 ParseValue(LHS->getType(), RHS, PFS))
5134 return true;
5135
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005136 bool Valid;
5137 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005138 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005139 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005140 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5141 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005142 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005143 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5144 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005145 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005146
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005147 if (!Valid)
5148 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005149
Chris Lattnerac161bf2009-01-02 07:01:27 +00005150 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5151 return false;
5152}
5153
5154/// ParseLogical
5155/// ::= ArithmeticOps TypeAndValue ',' Value {
5156bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5157 unsigned Opc) {
5158 LocTy Loc; Value *LHS, *RHS;
5159 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5160 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5161 ParseValue(LHS->getType(), RHS, PFS))
5162 return true;
5163
Duncan Sands9dff9be2010-02-15 16:12:20 +00005164 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005165 return Error(Loc,"instruction requires integer or integer vector operands");
5166
5167 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5168 return false;
5169}
5170
5171
5172/// ParseCompare
5173/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5174/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005175bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5176 unsigned Opc) {
5177 // Parse the integer/fp comparison predicate.
5178 LocTy Loc;
5179 unsigned Pred;
5180 Value *LHS, *RHS;
5181 if (ParseCmpPredicate(Pred, Opc) ||
5182 ParseTypeAndValue(LHS, Loc, PFS) ||
5183 ParseToken(lltok::comma, "expected ',' after compare value") ||
5184 ParseValue(LHS->getType(), RHS, PFS))
5185 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005186
Chris Lattnerac161bf2009-01-02 07:01:27 +00005187 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005188 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005189 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005190 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005191 } else {
5192 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005193 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005194 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005195 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005196 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005197 }
5198 return false;
5199}
5200
5201//===----------------------------------------------------------------------===//
5202// Other Instructions.
5203//===----------------------------------------------------------------------===//
5204
5205
5206/// ParseCast
5207/// ::= CastOpc TypeAndValue 'to' Type
5208bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5209 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005210 LocTy Loc;
5211 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005212 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005213 if (ParseTypeAndValue(Op, Loc, PFS) ||
5214 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5215 ParseType(DestTy))
5216 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005217
Chris Lattner89d856e2009-03-01 00:53:13 +00005218 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5219 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005220 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005221 getTypeString(Op->getType()) + "' to '" +
5222 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005223 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005224 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5225 return false;
5226}
5227
5228/// ParseSelect
5229/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5230bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5231 LocTy Loc;
5232 Value *Op0, *Op1, *Op2;
5233 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5234 ParseToken(lltok::comma, "expected ',' after select condition") ||
5235 ParseTypeAndValue(Op1, PFS) ||
5236 ParseToken(lltok::comma, "expected ',' after select value") ||
5237 ParseTypeAndValue(Op2, PFS))
5238 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005239
Chris Lattnerac161bf2009-01-02 07:01:27 +00005240 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5241 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005242
Chris Lattnerac161bf2009-01-02 07:01:27 +00005243 Inst = SelectInst::Create(Op0, Op1, Op2);
5244 return false;
5245}
5246
Chris Lattnerb55ab542009-01-05 08:18:44 +00005247/// ParseVA_Arg
5248/// ::= 'va_arg' TypeAndValue ',' Type
5249bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005250 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005251 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005252 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005253 if (ParseTypeAndValue(Op, PFS) ||
5254 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005255 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005256 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005257
Chris Lattnerb55ab542009-01-05 08:18:44 +00005258 if (!EltTy->isFirstClassType())
5259 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005260
5261 Inst = new VAArgInst(Op, EltTy);
5262 return false;
5263}
5264
5265/// ParseExtractElement
5266/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5267bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5268 LocTy Loc;
5269 Value *Op0, *Op1;
5270 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5271 ParseToken(lltok::comma, "expected ',' after extract value") ||
5272 ParseTypeAndValue(Op1, PFS))
5273 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005274
Chris Lattnerac161bf2009-01-02 07:01:27 +00005275 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5276 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005277
Eric Christopherc9742252009-07-25 02:28:41 +00005278 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005279 return false;
5280}
5281
5282/// ParseInsertElement
5283/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5284bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5285 LocTy Loc;
5286 Value *Op0, *Op1, *Op2;
5287 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5288 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5289 ParseTypeAndValue(Op1, PFS) ||
5290 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5291 ParseTypeAndValue(Op2, PFS))
5292 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005293
Chris Lattnerac161bf2009-01-02 07:01:27 +00005294 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005295 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005296
Chris Lattnerac161bf2009-01-02 07:01:27 +00005297 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5298 return false;
5299}
5300
5301/// ParseShuffleVector
5302/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5303bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5304 LocTy Loc;
5305 Value *Op0, *Op1, *Op2;
5306 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5307 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5308 ParseTypeAndValue(Op1, PFS) ||
5309 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5310 ParseTypeAndValue(Op2, PFS))
5311 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005312
Chris Lattnerac161bf2009-01-02 07:01:27 +00005313 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005314 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005315
Chris Lattnerac161bf2009-01-02 07:01:27 +00005316 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5317 return false;
5318}
5319
5320/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005321/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005322int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005323 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005324 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005325
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005326 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005327 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5328 ParseValue(Ty, Op0, PFS) ||
5329 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005330 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005331 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5332 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005333
Chris Lattnerf4f03422009-12-30 05:27:33 +00005334 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005335 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5336 while (1) {
5337 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005338
Chris Lattner3822f632009-01-02 08:05:26 +00005339 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005340 break;
5341
Chris Lattnerf4f03422009-12-30 05:27:33 +00005342 if (Lex.getKind() == lltok::MetadataVar) {
5343 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005344 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005345 }
Devang Patel8f842d32009-10-16 18:45:49 +00005346
Chris Lattner3822f632009-01-02 08:05:26 +00005347 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005348 ParseValue(Ty, Op0, PFS) ||
5349 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005350 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005351 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5352 return true;
5353 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005354
Chris Lattnerac161bf2009-01-02 07:01:27 +00005355 if (!Ty->isFirstClassType())
5356 return Error(TypeLoc, "phi node must have first class type");
5357
Jay Foad52131342011-03-30 11:28:46 +00005358 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005359 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5360 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5361 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005362 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005363}
5364
Bill Wendlingfae14752011-08-12 20:24:12 +00005365/// ParseLandingPad
5366/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5367/// Clause
5368/// ::= 'catch' TypeAndValue
5369/// ::= 'filter'
5370/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5371bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005372 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005373
David Majnemer7fddecc2015-06-17 20:52:32 +00005374 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005375 return true;
5376
David Majnemer7fddecc2015-06-17 20:52:32 +00005377 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005378 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5379
5380 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5381 LandingPadInst::ClauseType CT;
5382 if (EatIfPresent(lltok::kw_catch))
5383 CT = LandingPadInst::Catch;
5384 else if (EatIfPresent(lltok::kw_filter))
5385 CT = LandingPadInst::Filter;
5386 else
5387 return TokError("expected 'catch' or 'filter' clause type");
5388
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005389 Value *V;
5390 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005391 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005392 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005393
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005394 // A 'catch' type expects a non-array constant. A filter clause expects an
5395 // array constant.
5396 if (CT == LandingPadInst::Catch) {
5397 if (isa<ArrayType>(V->getType()))
5398 Error(VLoc, "'catch' clause has an invalid type");
5399 } else {
5400 if (!isa<ArrayType>(V->getType()))
5401 Error(VLoc, "'filter' clause has an invalid type");
5402 }
5403
Owen Andersonf8f259d2015-03-09 07:13:42 +00005404 Constant *CV = dyn_cast<Constant>(V);
5405 if (!CV)
5406 return Error(VLoc, "clause argument must be a constant");
5407 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005408 }
5409
Owen Andersonf8f259d2015-03-09 07:13:42 +00005410 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005411 return false;
5412}
5413
Chris Lattnerac161bf2009-01-02 07:01:27 +00005414/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00005415/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5416/// ParameterList OptionalAttrs
5417/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5418/// ParameterList OptionalAttrs
5419/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005420/// ParameterList OptionalAttrs
5421bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005422 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005423 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005424 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005425 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005426 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005427 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005428 LocTy RetTypeLoc;
5429 ValID CalleeID;
5430 SmallVector<ParamInfo, 16> ArgList;
5431 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005432
Reid Kleckner5772b772014-04-24 20:14:34 +00005433 if ((TCK != CallInst::TCK_None &&
5434 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005435 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00005436 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005437 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005438 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005439 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5440 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005441 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005442 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005443 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005444
Chris Lattnerac161bf2009-01-02 07:01:27 +00005445 // If RetType is a non-function pointer type, then this is the short syntax
5446 // for the call, which means that RetType is just the return type. Infer the
5447 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005448 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5449 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005450 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005451 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005452 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5453 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005454
Chris Lattnerac161bf2009-01-02 07:01:27 +00005455 if (!FunctionType::isValidReturnType(RetType))
5456 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005457
Owen Anderson4056ca92009-07-29 22:17:13 +00005458 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005459 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005460
David Blaikie41ba2b42015-07-27 23:32:19 +00005461 CalleeID.FTy = Ty;
5462
Chris Lattnerac161bf2009-01-02 07:01:27 +00005463 // Look up the callee.
5464 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005465 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5466 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005467
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005468 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005469 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005470 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005471 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5472 AttributeSet::ReturnIndex,
5473 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005474
Chris Lattnerac161bf2009-01-02 07:01:27 +00005475 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005476
Chris Lattnerac161bf2009-01-02 07:01:27 +00005477 // Loop through FunctionType's arguments and ensure they are specified
5478 // correctly. Also, gather any parameter attributes.
5479 FunctionType::param_iterator I = Ty->param_begin();
5480 FunctionType::param_iterator E = Ty->param_end();
5481 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005482 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005483 if (I != E) {
5484 ExpectedTy = *I++;
5485 } else if (!Ty->isVarArg()) {
5486 return Error(ArgList[i].Loc, "too many arguments specified");
5487 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005488
Chris Lattnerac161bf2009-01-02 07:01:27 +00005489 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5490 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005491 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005492 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005493 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5494 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005495 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5496 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005497 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005498
Chris Lattnerac161bf2009-01-02 07:01:27 +00005499 if (I != E)
5500 return Error(CallLoc, "not enough parameters specified for call");
5501
David Majnemer8d22abd2015-02-23 00:01:32 +00005502 if (FnAttrs.hasAttributes()) {
5503 if (FnAttrs.hasAlignmentAttr())
5504 return Error(CallLoc, "call instructions may not have an alignment");
5505
Bill Wendlingf5075a42013-01-27 02:24:02 +00005506 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5507 AttributeSet::FunctionIndex,
5508 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005509 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005510
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005511 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005512 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005513
David Blaikie348de692015-04-23 21:36:23 +00005514 CallInst *CI = CallInst::Create(Ty, Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00005515 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005516 CI->setCallingConv(CC);
5517 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005518 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005519 Inst = CI;
5520 return false;
5521}
5522
5523//===----------------------------------------------------------------------===//
5524// Memory Instructions.
5525//===----------------------------------------------------------------------===//
5526
5527/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00005528/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005529int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005530 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005531 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005532 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005533 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005534
5535 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5536
David Majnemera3b0eb22015-02-16 08:38:03 +00005537 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005538
David Majnemera3b0eb22015-02-16 08:38:03 +00005539 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5540 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005541
Chris Lattnerb2f39502009-12-30 05:44:30 +00005542 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005543 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005544 if (Lex.getKind() == lltok::kw_align) {
5545 if (ParseOptionalAlignment(Alignment)) return true;
5546 } else if (Lex.getKind() == lltok::MetadataVar) {
5547 AteExtraComma = true;
5548 } else {
5549 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5550 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5551 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005552 }
5553 }
5554
Dan Gohman2140a742010-05-28 01:14:11 +00005555 if (Size && !Size->getType()->isIntegerTy())
5556 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005557
Reid Kleckner436c42e2014-01-17 23:58:17 +00005558 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5559 AI->setUsedWithInAlloca(IsInAlloca);
5560 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005561 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005562}
5563
5564/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005565/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005566/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005567/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005568int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005569 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005570 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005571 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005572 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005573 AtomicOrdering Ordering = NotAtomic;
5574 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005575
5576 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005577 isAtomic = true;
5578 Lex.Lex();
5579 }
5580
Chris Lattnerbc639292011-11-27 06:56:53 +00005581 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005582 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005583 isVolatile = true;
5584 Lex.Lex();
5585 }
5586
David Blaikie15d9a4c2015-04-06 20:59:48 +00005587 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005588 LocTy ExplicitTypeLoc = Lex.getLoc();
5589 if (ParseType(Ty) ||
5590 ParseToken(lltok::comma, "expected comma after load's type") ||
5591 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005592 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005593 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5594 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005595
David Blaikie15d9a4c2015-04-06 20:59:48 +00005596 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005597 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005598 if (isAtomic && !Alignment)
5599 return Error(Loc, "atomic load must have explicit non-zero alignment");
5600 if (Ordering == Release || Ordering == AcquireRelease)
5601 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005602
David Blaikiea79ac142015-02-27 21:17:42 +00005603 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5604 return Error(ExplicitTypeLoc,
5605 "explicit pointee type doesn't match operand's pointee type");
5606
David Blaikie15d9a4c2015-04-06 20:59:48 +00005607 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005608 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005609}
5610
5611/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005612
5613/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5614/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005615/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005616int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005617 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005618 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005619 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005620 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005621 AtomicOrdering Ordering = NotAtomic;
5622 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005623
5624 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005625 isAtomic = true;
5626 Lex.Lex();
5627 }
5628
Chris Lattnerbc639292011-11-27 06:56:53 +00005629 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005630 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005631 isVolatile = true;
5632 Lex.Lex();
5633 }
5634
Chris Lattnerac161bf2009-01-02 07:01:27 +00005635 if (ParseTypeAndValue(Val, Loc, PFS) ||
5636 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005637 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005638 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005639 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005640 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00005641
Duncan Sands19d0b472010-02-16 11:11:14 +00005642 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005643 return Error(PtrLoc, "store operand must be a pointer");
5644 if (!Val->getType()->isFirstClassType())
5645 return Error(Loc, "store operand must be a first class value");
5646 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5647 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00005648 if (isAtomic && !Alignment)
5649 return Error(Loc, "atomic store must have explicit non-zero alignment");
5650 if (Ordering == Acquire || Ordering == AcquireRelease)
5651 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005652
Eli Friedman59b66882011-08-09 23:02:53 +00005653 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005654 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005655}
5656
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005657/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00005658/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5659/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00005660int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005661 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5662 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00005663 AtomicOrdering SuccessOrdering = NotAtomic;
5664 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005665 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005666 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00005667 bool isWeak = false;
5668
5669 if (EatIfPresent(lltok::kw_weak))
5670 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00005671
5672 if (EatIfPresent(lltok::kw_volatile))
5673 isVolatile = true;
5674
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005675 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5676 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5677 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5678 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5679 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00005680 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5681 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005682 return true;
5683
Tim Northovere94a5182014-03-11 10:48:52 +00005684 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005685 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00005686 if (SuccessOrdering < FailureOrdering)
5687 return TokError("cmpxchg must be at least as ordered on success as failure");
5688 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5689 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005690 if (!Ptr->getType()->isPointerTy())
5691 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5692 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5693 return Error(CmpLoc, "compare value and pointer type do not match");
5694 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5695 return Error(NewLoc, "new value and pointer type do not match");
5696 if (!New->getType()->isIntegerTy())
5697 return Error(NewLoc, "cmpxchg operand must be an integer");
5698 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5699 if (Size < 8 || (Size & (Size - 1)))
5700 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5701 " integer");
5702
Tim Northover420a2162014-06-13 14:24:07 +00005703 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5704 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005705 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00005706 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005707 Inst = CXI;
5708 return AteExtraComma ? InstExtraComma : InstNormal;
5709}
5710
5711/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00005712/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5713/// 'singlethread'? AtomicOrdering
5714int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005715 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5716 bool AteExtraComma = false;
5717 AtomicOrdering Ordering = NotAtomic;
5718 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005719 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005720 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00005721
5722 if (EatIfPresent(lltok::kw_volatile))
5723 isVolatile = true;
5724
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005725 switch (Lex.getKind()) {
5726 default: return TokError("expected binary operation in atomicrmw");
5727 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5728 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5729 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5730 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5731 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5732 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5733 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5734 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5735 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5736 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5737 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5738 }
5739 Lex.Lex(); // Eat the operation.
5740
5741 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5742 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5743 ParseTypeAndValue(Val, ValLoc, PFS) ||
5744 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5745 return true;
5746
5747 if (Ordering == Unordered)
5748 return TokError("atomicrmw cannot be unordered");
5749 if (!Ptr->getType()->isPointerTy())
5750 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5751 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5752 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5753 if (!Val->getType()->isIntegerTy())
5754 return Error(ValLoc, "atomicrmw operand must be an integer");
5755 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5756 if (Size < 8 || (Size & (Size - 1)))
5757 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5758 " integer");
5759
5760 AtomicRMWInst *RMWI =
5761 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5762 RMWI->setVolatile(isVolatile);
5763 Inst = RMWI;
5764 return AteExtraComma ? InstExtraComma : InstNormal;
5765}
5766
Eli Friedmanfee02c62011-07-25 23:16:38 +00005767/// ParseFence
5768/// ::= 'fence' 'singlethread'? AtomicOrdering
5769int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5770 AtomicOrdering Ordering = NotAtomic;
5771 SynchronizationScope Scope = CrossThread;
5772 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5773 return true;
5774
5775 if (Ordering == Unordered)
5776 return TokError("fence cannot be unordered");
5777 if (Ordering == Monotonic)
5778 return TokError("fence cannot be monotonic");
5779
5780 Inst = new FenceInst(Context, Ordering, Scope);
5781 return InstNormal;
5782}
5783
Chris Lattnerac161bf2009-01-02 07:01:27 +00005784/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00005785/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005786int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005787 Value *Ptr = nullptr;
5788 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005789 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00005790
Dan Gohman16cbbe42009-07-29 15:58:36 +00005791 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00005792
David Blaikie79e6c742015-02-27 19:29:02 +00005793 Type *Ty = nullptr;
5794 LocTy ExplicitTypeLoc = Lex.getLoc();
5795 if (ParseType(Ty) ||
5796 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5797 ParseTypeAndValue(Ptr, Loc, PFS))
5798 return true;
5799
Eli Benderskyd9806682013-04-22 17:03:42 +00005800 Type *BaseType = Ptr->getType();
5801 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5802 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005803 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005804
David Blaikie8d757942015-03-09 23:08:44 +00005805 if (Ty != BasePointerType->getElementType())
5806 return Error(ExplicitTypeLoc,
5807 "explicit pointee type doesn't match operand's pointee type");
5808
Chris Lattnerac161bf2009-01-02 07:01:27 +00005809 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005810 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00005811 // GEP returns a vector of pointers if at least one of parameters is a vector.
5812 // All vector parameters should have the same vector width.
5813 unsigned GEPWidth = BaseType->isVectorTy() ?
5814 BaseType->getVectorNumElements() : 0;
5815
Chris Lattner3822f632009-01-02 08:05:26 +00005816 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00005817 if (Lex.getKind() == lltok::MetadataVar) {
5818 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00005819 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005820 }
Chris Lattner3822f632009-01-02 08:05:26 +00005821 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005822 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005823 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00005824
Nadav Rotem3924cb02011-12-05 06:29:09 +00005825 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00005826 unsigned ValNumEl = Val->getType()->getVectorNumElements();
5827 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00005828 return Error(EltLoc,
5829 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00005830 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005831 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005832 Indices.push_back(Val);
5833 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005834
Craig Toppere3dcce92015-08-01 22:20:21 +00005835 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00005836 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00005837 return Error(Loc, "base element of getelementptr must be sized");
5838
David Blaikied33bad32015-04-17 22:32:13 +00005839 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005840 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00005841 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00005842 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00005843 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005844 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005845}
5846
5847/// ParseExtractValue
5848/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005849int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005850 Value *Val; LocTy Loc;
5851 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005852 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005853 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005854 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005855 return true;
5856
Chris Lattner392be582010-02-12 20:49:41 +00005857 if (!Val->getType()->isAggregateType())
5858 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005859
Jay Foad57aa6362011-07-13 10:26:04 +00005860 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005861 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00005862 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005863 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005864}
5865
5866/// ParseInsertValue
5867/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005868int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005869 Value *Val0, *Val1; LocTy Loc0, Loc1;
5870 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005871 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005872 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5873 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5874 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005875 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005876 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005877
Chris Lattner392be582010-02-12 20:49:41 +00005878 if (!Val0->getType()->isAggregateType())
5879 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005880
David Majnemer30074532015-02-11 07:43:58 +00005881 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5882 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005883 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00005884 if (IndexedType != Val1->getType())
5885 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5886 getTypeString(Val1->getType()) + "' instead of '" +
5887 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00005888 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005889 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005890}
Nick Lewycky49f89192009-04-04 07:22:01 +00005891
5892//===----------------------------------------------------------------------===//
5893// Embedded metadata.
5894//===----------------------------------------------------------------------===//
5895
5896/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005897/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005898/// Element
5899/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005900bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00005901 if (ParseToken(lltok::lbrace, "expected '{' here"))
5902 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005903
Dan Gohman1e0213a2010-07-13 19:33:27 +00005904 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005905 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00005906 return false;
5907
Nick Lewycky49f89192009-04-04 07:22:01 +00005908 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005909 // Null is a special case since it is typeless.
5910 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005911 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005912 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005913 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005914
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005915 Metadata *MD;
5916 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005917 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005918 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00005919 } while (EatIfPresent(lltok::comma));
5920
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005921 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00005922}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005923
5924//===----------------------------------------------------------------------===//
5925// Use-list order directives.
5926//===----------------------------------------------------------------------===//
5927bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5928 SMLoc Loc) {
5929 if (V->use_empty())
5930 return Error(Loc, "value has no uses");
5931
5932 unsigned NumUses = 0;
5933 SmallDenseMap<const Use *, unsigned, 16> Order;
5934 for (const Use &U : V->uses()) {
5935 if (++NumUses > Indexes.size())
5936 break;
5937 Order[&U] = Indexes[NumUses - 1];
5938 }
5939 if (NumUses < 2)
5940 return Error(Loc, "value only has one use");
5941 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5942 return Error(Loc, "wrong number of indexes, expected " +
5943 Twine(std::distance(V->use_begin(), V->use_end())));
5944
5945 V->sortUseList([&](const Use &L, const Use &R) {
5946 return Order.lookup(&L) < Order.lookup(&R);
5947 });
5948 return false;
5949}
5950
5951/// ParseUseListOrderIndexes
5952/// ::= '{' uint32 (',' uint32)+ '}'
5953bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5954 SMLoc Loc = Lex.getLoc();
5955 if (ParseToken(lltok::lbrace, "expected '{' here"))
5956 return true;
5957 if (Lex.getKind() == lltok::rbrace)
5958 return Lex.Error("expected non-empty list of uselistorder indexes");
5959
5960 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5961 // indexes should be distinct numbers in the range [0, size-1], and should
5962 // not be in order.
5963 unsigned Offset = 0;
5964 unsigned Max = 0;
5965 bool IsOrdered = true;
5966 assert(Indexes.empty() && "Expected empty order vector");
5967 do {
5968 unsigned Index;
5969 if (ParseUInt32(Index))
5970 return true;
5971
5972 // Update consistency checks.
5973 Offset += Index - Indexes.size();
5974 Max = std::max(Max, Index);
5975 IsOrdered &= Index == Indexes.size();
5976
5977 Indexes.push_back(Index);
5978 } while (EatIfPresent(lltok::comma));
5979
5980 if (ParseToken(lltok::rbrace, "expected '}' here"))
5981 return true;
5982
5983 if (Indexes.size() < 2)
5984 return Error(Loc, "expected >= 2 uselistorder indexes");
5985 if (Offset != 0 || Max >= Indexes.size())
5986 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5987 if (IsOrdered)
5988 return Error(Loc, "expected uselistorder indexes to change the order");
5989
5990 return false;
5991}
5992
5993/// ParseUseListOrder
5994/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5995bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5996 SMLoc Loc = Lex.getLoc();
5997 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5998 return true;
5999
6000 Value *V;
6001 SmallVector<unsigned, 16> Indexes;
6002 if (ParseTypeAndValue(V, PFS) ||
6003 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6004 ParseUseListOrderIndexes(Indexes))
6005 return true;
6006
6007 return sortUseListOrder(V, Indexes, Loc);
6008}
6009
6010/// ParseUseListOrderBB
6011/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6012bool LLParser::ParseUseListOrderBB() {
6013 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6014 SMLoc Loc = Lex.getLoc();
6015 Lex.Lex();
6016
6017 ValID Fn, Label;
6018 SmallVector<unsigned, 16> Indexes;
6019 if (ParseValID(Fn) ||
6020 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6021 ParseValID(Label) ||
6022 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6023 ParseUseListOrderIndexes(Indexes))
6024 return true;
6025
6026 // Check the function.
6027 GlobalValue *GV;
6028 if (Fn.Kind == ValID::t_GlobalName)
6029 GV = M->getNamedValue(Fn.StrVal);
6030 else if (Fn.Kind == ValID::t_GlobalID)
6031 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6032 else
6033 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6034 if (!GV)
6035 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6036 auto *F = dyn_cast<Function>(GV);
6037 if (!F)
6038 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6039 if (F->isDeclaration())
6040 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6041
6042 // Check the basic block.
6043 if (Label.Kind == ValID::t_LocalID)
6044 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6045 if (Label.Kind != ValID::t_LocalName)
6046 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6047 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6048 if (!V)
6049 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6050 if (!isa<BasicBlock>(V))
6051 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6052
6053 return sortUseListOrder(V, Indexes, Loc);
6054}