blob: c2a2ef2b7eb672c76c0069b8aa2a53703ac9da36 [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"
David Blaikieadbda4b2015-08-03 20:08:41 +000016#include "llvm/ADT/STLExtras.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000017#include "llvm/AsmParser/SlotMapping.h"
Chandler Carruth91065212014-03-05 10:34:14 +000018#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/CallingConv.h"
20#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +000021#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000022#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/InlineAsm.h"
25#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000026#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
28#include "llvm/IR/Operator.h"
29#include "llvm/IR/ValueSymbolTable.h"
Philip Reames1960cfd2016-02-19 00:06:41 +000030#include "llvm/Support/Debug.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000031#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000033#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000034#include "llvm/Support/raw_ostream.h"
35using namespace llvm;
36
Chris Lattner229907c2011-07-18 04:54:35 +000037static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000038 std::string Result;
39 raw_string_ostream Tmp(Result);
40 Tmp << *T;
41 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000042}
43
Chris Lattner3822f632009-01-02 08:05:26 +000044/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000045bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000046 // Prime the lexer.
47 Lex.Lex();
48
Mehdi Amini50af49f2016-04-02 03:46:17 +000049 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000050 return Error(
51 Lex.getLoc(),
52 "Can't read textual IR with a Context that discards named Values");
53
Chris Lattnerad6f3352009-01-04 20:44:11 +000054 return ParseTopLevelEntities() ||
55 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000056}
57
Alex Lorenz1de2acd2015-08-21 21:32:39 +000058bool LLParser::parseStandaloneConstantValue(Constant *&C,
59 const SlotMapping *Slots) {
60 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000061 Lex.Lex();
62
63 Type *Ty = nullptr;
64 if (ParseType(Ty) || parseConstantValue(Ty, C))
65 return true;
66 if (Lex.getKind() != lltok::Eof)
67 return Error(Lex.getLoc(), "expected end of string");
68 return false;
69}
70
Quentin Colombetdafed5d2016-03-08 00:37:07 +000071bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
72 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000073 restoreParsingState(Slots);
74 Lex.Lex();
75
Quentin Colombetdafed5d2016-03-08 00:37:07 +000076 Read = 0;
77 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000078 Ty = nullptr;
79 if (ParseType(Ty))
80 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +000081 SMLoc End = Lex.getLoc();
82 Read = End.getPointer() - Start.getPointer();
83
Quentin Colombet81e72b42016-03-07 22:09:05 +000084 return false;
85}
86
Alex Lorenz1de2acd2015-08-21 21:32:39 +000087void LLParser::restoreParsingState(const SlotMapping *Slots) {
88 if (!Slots)
89 return;
90 NumberedVals = Slots->GlobalValues;
91 NumberedMetadata = Slots->MetadataNodes;
92 for (const auto &I : Slots->NamedTypes)
93 NamedTypes.insert(
94 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
95 for (const auto &I : Slots->Types)
96 NumberedTypes.insert(
97 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
98}
99
Chris Lattnerac161bf2009-01-02 07:01:27 +0000100/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
101/// module.
102bool LLParser::ValidateEndOfModule() {
Manman Ren209b17c2013-09-28 00:22:27 +0000103 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
104 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
105
Bill Wendlingb32b0412013-02-08 06:32:06 +0000106 // Handle any function attribute group forward references.
107 for (std::map<Value*, std::vector<unsigned> >::iterator
108 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
109 I != E; ++I) {
110 Value *V = I->first;
111 std::vector<unsigned> &Vec = I->second;
112 AttrBuilder B;
113
114 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
115 VI != VE; ++VI)
116 B.merge(NumberedAttrBuilders[*VI]);
117
118 if (Function *Fn = dyn_cast<Function>(V)) {
119 AttributeSet AS = Fn->getAttributes();
120 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
121 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
122 AS.getFnAttributes());
123
124 FnAttrs.merge(B);
125
126 // If the alignment was parsed as an attribute, move to the alignment
127 // field.
128 if (FnAttrs.hasAlignmentAttr()) {
129 Fn->setAlignment(FnAttrs.getAlignment());
130 FnAttrs.removeAttribute(Attribute::Alignment);
131 }
132
133 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
134 AttributeSet::get(Context,
135 AttributeSet::FunctionIndex,
136 FnAttrs));
137 Fn->setAttributes(AS);
138 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
139 AttributeSet AS = CI->getAttributes();
140 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
141 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
142 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000143 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000144 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
145 AttributeSet::get(Context,
146 AttributeSet::FunctionIndex,
147 FnAttrs));
148 CI->setAttributes(AS);
149 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
150 AttributeSet AS = II->getAttributes();
151 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
152 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
153 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000154 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000155 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
156 AttributeSet::get(Context,
157 AttributeSet::FunctionIndex,
158 FnAttrs));
159 II->setAttributes(AS);
160 } else {
161 llvm_unreachable("invalid object with forward attribute group reference");
162 }
163 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000164
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000165 // If there are entries in ForwardRefBlockAddresses at this point, the
166 // function was never defined.
167 if (!ForwardRefBlockAddresses.empty())
168 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
169 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000170
David Majnemer19b51052015-02-11 07:43:56 +0000171 for (const auto &NT : NumberedTypes)
172 if (NT.second.second.isValid())
173 return Error(NT.second.second,
174 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000175
176 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
177 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
178 if (I->second.second.isValid())
179 return Error(I->second.second,
180 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000181
David Majnemerdad0a642014-06-27 18:19:56 +0000182 if (!ForwardRefComdats.empty())
183 return Error(ForwardRefComdats.begin()->second,
184 "use of undefined comdat '$" +
185 ForwardRefComdats.begin()->first + "'");
186
Chris Lattnerac161bf2009-01-02 07:01:27 +0000187 if (!ForwardRefVals.empty())
188 return Error(ForwardRefVals.begin()->second.second,
189 "use of undefined value '@" + ForwardRefVals.begin()->first +
190 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000191
Chris Lattnerac161bf2009-01-02 07:01:27 +0000192 if (!ForwardRefValIDs.empty())
193 return Error(ForwardRefValIDs.begin()->second.second,
194 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000195 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000196
Devang Pateld2541152009-07-08 19:23:54 +0000197 if (!ForwardRefMDNodes.empty())
198 return Error(ForwardRefMDNodes.begin()->second.second,
199 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000200 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000201
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000202 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000203 for (auto &N : NumberedMetadata) {
204 if (N.second && !N.second->isResolved())
205 N.second->resolveCycles();
206 }
Devang Pateld2541152009-07-08 19:23:54 +0000207
Chris Lattnerac161bf2009-01-02 07:01:27 +0000208 // Look for intrinsic functions and CallInst that need to be upgraded
209 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000210 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000211
Manman Ren8b4306c2013-12-02 21:29:56 +0000212 UpgradeDebugInfo(*M);
213
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000214 if (!Slots)
215 return false;
216 // Initialize the slot mapping.
217 // Because by this point we've parsed and validated everything, we can "steal"
218 // the mapping from LLParser as it doesn't need it anymore.
219 Slots->GlobalValues = std::move(NumberedVals);
220 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000221 for (const auto &I : NamedTypes)
222 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
223 for (const auto &I : NumberedTypes)
224 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000225
Chris Lattnerac161bf2009-01-02 07:01:27 +0000226 return false;
227}
228
229//===----------------------------------------------------------------------===//
230// Top-Level Entities
231//===----------------------------------------------------------------------===//
232
233bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000234 while (1) {
235 switch (Lex.getKind()) {
236 default: return TokError("expected top-level entity");
237 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000238 case lltok::kw_declare: if (ParseDeclare()) return true; break;
239 case lltok::kw_define: if (ParseDefine()) return true; break;
240 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
241 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000242 case lltok::kw_source_filename:
243 if (ParseSourceFileName())
244 return true;
245 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000246 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000247 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000248 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000249 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000250 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000251 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000252 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000253 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000254
255 // The Global variable production with no name can have many different
256 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000257 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000258 // OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000259 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000260 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000261 case lltok::kw_internal: // OptionalLinkage
262 case lltok::kw_weak: // OptionalLinkage
263 case lltok::kw_weak_odr: // OptionalLinkage
264 case lltok::kw_linkonce: // OptionalLinkage
265 case lltok::kw_linkonce_odr: // OptionalLinkage
266 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000267 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000268 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000269 case lltok::kw_external: // OptionalLinkage
270 case lltok::kw_default: // OptionalVisibility
271 case lltok::kw_hidden: // OptionalVisibility
272 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000273 case lltok::kw_dllimport: // OptionalDLLStorageClass
274 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000275 case lltok::kw_thread_local: // OptionalThreadLocal
276 case lltok::kw_addrspace: // OptionalAddrSpace
277 case lltok::kw_constant: // GlobalType
278 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000279 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000280 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000281 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000282 bool HasLinkage;
283 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000284 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000285 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000286 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000287 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000288 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000289 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000290 return true;
291 break;
292 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000293
294 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000295 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
296 case lltok::kw_uselistorder_bb:
297 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000298 }
299 }
300}
301
302
303/// toplevelentity
304/// ::= 'module' 'asm' STRINGCONSTANT
305bool LLParser::ParseModuleAsm() {
306 assert(Lex.getKind() == lltok::kw_module);
307 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000308
309 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000310 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
311 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000312
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000313 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000314 return false;
315}
316
317/// toplevelentity
318/// ::= 'target' 'triple' '=' STRINGCONSTANT
319/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
320bool LLParser::ParseTargetDefinition() {
321 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000322 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000323 switch (Lex.Lex()) {
324 default: return TokError("unknown target property");
325 case lltok::kw_triple:
326 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000327 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
328 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000329 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000330 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000331 return false;
332 case lltok::kw_datalayout:
333 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000334 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
335 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000336 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000337 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000338 return false;
339 }
340}
341
Bill Wendling706d3d62012-11-28 08:41:48 +0000342/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000343/// ::= 'source_filename' '=' STRINGCONSTANT
344bool LLParser::ParseSourceFileName() {
345 assert(Lex.getKind() == lltok::kw_source_filename);
346 std::string Str;
347 Lex.Lex();
348 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
349 ParseStringConstant(Str))
350 return true;
351 M->setSourceFileName(Str);
352 return false;
353}
354
355/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000356/// ::= 'deplibs' '=' '[' ']'
357/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
358/// FIXME: Remove in 4.0. Currently parse, but ignore.
359bool LLParser::ParseDepLibs() {
360 assert(Lex.getKind() == lltok::kw_deplibs);
361 Lex.Lex();
362 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
363 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
364 return true;
365
366 if (EatIfPresent(lltok::rsquare))
367 return false;
368
369 do {
370 std::string Str;
371 if (ParseStringConstant(Str)) return true;
372 } while (EatIfPresent(lltok::comma));
373
374 return ParseToken(lltok::rsquare, "expected ']' at end of list");
375}
376
Dan Gohman466876b2009-08-12 23:32:33 +0000377/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000378/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000379bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000380 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000381 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000382 Lex.Lex(); // eat LocalVarID;
383
384 if (ParseToken(lltok::equal, "expected '=' after name") ||
385 ParseToken(lltok::kw_type, "expected 'type' after '='"))
386 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000387
Craig Topper2617dcc2014-04-15 06:32:26 +0000388 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000389 if (ParseStructDefinition(TypeLoc, "",
390 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000391
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000392 if (!isa<StructType>(Result)) {
393 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
394 if (Entry.first)
395 return Error(TypeLoc, "non-struct types may not be recursive");
396 Entry.first = Result;
397 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000398 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000399
Chris Lattnerac161bf2009-01-02 07:01:27 +0000400 return false;
401}
402
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000403
Chris Lattnerac161bf2009-01-02 07:01:27 +0000404/// toplevelentity
405/// ::= LocalVar '=' 'type' type
406bool LLParser::ParseNamedType() {
407 std::string Name = Lex.getStrVal();
408 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000409 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000410
Chris Lattner3822f632009-01-02 08:05:26 +0000411 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000412 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000413 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000414
Craig Topper2617dcc2014-04-15 06:32:26 +0000415 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000416 if (ParseStructDefinition(NameLoc, Name,
417 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000418
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000419 if (!isa<StructType>(Result)) {
420 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
421 if (Entry.first)
422 return Error(NameLoc, "non-struct types may not be recursive");
423 Entry.first = Result;
424 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000425 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000426
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000427 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000428}
429
430
431/// toplevelentity
432/// ::= 'declare' FunctionHeader
433bool LLParser::ParseDeclare() {
434 assert(Lex.getKind() == lltok::kw_declare);
435 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000436
Chris Lattnerac161bf2009-01-02 07:01:27 +0000437 Function *F;
438 return ParseFunctionHeader(F, false);
439}
440
441/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000442/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000443bool LLParser::ParseDefine() {
444 assert(Lex.getKind() == lltok::kw_define);
445 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000446
Chris Lattnerac161bf2009-01-02 07:01:27 +0000447 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000448 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000449 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000450 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000451}
452
Chris Lattner3822f632009-01-02 08:05:26 +0000453/// ParseGlobalType
454/// ::= 'constant'
455/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000456bool LLParser::ParseGlobalType(bool &IsConstant) {
457 if (Lex.getKind() == lltok::kw_constant)
458 IsConstant = true;
459 else if (Lex.getKind() == lltok::kw_global)
460 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000461 else {
462 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000463 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000464 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000465 Lex.Lex();
466 return false;
467}
468
Dan Gohman466876b2009-08-12 23:32:33 +0000469/// ParseUnnamedGlobal:
470/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000471/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
472/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000473/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000474/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
475/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000476bool LLParser::ParseUnnamedGlobal() {
477 unsigned VarID = NumberedVals.size();
478 std::string Name;
479 LocTy NameLoc = Lex.getLoc();
480
481 // Handle the GlobalID form.
482 if (Lex.getKind() == lltok::GlobalID) {
483 if (Lex.getUIntVal() != VarID)
484 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000485 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000486 Lex.Lex(); // eat GlobalID;
487
488 if (ParseToken(lltok::equal, "expected '=' after name"))
489 return true;
490 }
491
492 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000493 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000494 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000495 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000496 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000497 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000498 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000499 ParseOptionalThreadLocal(TLM) ||
500 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000501 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000502
Rafael Espindola464fe022014-07-30 22:51:54 +0000503 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000504 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000505 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000506
507 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
508 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000509}
510
Chris Lattnerac161bf2009-01-02 07:01:27 +0000511/// ParseNamedGlobal:
512/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000513/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
514/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000515bool LLParser::ParseNamedGlobal() {
516 assert(Lex.getKind() == lltok::GlobalVar);
517 LocTy NameLoc = Lex.getLoc();
518 std::string Name = Lex.getStrVal();
519 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000520
Chris Lattnerac161bf2009-01-02 07:01:27 +0000521 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000522 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000523 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000524 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000525 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
526 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000527 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000528 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000529 ParseOptionalThreadLocal(TLM) ||
530 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000531 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000532
Rafael Espindola464fe022014-07-30 22:51:54 +0000533 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000534 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000535 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000536
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000537 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
538 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000539}
540
David Majnemerdad0a642014-06-27 18:19:56 +0000541bool LLParser::parseComdat() {
542 assert(Lex.getKind() == lltok::ComdatVar);
543 std::string Name = Lex.getStrVal();
544 LocTy NameLoc = Lex.getLoc();
545 Lex.Lex();
546
547 if (ParseToken(lltok::equal, "expected '=' here"))
548 return true;
549
550 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
551 return TokError("expected comdat type");
552
553 Comdat::SelectionKind SK;
554 switch (Lex.getKind()) {
555 default:
556 return TokError("unknown selection kind");
557 case lltok::kw_any:
558 SK = Comdat::Any;
559 break;
560 case lltok::kw_exactmatch:
561 SK = Comdat::ExactMatch;
562 break;
563 case lltok::kw_largest:
564 SK = Comdat::Largest;
565 break;
566 case lltok::kw_noduplicates:
567 SK = Comdat::NoDuplicates;
568 break;
569 case lltok::kw_samesize:
570 SK = Comdat::SameSize;
571 break;
572 }
573 Lex.Lex();
574
575 // See if the comdat was forward referenced, if so, use the comdat.
576 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
577 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
578 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
579 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
580
581 Comdat *C;
582 if (I != ComdatSymTab.end())
583 C = &I->second;
584 else
585 C = M->getOrInsertComdat(Name);
586 C->setSelectionKind(SK);
587
588 return false;
589}
590
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000591// MDString:
592// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000593bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000594 std::string Str;
595 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000596 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000597 return false;
598}
599
600// MDNode:
601// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000602bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000603 // !{ ..., !42, ... }
604 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000605 if (ParseUInt32(MID))
606 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000607
Chris Lattner8eff0152010-04-01 05:14:45 +0000608 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000609 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000610 Result = NumberedMetadata[MID];
611 return false;
612 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000613
Chris Lattner8eff0152010-04-01 05:14:45 +0000614 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000615 auto &FwdRef = ForwardRefMDNodes[MID];
616 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000617
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000618 Result = FwdRef.first.get();
619 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000620 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000621}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000622
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000623/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000624/// !foo = !{ !1, !2 }
625bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000626 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000627 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000628 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000629
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000630 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000631 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000632 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000633 return true;
634
Dan Gohman2637cc12010-07-21 23:38:33 +0000635 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000636 if (Lex.getKind() != lltok::rbrace)
637 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000638 if (ParseToken(lltok::exclaim, "Expected '!' here"))
639 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000640
Craig Topper2617dcc2014-04-15 06:32:26 +0000641 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000642 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000643 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000644 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000645
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000646 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000647}
648
Devang Patel39e64d42009-07-01 19:21:12 +0000649/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000650/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000651bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000652 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000653 Lex.Lex();
654 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000655
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000656 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000657 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000658 ParseToken(lltok::equal, "expected '=' here"))
659 return true;
660
661 // Detect common error, from old metadata syntax.
662 if (Lex.getKind() == lltok::Type)
663 return TokError("unexpected type in metadata definition");
664
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000665 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000666 if (Lex.getKind() == lltok::MetadataVar) {
667 if (ParseSpecializedMDNode(Init, IsDistinct))
668 return true;
669 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
670 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000671 return true;
672
Chris Lattnerfc58af22009-12-30 04:51:58 +0000673 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000674 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000675 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000676 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000677 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000678
Chris Lattnerfc58af22009-12-30 04:51:58 +0000679 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
680 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000681 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000682 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000683 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000684 }
685
Devang Patel39e64d42009-07-01 19:21:12 +0000686 return false;
687}
688
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000689static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
690 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
691 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
692}
693
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000694/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000695/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
696/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000697/// OptionalUnnamedAddr 'alias' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000698///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000699/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000700/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000701///
Eric Christopher536f0a92015-05-28 23:07:39 +0000702/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000703///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000704bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
705 unsigned L, unsigned Visibility,
706 unsigned DLLStorageClass,
707 GlobalVariable::ThreadLocalMode TLM,
708 bool UnnamedAddr) {
709 bool IsAlias;
710 if (Lex.getKind() == lltok::kw_alias)
711 IsAlias = true;
712 else
713 llvm_unreachable("Not an alias!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000714 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000715
Rafael Espindola78527052013-10-06 15:10:43 +0000716 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
717
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000718 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000719 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000720
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000721 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000722 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000723 "symbol with local linkage must have default visibility");
724
David Blaikie2f408302015-09-11 03:22:04 +0000725 Type *Ty;
726 LocTy ExplicitTypeLoc = Lex.getLoc();
727 if (ParseType(Ty) ||
728 ParseToken(lltok::comma, "expected comma after alias's type"))
729 return true;
730
Rafael Espindola64c1e182014-06-03 02:41:57 +0000731 Constant *Aliasee;
732 LocTy AliaseeLoc = Lex.getLoc();
733 if (Lex.getKind() != lltok::kw_bitcast &&
734 Lex.getKind() != lltok::kw_getelementptr &&
735 Lex.getKind() != lltok::kw_addrspacecast &&
736 Lex.getKind() != lltok::kw_inttoptr) {
737 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000738 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000739 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000740 // The bitcast dest type is not present, it is implied by the dest type.
741 ValID ID;
742 if (ParseValID(ID))
743 return true;
744 if (ID.Kind != ValID::t_Constant)
745 return Error(AliaseeLoc, "invalid aliasee");
746 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000747 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000748
Rafael Espindola64c1e182014-06-03 02:41:57 +0000749 Type *AliaseeType = Aliasee->getType();
750 auto *PTy = dyn_cast<PointerType>(AliaseeType);
751 if (!PTy)
752 return Error(AliaseeLoc, "An alias must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000753 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000754
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000755 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000756 return Error(
757 ExplicitTypeLoc,
758 "explicit pointee type doesn't match operand's pointee type");
759
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000760 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
761 return Error(
762 ExplicitTypeLoc,
763 "explicit pointee type should be a function type");
764
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000765 GlobalValue *GVal = nullptr;
766
767 // See if the alias was forward referenced, if so, prepare to replace the
768 // forward reference.
769 if (!Name.empty()) {
770 GVal = M->getNamedValue(Name);
771 if (GVal) {
772 if (!ForwardRefVals.erase(Name))
773 return Error(NameLoc, "redefinition of global '@" + Name + "'");
774 }
775 } else {
776 auto I = ForwardRefValIDs.find(NumberedVals.size());
777 if (I != ForwardRefValIDs.end()) {
778 GVal = I->second.first;
779 ForwardRefValIDs.erase(I);
780 }
781 }
782
Chris Lattnerac161bf2009-01-02 07:01:27 +0000783 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000784 std::unique_ptr<GlobalIndirectSymbol> GA;
785 if (IsAlias)
786 GA.reset(GlobalAlias::create(Ty, AddrSpace,
787 (GlobalValue::LinkageTypes)Linkage, Name,
788 Aliasee, /*Parent*/ nullptr));
789 else
790 llvm_unreachable("Not an alias!");
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000791 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000792 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000793 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000794 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000795
Rafael Espindola54fc2982015-06-17 17:53:31 +0000796 if (Name.empty())
797 NumberedVals.push_back(GA.get());
798
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000799 if (GVal) {
800 // Verify that types agree.
801 if (GVal->getType() != GA->getType())
802 return Error(
803 ExplicitTypeLoc,
804 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000805
Chris Lattnerac161bf2009-01-02 07:01:27 +0000806 // If they agree, just RAUW the old value with the alias and remove the
807 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000808 GVal->replaceAllUsesWith(GA.get());
809 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000810 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000811
Chris Lattnerac161bf2009-01-02 07:01:27 +0000812 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000813 if (IsAlias)
814 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
815 else
816 llvm_unreachable("Not an alias!");
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000817 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000818
Rafael Espindolaaa273822014-05-09 21:49:17 +0000819 // The module owns this now
820 GA.release();
821
Chris Lattnerac161bf2009-01-02 07:01:27 +0000822 return false;
823}
824
825/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000826/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000827/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000828/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000829/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000830/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000831/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000832///
Eric Christopher536f0a92015-05-28 23:07:39 +0000833/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000834/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000835///
836bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
837 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000838 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000839 GlobalVariable::ThreadLocalMode TLM,
840 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000841 if (!isValidVisibilityForLinkage(Visibility, Linkage))
842 return Error(NameLoc,
843 "symbol with local linkage must have default visibility");
844
Chris Lattnerac161bf2009-01-02 07:01:27 +0000845 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000846 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000847 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000848 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000849
Craig Topper2617dcc2014-04-15 06:32:26 +0000850 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000851 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000852 ParseOptionalToken(lltok::kw_externally_initialized,
853 IsExternallyInitialized,
854 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000855 ParseGlobalType(IsConstant) ||
856 ParseType(Ty, TyLoc))
857 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000858
Chris Lattnerac161bf2009-01-02 07:01:27 +0000859 // If the linkage is specified and is external, then no initializer is
860 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000861 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000862 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000863 Linkage != GlobalValue::ExternalLinkage)) {
864 if (ParseGlobalValue(Ty, Init))
865 return true;
866 }
867
David Majnemer49b3d9b2015-02-16 08:41:08 +0000868 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000869 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000870
David Majnemer598bd052014-12-09 05:56:09 +0000871 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000872
873 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000874 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000875 GVal = M->getNamedValue(Name);
876 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000877 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000878 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000879 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000880 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000881 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000882 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000883 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000884 ForwardRefValIDs.erase(I);
885 }
886 }
887
David Majnemer598bd052014-12-09 05:56:09 +0000888 GlobalVariable *GV;
889 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000890 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
891 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000892 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000893 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000894 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000895 return Error(TyLoc,
896 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000897
David Majnemer598bd052014-12-09 05:56:09 +0000898 GV = cast<GlobalVariable>(GVal);
899
Chris Lattnerac161bf2009-01-02 07:01:27 +0000900 // Move the forward-reference to the correct spot in the module.
901 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
902 }
903
904 if (Name.empty())
905 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000906
Chris Lattnerac161bf2009-01-02 07:01:27 +0000907 // Set the parsed properties on the global.
908 if (Init)
909 GV->setInitializer(Init);
910 GV->setConstant(IsConstant);
911 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
912 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000913 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000914 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000915 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000916 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000917
Chris Lattnerac161bf2009-01-02 07:01:27 +0000918 // Parse attributes on the global.
919 while (Lex.getKind() == lltok::comma) {
920 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000921
Chris Lattnerac161bf2009-01-02 07:01:27 +0000922 if (Lex.getKind() == lltok::kw_section) {
923 Lex.Lex();
924 GV->setSection(Lex.getStrVal());
925 if (ParseToken(lltok::StringConstant, "expected global section string"))
926 return true;
927 } else if (Lex.getKind() == lltok::kw_align) {
928 unsigned Alignment;
929 if (ParseOptionalAlignment(Alignment)) return true;
930 GV->setAlignment(Alignment);
931 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000932 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000933 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000934 return true;
935 if (C)
936 GV->setComdat(C);
937 else
938 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000939 }
940 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000941
Chris Lattnerac161bf2009-01-02 07:01:27 +0000942 return false;
943}
944
Bill Wendling63b88192013-02-06 06:52:58 +0000945/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000946/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000947bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000948 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000949 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000950 Lex.Lex();
951
David Majnemerb39e22b2014-12-09 18:33:57 +0000952 if (Lex.getKind() != lltok::AttrGrpID)
953 return TokError("expected attribute group id");
954
Bill Wendling63b88192013-02-06 06:52:58 +0000955 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000956 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000957 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000958 Lex.Lex();
959
960 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000961 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000962 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000963 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000964 ParseToken(lltok::rbrace, "expected end of attribute group"))
965 return true;
966
Bill Wendlingb32b0412013-02-08 06:32:06 +0000967 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000968 return Error(AttrGrpLoc, "attribute group has no attributes");
969
970 return false;
971}
972
Bill Wendling8b0321d2013-02-08 00:52:31 +0000973/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000974/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000975bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
976 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000977 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000978 bool HaveError = false;
979
980 B.clear();
981
Bill Wendling63b88192013-02-06 06:52:58 +0000982 while (true) {
983 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000984 if (Token == lltok::kw_builtin)
985 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000986 switch (Token) {
987 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000988 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000989 return Error(Lex.getLoc(), "unterminated attribute group");
990 case lltok::rbrace:
991 // Finished.
992 return false;
993
Bill Wendlingb32b0412013-02-08 06:32:06 +0000994 case lltok::AttrGrpID: {
995 // Allow a function to reference an attribute group:
996 //
997 // define void @foo() #1 { ... }
998 if (inAttrGrp)
999 HaveError |=
1000 Error(Lex.getLoc(),
1001 "cannot have an attribute group reference in an attribute group");
1002
1003 unsigned AttrGrpNum = Lex.getUIntVal();
1004 if (inAttrGrp) break;
1005
1006 // Save the reference to the attribute group. We'll fill it in later.
1007 FwdRefAttrGrps.push_back(AttrGrpNum);
1008 break;
1009 }
Bill Wendling63b88192013-02-06 06:52:58 +00001010 // Target-dependent attributes:
1011 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001012 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001013 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001014 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001015 }
1016
1017 // Target-independent attributes:
1018 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001019 // As a hack, we allow function alignment to be initially parsed as an
1020 // attribute on a function declaration/definition or added to an attribute
1021 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001022 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001023 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001024 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001025 if (ParseToken(lltok::equal, "expected '=' here") ||
1026 ParseUInt32(Alignment))
1027 return true;
1028 } else {
1029 if (ParseOptionalAlignment(Alignment))
1030 return true;
1031 }
Bill Wendling63b88192013-02-06 06:52:58 +00001032 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001033 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001034 }
1035 case lltok::kw_alignstack: {
1036 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001037 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001038 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001039 if (ParseToken(lltok::equal, "expected '=' here") ||
1040 ParseUInt32(Alignment))
1041 return true;
1042 } else {
1043 if (ParseOptionalStackAlignment(Alignment))
1044 return true;
1045 }
Bill Wendling63b88192013-02-06 06:52:58 +00001046 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001047 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001048 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001049 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1050 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1051 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1052 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1053 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001054 case lltok::kw_inaccessiblememonly:
1055 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1056 case lltok::kw_inaccessiblemem_or_argmemonly:
1057 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001058 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1059 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1060 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1061 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1062 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1063 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1064 case lltok::kw_noimplicitfloat:
1065 B.addAttribute(Attribute::NoImplicitFloat); break;
1066 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1067 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1068 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1069 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001070 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001071 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1072 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1073 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1074 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1075 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1076 case lltok::kw_returns_twice:
1077 B.addAttribute(Attribute::ReturnsTwice); break;
1078 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1079 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1080 case lltok::kw_sspstrong:
1081 B.addAttribute(Attribute::StackProtectStrong); break;
1082 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1083 case lltok::kw_sanitize_address:
1084 B.addAttribute(Attribute::SanitizeAddress); break;
1085 case lltok::kw_sanitize_thread:
1086 B.addAttribute(Attribute::SanitizeThread); break;
1087 case lltok::kw_sanitize_memory:
1088 B.addAttribute(Attribute::SanitizeMemory); break;
1089 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001090
1091 // Error handling.
1092 case lltok::kw_inreg:
1093 case lltok::kw_signext:
1094 case lltok::kw_zeroext:
1095 HaveError |=
1096 Error(Lex.getLoc(),
1097 "invalid use of attribute on a function");
1098 break;
1099 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001100 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001101 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001102 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001103 case lltok::kw_nest:
1104 case lltok::kw_noalias:
1105 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001106 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001107 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001108 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001109 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001110 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001111 HaveError |=
1112 Error(Lex.getLoc(),
1113 "invalid use of parameter-only attribute on a function");
1114 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001115 }
1116
1117 Lex.Lex();
1118 }
1119}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001120
1121//===----------------------------------------------------------------------===//
1122// GlobalValue Reference/Resolution Routines.
1123//===----------------------------------------------------------------------===//
1124
Karl Schimpf77729782015-09-03 18:06:44 +00001125static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1126 const std::string &Name) {
1127 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1128 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1129 else
1130 return new GlobalVariable(*M, PTy->getElementType(), false,
1131 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1132 nullptr, GlobalVariable::NotThreadLocal,
1133 PTy->getAddressSpace());
1134}
1135
Chris Lattnerac161bf2009-01-02 07:01:27 +00001136/// GetGlobalVal - Get a value with the specified name or ID, creating a
1137/// forward reference record if needed. This can return null if the value
1138/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001139GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001140 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001141 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001142 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001143 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001144 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001145 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001146
Chris Lattnerac161bf2009-01-02 07:01:27 +00001147 // Look this name up in the normal function symbol table.
1148 GlobalValue *Val =
1149 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001150
Chris Lattnerac161bf2009-01-02 07:01:27 +00001151 // If this is a forward reference for the value, see if we already created a
1152 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001153 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001154 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001155 if (I != ForwardRefVals.end())
1156 Val = I->second.first;
1157 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001158
Chris Lattnerac161bf2009-01-02 07:01:27 +00001159 // If we have the value in the symbol table or fwd-ref table, return it.
1160 if (Val) {
1161 if (Val->getType() == Ty) return Val;
1162 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001163 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001164 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001165 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001166
Chris Lattnerac161bf2009-01-02 07:01:27 +00001167 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001168 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001169 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1170 return FwdVal;
1171}
1172
Chris Lattner229907c2011-07-18 04:54:35 +00001173GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1174 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001175 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001176 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001177 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001178 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001179
Craig Topper2617dcc2014-04-15 06:32:26 +00001180 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001181
Chris Lattnerac161bf2009-01-02 07:01:27 +00001182 // If this is a forward reference for the value, see if we already created a
1183 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001184 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001185 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001186 if (I != ForwardRefValIDs.end())
1187 Val = I->second.first;
1188 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001189
Chris Lattnerac161bf2009-01-02 07:01:27 +00001190 // If we have the value in the symbol table or fwd-ref table, return it.
1191 if (Val) {
1192 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001193 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001194 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001195 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001196 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001197
Chris Lattnerac161bf2009-01-02 07:01:27 +00001198 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001199 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001200 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1201 return FwdVal;
1202}
1203
1204
1205//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001206// Comdat Reference/Resolution Routines.
1207//===----------------------------------------------------------------------===//
1208
1209Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1210 // Look this name up in the comdat symbol table.
1211 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1212 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1213 if (I != ComdatSymTab.end())
1214 return &I->second;
1215
1216 // Otherwise, create a new forward reference for this value and remember it.
1217 Comdat *C = M->getOrInsertComdat(Name);
1218 ForwardRefComdats[Name] = Loc;
1219 return C;
1220}
1221
1222
1223//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001224// Helper Routines.
1225//===----------------------------------------------------------------------===//
1226
1227/// ParseToken - If the current token has the specified kind, eat it and return
1228/// success. Otherwise, emit the specified error and return failure.
1229bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1230 if (Lex.getKind() != T)
1231 return TokError(ErrMsg);
1232 Lex.Lex();
1233 return false;
1234}
1235
Chris Lattner3822f632009-01-02 08:05:26 +00001236/// ParseStringConstant
1237/// ::= StringConstant
1238bool LLParser::ParseStringConstant(std::string &Result) {
1239 if (Lex.getKind() != lltok::StringConstant)
1240 return TokError("expected string constant");
1241 Result = Lex.getStrVal();
1242 Lex.Lex();
1243 return false;
1244}
1245
1246/// ParseUInt32
1247/// ::= uint32
1248bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001249 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1250 return TokError("expected integer");
1251 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1252 if (Val64 != unsigned(Val64))
1253 return TokError("expected 32-bit integer (too large)");
1254 Val = Val64;
1255 Lex.Lex();
1256 return false;
1257}
1258
Hal Finkelb0407ba2014-07-18 15:51:28 +00001259/// ParseUInt64
1260/// ::= uint64
1261bool LLParser::ParseUInt64(uint64_t &Val) {
1262 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1263 return TokError("expected integer");
1264 Val = Lex.getAPSIntVal().getLimitedValue();
1265 Lex.Lex();
1266 return false;
1267}
1268
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001269/// ParseTLSModel
1270/// := 'localdynamic'
1271/// := 'initialexec'
1272/// := 'localexec'
1273bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1274 switch (Lex.getKind()) {
1275 default:
1276 return TokError("expected localdynamic, initialexec or localexec");
1277 case lltok::kw_localdynamic:
1278 TLM = GlobalVariable::LocalDynamicTLSModel;
1279 break;
1280 case lltok::kw_initialexec:
1281 TLM = GlobalVariable::InitialExecTLSModel;
1282 break;
1283 case lltok::kw_localexec:
1284 TLM = GlobalVariable::LocalExecTLSModel;
1285 break;
1286 }
1287
1288 Lex.Lex();
1289 return false;
1290}
1291
1292/// ParseOptionalThreadLocal
1293/// := /*empty*/
1294/// := 'thread_local'
1295/// := 'thread_local' '(' tlsmodel ')'
1296bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1297 TLM = GlobalVariable::NotThreadLocal;
1298 if (!EatIfPresent(lltok::kw_thread_local))
1299 return false;
1300
1301 TLM = GlobalVariable::GeneralDynamicTLSModel;
1302 if (Lex.getKind() == lltok::lparen) {
1303 Lex.Lex();
1304 return ParseTLSModel(TLM) ||
1305 ParseToken(lltok::rparen, "expected ')' after thread local model");
1306 }
1307 return false;
1308}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001309
1310/// ParseOptionalAddrSpace
1311/// := /*empty*/
1312/// := 'addrspace' '(' uint32 ')'
1313bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1314 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001315 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001316 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001317 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001318 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001319 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001320}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001321
Artur Pilipenko17376c42015-08-03 14:31:49 +00001322/// ParseStringAttribute
1323/// := StringConstant
1324/// := StringConstant '=' StringConstant
1325bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1326 std::string Attr = Lex.getStrVal();
1327 Lex.Lex();
1328 std::string Val;
1329 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1330 return true;
1331 B.addAttribute(Attr, Val);
1332 return false;
1333}
1334
Bill Wendling34c2eb22012-12-04 23:40:58 +00001335/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1336bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1337 bool HaveError = false;
1338
1339 B.clear();
1340
1341 while (1) {
1342 lltok::Kind Token = Lex.getKind();
1343 switch (Token) {
1344 default: // End of attributes.
1345 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001346 case lltok::StringConstant: {
1347 if (ParseStringAttribute(B))
1348 return true;
1349 continue;
1350 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001351 case lltok::kw_align: {
1352 unsigned Alignment;
1353 if (ParseOptionalAlignment(Alignment))
1354 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001355 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001356 continue;
1357 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001358 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001359 case lltok::kw_dereferenceable: {
1360 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001361 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001362 return true;
1363 B.addDereferenceableAttr(Bytes);
1364 continue;
1365 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001366 case lltok::kw_dereferenceable_or_null: {
1367 uint64_t Bytes;
1368 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1369 return true;
1370 B.addDereferenceableOrNullAttr(Bytes);
1371 continue;
1372 }
Reid Klecknera534a382013-12-19 02:14:12 +00001373 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001374 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1375 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1376 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1377 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001378 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001379 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1380 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001381 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001382 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1383 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001384 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001385 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001386 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001387
Stephen Lin7577ed52013-04-20 13:16:13 +00001388 case lltok::kw_alignstack:
1389 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001390 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001391 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001392 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001393 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001394 case lltok::kw_minsize:
1395 case lltok::kw_naked:
1396 case lltok::kw_nobuiltin:
1397 case lltok::kw_noduplicate:
1398 case lltok::kw_noimplicitfloat:
1399 case lltok::kw_noinline:
1400 case lltok::kw_nonlazybind:
1401 case lltok::kw_noredzone:
1402 case lltok::kw_noreturn:
1403 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001404 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001405 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001406 case lltok::kw_returns_twice:
1407 case lltok::kw_sanitize_address:
1408 case lltok::kw_sanitize_memory:
1409 case lltok::kw_sanitize_thread:
1410 case lltok::kw_ssp:
1411 case lltok::kw_sspreq:
1412 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001413 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001414 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001415 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1416 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001417 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001418
Bill Wendling34c2eb22012-12-04 23:40:58 +00001419 Lex.Lex();
1420 }
1421}
1422
1423/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1424bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1425 bool HaveError = false;
1426
1427 B.clear();
1428
1429 while (1) {
1430 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001431 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001432 default: // End of attributes.
1433 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001434 case lltok::StringConstant: {
1435 if (ParseStringAttribute(B))
1436 return true;
1437 continue;
1438 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001439 case lltok::kw_dereferenceable: {
1440 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001441 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001442 return true;
1443 B.addDereferenceableAttr(Bytes);
1444 continue;
1445 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001446 case lltok::kw_dereferenceable_or_null: {
1447 uint64_t Bytes;
1448 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1449 return true;
1450 B.addDereferenceableOrNullAttr(Bytes);
1451 continue;
1452 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001453 case lltok::kw_align: {
1454 unsigned Alignment;
1455 if (ParseOptionalAlignment(Alignment))
1456 return true;
1457 B.addAlignmentAttr(Alignment);
1458 continue;
1459 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001460 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1461 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001462 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001463 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1464 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001465
Bill Wendling34c2eb22012-12-04 23:40:58 +00001466 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001467 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001468 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001469 case lltok::kw_nest:
1470 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001471 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001472 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001473 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001474 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001475 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001476 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001477
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001478 case lltok::kw_alignstack:
1479 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001480 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001481 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001482 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001483 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001484 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001485 case lltok::kw_minsize:
1486 case lltok::kw_naked:
1487 case lltok::kw_nobuiltin:
1488 case lltok::kw_noduplicate:
1489 case lltok::kw_noimplicitfloat:
1490 case lltok::kw_noinline:
1491 case lltok::kw_nonlazybind:
1492 case lltok::kw_noredzone:
1493 case lltok::kw_noreturn:
1494 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001495 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001496 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001497 case lltok::kw_returns_twice:
1498 case lltok::kw_sanitize_address:
1499 case lltok::kw_sanitize_memory:
1500 case lltok::kw_sanitize_thread:
1501 case lltok::kw_ssp:
1502 case lltok::kw_sspreq:
1503 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001504 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001505 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001506 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001507 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001508
1509 case lltok::kw_readnone:
1510 case lltok::kw_readonly:
1511 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001512 }
1513
Chris Lattnerac161bf2009-01-02 07:01:27 +00001514 Lex.Lex();
1515 }
1516}
1517
1518/// ParseOptionalLinkage
1519/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001520/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001521/// ::= 'internal'
1522/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001523/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001524/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001525/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001526/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001527/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001528/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001529/// ::= 'extern_weak'
1530/// ::= 'external'
1531bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1532 HasLinkage = false;
1533 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001534 default: Res=GlobalValue::ExternalLinkage; return false;
1535 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001536 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1537 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1538 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1539 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1540 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001541 case lltok::kw_available_externally:
1542 Res = GlobalValue::AvailableExternallyLinkage;
1543 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001544 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001545 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001546 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1547 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001548 }
1549 Lex.Lex();
1550 HasLinkage = true;
1551 return false;
1552}
1553
1554/// ParseOptionalVisibility
1555/// ::= /*empty*/
1556/// ::= 'default'
1557/// ::= 'hidden'
1558/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001559///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001560bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1561 switch (Lex.getKind()) {
1562 default: Res = GlobalValue::DefaultVisibility; return false;
1563 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1564 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1565 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1566 }
1567 Lex.Lex();
1568 return false;
1569}
1570
Nico Rieck7157bb72014-01-14 15:22:47 +00001571/// ParseOptionalDLLStorageClass
1572/// ::= /*empty*/
1573/// ::= 'dllimport'
1574/// ::= 'dllexport'
1575///
1576bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1577 switch (Lex.getKind()) {
1578 default: Res = GlobalValue::DefaultStorageClass; return false;
1579 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1580 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1581 }
1582 Lex.Lex();
1583 return false;
1584}
1585
Chris Lattnerac161bf2009-01-02 07:01:27 +00001586/// ParseOptionalCallingConv
1587/// ::= /*empty*/
1588/// ::= 'ccc'
1589/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001590/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001591/// ::= 'coldcc'
1592/// ::= 'x86_stdcallcc'
1593/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001594/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001595/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001596/// ::= 'arm_apcscc'
1597/// ::= 'arm_aapcscc'
1598/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001599/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001600/// ::= 'avr_intrcc'
1601/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001602/// ::= 'ptx_kernel'
1603/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001604/// ::= 'spir_func'
1605/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001606/// ::= 'x86_64_sysvcc'
1607/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001608/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001609/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001610/// ::= 'preserve_mostcc'
1611/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001612/// ::= 'ghccc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001613/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001614/// ::= 'hhvmcc'
1615/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001616/// ::= 'cxx_fast_tlscc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001617/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001618///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001619bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001620 switch (Lex.getKind()) {
1621 default: CC = CallingConv::C; return false;
1622 case lltok::kw_ccc: CC = CallingConv::C; break;
1623 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1624 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1625 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1626 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001627 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001628 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001629 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1630 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1631 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001632 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001633 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1634 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001635 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1636 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001637 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1638 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001639 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001640 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1641 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001642 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001643 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001644 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1645 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001646 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001647 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001648 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1649 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001650 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001651 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001652 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001653 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001654 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001655 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001656
Chris Lattnerac161bf2009-01-02 07:01:27 +00001657 Lex.Lex();
1658 return false;
1659}
1660
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001661/// ParseMetadataAttachment
1662/// ::= !dbg !42
1663bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1664 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1665
1666 std::string Name = Lex.getStrVal();
1667 Kind = M->getMDKindID(Name);
1668 Lex.Lex();
1669
1670 return ParseMDNode(MD);
1671}
1672
Chris Lattner5c427632009-12-30 05:31:19 +00001673/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001674/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001675bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001676 do {
1677 if (Lex.getKind() != lltok::MetadataVar)
1678 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001679
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001680 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001681 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001682 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001683 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001684
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001685 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001686 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001687 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001688
Chris Lattner596760d2009-12-29 21:25:40 +00001689 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001690 } while (EatIfPresent(lltok::comma));
1691 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001692}
1693
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001694/// ParseOptionalFunctionMetadata
1695/// ::= (!dbg !57)*
1696bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1697 while (Lex.getKind() == lltok::MetadataVar) {
1698 unsigned MDK;
1699 MDNode *N;
1700 if (ParseMetadataAttachment(MDK, N))
1701 return true;
1702
1703 F.setMetadata(MDK, N);
1704 }
1705 return false;
1706}
1707
Chris Lattnerac161bf2009-01-02 07:01:27 +00001708/// ParseOptionalAlignment
1709/// ::= /* empty */
1710/// ::= 'align' 4
1711bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1712 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001713 if (!EatIfPresent(lltok::kw_align))
1714 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001715 LocTy AlignLoc = Lex.getLoc();
1716 if (ParseUInt32(Alignment)) return true;
1717 if (!isPowerOf2_32(Alignment))
1718 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001719 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001720 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001721 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001722}
1723
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001724/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001725/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001726/// ::= AttrKind '(' 4 ')'
1727///
1728/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1729bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1730 uint64_t &Bytes) {
1731 assert((AttrKind == lltok::kw_dereferenceable ||
1732 AttrKind == lltok::kw_dereferenceable_or_null) &&
1733 "contract!");
1734
Hal Finkelb0407ba2014-07-18 15:51:28 +00001735 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001736 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001737 return false;
1738 LocTy ParenLoc = Lex.getLoc();
1739 if (!EatIfPresent(lltok::lparen))
1740 return Error(ParenLoc, "expected '('");
1741 LocTy DerefLoc = Lex.getLoc();
1742 if (ParseUInt64(Bytes)) return true;
1743 ParenLoc = Lex.getLoc();
1744 if (!EatIfPresent(lltok::rparen))
1745 return Error(ParenLoc, "expected ')'");
1746 if (!Bytes)
1747 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1748 return false;
1749}
1750
Chris Lattnerb2f39502009-12-30 05:44:30 +00001751/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001752/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001753/// ::= ',' align 4
1754///
1755/// This returns with AteExtraComma set to true if it ate an excess comma at the
1756/// end.
1757bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1758 bool &AteExtraComma) {
1759 AteExtraComma = false;
1760 while (EatIfPresent(lltok::comma)) {
1761 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001762 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001763 AteExtraComma = true;
1764 return false;
1765 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001766
Chris Lattner95b0ff42010-04-23 00:50:50 +00001767 if (Lex.getKind() != lltok::kw_align)
1768 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001769
Chris Lattner95b0ff42010-04-23 00:50:50 +00001770 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001771 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001772
Devang Patelea8a4b92009-09-17 23:04:48 +00001773 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001774}
1775
Eli Friedmanfee02c62011-07-25 23:16:38 +00001776/// ParseScopeAndOrdering
1777/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1778/// else: ::=
1779///
1780/// This sets Scope and Ordering to the parsed values.
1781bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1782 AtomicOrdering &Ordering) {
1783 if (!isAtomic)
1784 return false;
1785
1786 Scope = CrossThread;
1787 if (EatIfPresent(lltok::kw_singlethread))
1788 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001789
1790 return ParseOrdering(Ordering);
1791}
1792
1793/// ParseOrdering
1794/// ::= AtomicOrdering
1795///
1796/// This sets Ordering to the parsed value.
1797bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001798 switch (Lex.getKind()) {
1799 default: return TokError("Expected ordering on atomic instruction");
1800 case lltok::kw_unordered: Ordering = Unordered; break;
1801 case lltok::kw_monotonic: Ordering = Monotonic; break;
1802 case lltok::kw_acquire: Ordering = Acquire; break;
1803 case lltok::kw_release: Ordering = Release; break;
1804 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1805 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1806 }
1807 Lex.Lex();
1808 return false;
1809}
1810
Charles Davisbe5557e2010-02-12 00:31:15 +00001811/// ParseOptionalStackAlignment
1812/// ::= /* empty */
1813/// ::= 'alignstack' '(' 4 ')'
1814bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1815 Alignment = 0;
1816 if (!EatIfPresent(lltok::kw_alignstack))
1817 return false;
1818 LocTy ParenLoc = Lex.getLoc();
1819 if (!EatIfPresent(lltok::lparen))
1820 return Error(ParenLoc, "expected '('");
1821 LocTy AlignLoc = Lex.getLoc();
1822 if (ParseUInt32(Alignment)) return true;
1823 ParenLoc = Lex.getLoc();
1824 if (!EatIfPresent(lltok::rparen))
1825 return Error(ParenLoc, "expected ')'");
1826 if (!isPowerOf2_32(Alignment))
1827 return Error(AlignLoc, "stack alignment is not a power of two");
1828 return false;
1829}
Devang Patelea8a4b92009-09-17 23:04:48 +00001830
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001831/// ParseIndexList - This parses the index list for an insert/extractvalue
1832/// instruction. This sets AteExtraComma in the case where we eat an extra
1833/// comma at the end of the line and find that it is followed by metadata.
1834/// Clients that don't allow metadata can call the version of this function that
1835/// only takes one argument.
1836///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001837/// ParseIndexList
1838/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001839///
1840bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1841 bool &AteExtraComma) {
1842 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001843
Chris Lattnerac161bf2009-01-02 07:01:27 +00001844 if (Lex.getKind() != lltok::comma)
1845 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001846
Chris Lattner3822f632009-01-02 08:05:26 +00001847 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001848 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001849 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001850 AteExtraComma = true;
1851 return false;
1852 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001853 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001854 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001855 Indices.push_back(Idx);
1856 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001857
Chris Lattnerac161bf2009-01-02 07:01:27 +00001858 return false;
1859}
1860
1861//===----------------------------------------------------------------------===//
1862// Type Parsing.
1863//===----------------------------------------------------------------------===//
1864
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001865/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001866bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001867 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001868 switch (Lex.getKind()) {
1869 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001870 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001871 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001872 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001873 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001874 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001875 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001876 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001877 // Type ::= StructType
1878 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001879 return true;
1880 break;
1881 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001882 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001883 Lex.Lex(); // eat the lsquare.
1884 if (ParseArrayVectorType(Result, false))
1885 return true;
1886 break;
1887 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001888 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001889 Lex.Lex();
1890 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001891 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001892 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001893 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001894 } else if (ParseArrayVectorType(Result, true))
1895 return true;
1896 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001897 case lltok::LocalVar: {
1898 // Type ::= %foo
1899 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001900
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001901 // If the type hasn't been defined yet, create a forward definition and
1902 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001903 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001904 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001905 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001906 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001907 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001908 Lex.Lex();
1909 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001910 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001911
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001912 case lltok::LocalVarID: {
1913 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001914 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001915
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001916 // If the type hasn't been defined yet, create a forward definition and
1917 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001918 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001919 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001920 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001921 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001922 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001923 Lex.Lex();
1924 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001925 }
1926 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001927
1928 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001929 while (1) {
1930 switch (Lex.getKind()) {
1931 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001932 default:
1933 if (!AllowVoid && Result->isVoidTy())
1934 return Error(TypeLoc, "void type only allowed for function results");
1935 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001936
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001937 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001938 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001939 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001940 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001941 if (Result->isVoidTy())
1942 return TokError("pointers to void are invalid - use i8* instead");
1943 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001944 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001945 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001946 Lex.Lex();
1947 break;
1948
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001949 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001950 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001951 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001952 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001953 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001954 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001955 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001956 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001957 unsigned AddrSpace;
1958 if (ParseOptionalAddrSpace(AddrSpace) ||
1959 ParseToken(lltok::star, "expected '*' in address space"))
1960 return true;
1961
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001962 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001963 break;
1964 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001965
Chris Lattnerac161bf2009-01-02 07:01:27 +00001966 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1967 case lltok::lparen:
1968 if (ParseFunctionType(Result))
1969 return true;
1970 break;
1971 }
1972 }
1973}
1974
1975/// ParseParameterList
1976/// ::= '(' ')'
1977/// ::= '(' Arg (',' Arg)* ')'
1978/// Arg
1979/// ::= Type OptionalAttributes Value OptionalAttributes
1980bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001981 PerFunctionState &PFS, bool IsMustTailCall,
1982 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001983 if (ParseToken(lltok::lparen, "expected '(' in call"))
1984 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001985
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001986 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001987 while (Lex.getKind() != lltok::rparen) {
1988 // If this isn't the first argument, we need a comma.
1989 if (!ArgList.empty() &&
1990 ParseToken(lltok::comma, "expected ',' in argument list"))
1991 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001992
Reid Kleckner83498642014-08-26 00:33:28 +00001993 // Parse an ellipsis if this is a musttail call in a variadic function.
1994 if (Lex.getKind() == lltok::dotdotdot) {
1995 const char *Msg = "unexpected ellipsis in argument list for ";
1996 if (!IsMustTailCall)
1997 return TokError(Twine(Msg) + "non-musttail call");
1998 if (!InVarArgsFunc)
1999 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2000 Lex.Lex(); // Lex the '...', it is purely for readability.
2001 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2002 }
2003
Chris Lattnerac161bf2009-01-02 07:01:27 +00002004 // Parse the argument.
2005 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002006 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002007 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002008 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002009 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002010 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002011
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002012 if (ArgTy->isMetadataTy()) {
2013 if (ParseMetadataAsValue(V, PFS))
2014 return true;
2015 } else {
2016 // Otherwise, handle normal operands.
2017 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2018 return true;
2019 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002020 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
2021 AttrIndex++,
2022 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002023 }
2024
Reid Kleckner83498642014-08-26 00:33:28 +00002025 if (IsMustTailCall && InVarArgsFunc)
2026 return TokError("expected '...' at end of argument list for musttail call "
2027 "in varargs function");
2028
Chris Lattnerac161bf2009-01-02 07:01:27 +00002029 Lex.Lex(); // Lex the ')'.
2030 return false;
2031}
2032
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002033/// ParseOptionalOperandBundles
2034/// ::= /*empty*/
2035/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2036///
2037/// OperandBundle
2038/// ::= bundle-tag '(' ')'
2039/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2040///
2041/// bundle-tag ::= String Constant
2042bool LLParser::ParseOptionalOperandBundles(
2043 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2044 LocTy BeginLoc = Lex.getLoc();
2045 if (!EatIfPresent(lltok::lsquare))
2046 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002047
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002048 while (Lex.getKind() != lltok::rsquare) {
2049 // If this isn't the first operand bundle, we need a comma.
2050 if (!BundleList.empty() &&
2051 ParseToken(lltok::comma, "expected ',' in input list"))
2052 return true;
2053
2054 std::string Tag;
2055 if (ParseStringConstant(Tag))
2056 return true;
2057
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002058 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2059 return true;
2060
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002061 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002062 while (Lex.getKind() != lltok::rparen) {
2063 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002064 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002065 ParseToken(lltok::comma, "expected ',' in input list"))
2066 return true;
2067
2068 Type *Ty = nullptr;
2069 Value *Input = nullptr;
2070 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2071 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002072 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002073 }
2074
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002075 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2076
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002077 Lex.Lex(); // Lex the ')'.
2078 }
2079
2080 if (BundleList.empty())
2081 return Error(BeginLoc, "operand bundle set must not be empty");
2082
2083 Lex.Lex(); // Lex the ']'.
2084 return false;
2085}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002086
Chris Lattner2ed06b42009-01-05 18:34:07 +00002087/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002088/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002089/// ::= '(' ArgTypeListI ')'
2090/// ArgTypeListI
2091/// ::= /*empty*/
2092/// ::= '...'
2093/// ::= ArgTypeList ',' '...'
2094/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002095///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002096bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2097 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002098 isVarArg = false;
2099 assert(Lex.getKind() == lltok::lparen);
2100 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002101
Chris Lattnerac161bf2009-01-02 07:01:27 +00002102 if (Lex.getKind() == lltok::rparen) {
2103 // empty
2104 } else if (Lex.getKind() == lltok::dotdotdot) {
2105 isVarArg = true;
2106 Lex.Lex();
2107 } else {
2108 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002109 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002110 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002111 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002112
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002113 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002114 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002115
Chris Lattnerfdd87902009-10-05 05:54:46 +00002116 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002117 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002118
Chris Lattnerdef19492011-06-17 06:36:20 +00002119 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002120 Name = Lex.getStrVal();
2121 Lex.Lex();
2122 }
Chris Lattner3822f632009-01-02 08:05:26 +00002123
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002124 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002125 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002126
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002127 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002128 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2129 AttrIndex++, Attrs),
2130 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002131
Chris Lattner3822f632009-01-02 08:05:26 +00002132 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002133 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002134 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002135 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002136 break;
2137 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002138
Chris Lattnerac161bf2009-01-02 07:01:27 +00002139 // Otherwise must be an argument type.
2140 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002141 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002142
Chris Lattnerfdd87902009-10-05 05:54:46 +00002143 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002144 return Error(TypeLoc, "argument can not have void type");
2145
Chris Lattnerdef19492011-06-17 06:36:20 +00002146 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002147 Name = Lex.getStrVal();
2148 Lex.Lex();
2149 } else {
2150 Name = "";
2151 }
Chris Lattner3822f632009-01-02 08:05:26 +00002152
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002153 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002154 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002155
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002156 ArgList.emplace_back(
2157 TypeLoc, ArgTy,
2158 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2159 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002160 }
2161 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002162
Chris Lattner3822f632009-01-02 08:05:26 +00002163 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002164}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002165
Chris Lattnerac161bf2009-01-02 07:01:27 +00002166/// ParseFunctionType
2167/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002168bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002169 assert(Lex.getKind() == lltok::lparen);
2170
Chris Lattnerce473c72009-01-05 08:04:33 +00002171 if (!FunctionType::isValidReturnType(Result))
2172 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002173
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002174 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002175 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002176 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002177 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002178
Chris Lattnerac161bf2009-01-02 07:01:27 +00002179 // Reject names on the arguments lists.
2180 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2181 if (!ArgList[i].Name.empty())
2182 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002183 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002184 return Error(ArgList[i].Loc,
2185 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002186 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002187
Jay Foadb804a2b2011-07-12 14:06:48 +00002188 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002189 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002190 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002191
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002192 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002193 return false;
2194}
2195
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002196/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2197/// other structs.
2198bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2199 SmallVector<Type*, 8> Elts;
2200 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002201
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002202 Result = StructType::get(Context, Elts, Packed);
2203 return false;
2204}
2205
2206/// ParseStructDefinition - Parse a struct in a 'type' definition.
2207bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2208 std::pair<Type*, LocTy> &Entry,
2209 Type *&ResultTy) {
2210 // If the type was already defined, diagnose the redefinition.
2211 if (Entry.first && !Entry.second.isValid())
2212 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002213
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002214 // If we have opaque, just return without filling in the definition for the
2215 // struct. This counts as a definition as far as the .ll file goes.
2216 if (EatIfPresent(lltok::kw_opaque)) {
2217 // This type is being defined, so clear the location to indicate this.
2218 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002219
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002220 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002221 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002222 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002223 ResultTy = Entry.first;
2224 return false;
2225 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002226
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002227 // If the type starts with '<', then it is either a packed struct or a vector.
2228 bool isPacked = EatIfPresent(lltok::less);
2229
2230 // If we don't have a struct, then we have a random type alias, which we
2231 // accept for compatibility with old files. These types are not allowed to be
2232 // forward referenced and not allowed to be recursive.
2233 if (Lex.getKind() != lltok::lbrace) {
2234 if (Entry.first)
2235 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002236
Craig Topper2617dcc2014-04-15 06:32:26 +00002237 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002238 if (isPacked)
2239 return ParseArrayVectorType(ResultTy, true);
2240 return ParseType(ResultTy);
2241 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002242
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002243 // This type is being defined, so clear the location to indicate this.
2244 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002245
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002246 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002247 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002248 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002249
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002250 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002251
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002252 SmallVector<Type*, 8> Body;
2253 if (ParseStructBody(Body) ||
2254 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2255 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002256
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002257 STy->setBody(Body, isPacked);
2258 ResultTy = STy;
2259 return false;
2260}
2261
2262
Chris Lattnerac161bf2009-01-02 07:01:27 +00002263/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002264/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002265/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002266/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002267/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002268/// ::= '<' '{' Type (',' Type)* '}' '>'
2269bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002270 assert(Lex.getKind() == lltok::lbrace);
2271 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002272
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002273 // Handle the empty struct.
2274 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002275 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002276
Chris Lattnerf880ca22009-03-09 04:49:14 +00002277 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002278 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002279 if (ParseType(Ty)) return true;
2280 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002281
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002282 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002283 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002284
Chris Lattner3822f632009-01-02 08:05:26 +00002285 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002286 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002287 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002288
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002289 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002290 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002291
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002292 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002293 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002294
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002295 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002296}
2297
2298/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2299/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002300/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002301/// ::= '[' APSINTVAL 'x' Types ']'
2302/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002303bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002304 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2305 Lex.getAPSIntVal().getBitWidth() > 64)
2306 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002307
Chris Lattnerac161bf2009-01-02 07:01:27 +00002308 LocTy SizeLoc = Lex.getLoc();
2309 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002310 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002311
Chris Lattner3822f632009-01-02 08:05:26 +00002312 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2313 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002314
2315 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002316 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002317 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002318
Chris Lattner3822f632009-01-02 08:05:26 +00002319 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2320 "expected end of sequential type"))
2321 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002322
Chris Lattnerac161bf2009-01-02 07:01:27 +00002323 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002324 if (Size == 0)
2325 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002326 if ((unsigned)Size != Size)
2327 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002328 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002329 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002330 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002331 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002332 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002333 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002334 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002335 }
2336 return false;
2337}
2338
2339//===----------------------------------------------------------------------===//
2340// Function Semantic Analysis.
2341//===----------------------------------------------------------------------===//
2342
Chris Lattner3432c622009-10-28 03:39:23 +00002343LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2344 int functionNumber)
2345 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002346
2347 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002348 for (Argument &A : F.args())
2349 if (!A.hasName())
2350 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002351}
2352
2353LLParser::PerFunctionState::~PerFunctionState() {
2354 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002355
David Blaikie9ebdc692015-09-21 21:07:50 +00002356 for (const auto &P : ForwardRefVals) {
2357 if (isa<BasicBlock>(P.second.first))
2358 continue;
2359 P.second.first->replaceAllUsesWith(
2360 UndefValue::get(P.second.first->getType()));
2361 delete P.second.first;
2362 }
2363
2364 for (const auto &P : ForwardRefValIDs) {
2365 if (isa<BasicBlock>(P.second.first))
2366 continue;
2367 P.second.first->replaceAllUsesWith(
2368 UndefValue::get(P.second.first->getType()));
2369 delete P.second.first;
2370 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002371}
2372
Chris Lattner3432c622009-10-28 03:39:23 +00002373bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002374 if (!ForwardRefVals.empty())
2375 return P.Error(ForwardRefVals.begin()->second.second,
2376 "use of undefined value '%" + ForwardRefVals.begin()->first +
2377 "'");
2378 if (!ForwardRefValIDs.empty())
2379 return P.Error(ForwardRefValIDs.begin()->second.second,
2380 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002381 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002382 return false;
2383}
2384
2385
2386/// GetVal - Get a value with the specified name or ID, creating a
2387/// forward reference record if needed. This can return null if the value
2388/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002389Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002390 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002391 // Look this name up in the normal function symbol table.
2392 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002393
Chris Lattnerac161bf2009-01-02 07:01:27 +00002394 // If this is a forward reference for the value, see if we already created a
2395 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002396 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002397 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002398 if (I != ForwardRefVals.end())
2399 Val = I->second.first;
2400 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002401
Chris Lattnerac161bf2009-01-02 07:01:27 +00002402 // If we have the value in the symbol table or fwd-ref table, return it.
2403 if (Val) {
2404 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002405 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002406 P.Error(Loc, "'%" + Name + "' is not a basic block");
2407 else
2408 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002409 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002410 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002411 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002412
Chris Lattnerac161bf2009-01-02 07:01:27 +00002413 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002414 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002415 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002416 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002417 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002418
Chris Lattnerac161bf2009-01-02 07:01:27 +00002419 // Otherwise, create a new forward reference for this value and remember it.
2420 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002421 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002422 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002423 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002424 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002425 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002426
Chris Lattnerac161bf2009-01-02 07:01:27 +00002427 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2428 return FwdVal;
2429}
2430
David Majnemer8a1c45d2015-12-12 05:38:55 +00002431Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002432 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002433 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002434
Chris Lattnerac161bf2009-01-02 07:01:27 +00002435 // If this is a forward reference for the value, see if we already created a
2436 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002437 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002438 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002439 if (I != ForwardRefValIDs.end())
2440 Val = I->second.first;
2441 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002442
Chris Lattnerac161bf2009-01-02 07:01:27 +00002443 // If we have the value in the symbol table or fwd-ref table, return it.
2444 if (Val) {
2445 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002446 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002447 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002448 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002449 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002450 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002451 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002452 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002453
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002454 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002455 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002456 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002457 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002458
Chris Lattnerac161bf2009-01-02 07:01:27 +00002459 // Otherwise, create a new forward reference for this value and remember it.
2460 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002461 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002462 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002463 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002464 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002465 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002466
Chris Lattnerac161bf2009-01-02 07:01:27 +00002467 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2468 return FwdVal;
2469}
2470
2471/// SetInstName - After an instruction is parsed and inserted into its
2472/// basic block, this installs its name.
2473bool LLParser::PerFunctionState::SetInstName(int NameID,
2474 const std::string &NameStr,
2475 LocTy NameLoc, Instruction *Inst) {
2476 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002477 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002478 if (NameID != -1 || !NameStr.empty())
2479 return P.Error(NameLoc, "instructions returning void cannot have a name");
2480 return false;
2481 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002482
Chris Lattnerac161bf2009-01-02 07:01:27 +00002483 // If this was a numbered instruction, verify that the instruction is the
2484 // expected value and resolve any forward references.
2485 if (NameStr.empty()) {
2486 // If neither a name nor an ID was specified, just use the next ID.
2487 if (NameID == -1)
2488 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002489
Chris Lattnerac161bf2009-01-02 07:01:27 +00002490 if (unsigned(NameID) != NumberedVals.size())
2491 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002492 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002493
David Blaikie9ebdc692015-09-21 21:07:50 +00002494 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002495 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002496 Value *Sentinel = FI->second.first;
2497 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002498 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002499 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002500
2501 Sentinel->replaceAllUsesWith(Inst);
2502 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002503 ForwardRefValIDs.erase(FI);
2504 }
2505
2506 NumberedVals.push_back(Inst);
2507 return false;
2508 }
2509
2510 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002511 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002512 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002513 Value *Sentinel = FI->second.first;
2514 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002515 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002516 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002517
2518 Sentinel->replaceAllUsesWith(Inst);
2519 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002520 ForwardRefVals.erase(FI);
2521 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002522
Chris Lattnerac161bf2009-01-02 07:01:27 +00002523 // Set the name on the instruction.
2524 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002525
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002526 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002527 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002528 NameStr + "'");
2529 return false;
2530}
2531
2532/// GetBB - Get a basic block with the specified name or ID, creating a
2533/// forward reference record if needed.
2534BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2535 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002536 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2537 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002538}
2539
2540BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002541 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2542 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002543}
2544
2545/// DefineBB - Define the specified basic block, which is either named or
2546/// unnamed. If there is an error, this returns null otherwise it returns
2547/// the block being defined.
2548BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2549 LocTy Loc) {
2550 BasicBlock *BB;
2551 if (Name.empty())
2552 BB = GetBB(NumberedVals.size(), Loc);
2553 else
2554 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002555 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002556
Chris Lattnerac161bf2009-01-02 07:01:27 +00002557 // Move the block to the end of the function. Forward ref'd blocks are
2558 // inserted wherever they happen to be referenced.
2559 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002560
Chris Lattnerac161bf2009-01-02 07:01:27 +00002561 // Remove the block from forward ref sets.
2562 if (Name.empty()) {
2563 ForwardRefValIDs.erase(NumberedVals.size());
2564 NumberedVals.push_back(BB);
2565 } else {
2566 // BB forward references are already in the function symbol table.
2567 ForwardRefVals.erase(Name);
2568 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002569
Chris Lattnerac161bf2009-01-02 07:01:27 +00002570 return BB;
2571}
2572
2573//===----------------------------------------------------------------------===//
2574// Constants.
2575//===----------------------------------------------------------------------===//
2576
2577/// ParseValID - Parse an abstract value that doesn't necessarily have a
2578/// type implied. For example, if we parse "4" we don't know what integer type
2579/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002580/// sanity. PFS is used to convert function-local operands of metadata (since
2581/// metadata operands are not just parsed here but also converted to values).
2582/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002583bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002584 ID.Loc = Lex.getLoc();
2585 switch (Lex.getKind()) {
2586 default: return TokError("expected value token");
2587 case lltok::GlobalID: // @42
2588 ID.UIntVal = Lex.getUIntVal();
2589 ID.Kind = ValID::t_GlobalID;
2590 break;
2591 case lltok::GlobalVar: // @foo
2592 ID.StrVal = Lex.getStrVal();
2593 ID.Kind = ValID::t_GlobalName;
2594 break;
2595 case lltok::LocalVarID: // %42
2596 ID.UIntVal = Lex.getUIntVal();
2597 ID.Kind = ValID::t_LocalID;
2598 break;
2599 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002600 ID.StrVal = Lex.getStrVal();
2601 ID.Kind = ValID::t_LocalName;
2602 break;
2603 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002604 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002605 ID.Kind = ValID::t_APSInt;
2606 break;
2607 case lltok::APFloat:
2608 ID.APFloatVal = Lex.getAPFloatVal();
2609 ID.Kind = ValID::t_APFloat;
2610 break;
2611 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002612 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002613 ID.Kind = ValID::t_Constant;
2614 break;
2615 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002616 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002617 ID.Kind = ValID::t_Constant;
2618 break;
2619 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2620 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2621 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002622 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002623
Chris Lattnerac161bf2009-01-02 07:01:27 +00002624 case lltok::lbrace: {
2625 // ValID ::= '{' ConstVector '}'
2626 Lex.Lex();
2627 SmallVector<Constant*, 16> Elts;
2628 if (ParseGlobalValueVector(Elts) ||
2629 ParseToken(lltok::rbrace, "expected end of struct constant"))
2630 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002631
David Blaikieadbda4b2015-08-03 20:08:41 +00002632 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002633 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002634 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2635 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002636 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002637 return false;
2638 }
2639 case lltok::less: {
2640 // ValID ::= '<' ConstVector '>' --> Vector.
2641 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2642 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002643 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002644
Chris Lattnerac161bf2009-01-02 07:01:27 +00002645 SmallVector<Constant*, 16> Elts;
2646 LocTy FirstEltLoc = Lex.getLoc();
2647 if (ParseGlobalValueVector(Elts) ||
2648 (isPackedStruct &&
2649 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2650 ParseToken(lltok::greater, "expected end of constant"))
2651 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002652
Chris Lattnerac161bf2009-01-02 07:01:27 +00002653 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002654 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2655 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2656 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002657 ID.UIntVal = Elts.size();
2658 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002659 return false;
2660 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002661
Chris Lattnerac161bf2009-01-02 07:01:27 +00002662 if (Elts.empty())
2663 return Error(ID.Loc, "constant vector must not be empty");
2664
Duncan Sands9dff9be2010-02-15 16:12:20 +00002665 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002666 !Elts[0]->getType()->isFloatingPointTy() &&
2667 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002668 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002669 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002670
Chris Lattnerac161bf2009-01-02 07:01:27 +00002671 // Verify that all the vector elements have the same type.
2672 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2673 if (Elts[i]->getType() != Elts[0]->getType())
2674 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002675 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002676 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002677
Chris Lattner69229312011-02-15 00:14:00 +00002678 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002679 ID.Kind = ValID::t_Constant;
2680 return false;
2681 }
2682 case lltok::lsquare: { // Array Constant
2683 Lex.Lex();
2684 SmallVector<Constant*, 16> Elts;
2685 LocTy FirstEltLoc = Lex.getLoc();
2686 if (ParseGlobalValueVector(Elts) ||
2687 ParseToken(lltok::rsquare, "expected end of array constant"))
2688 return true;
2689
2690 // Handle empty element.
2691 if (Elts.empty()) {
2692 // Use undef instead of an array because it's inconvenient to determine
2693 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002694 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002695 return false;
2696 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002697
Chris Lattnerac161bf2009-01-02 07:01:27 +00002698 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002699 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002700 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002701
Owen Anderson4056ca92009-07-29 22:17:13 +00002702 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002703
Chris Lattnerac161bf2009-01-02 07:01:27 +00002704 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002705 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002706 if (Elts[i]->getType() != Elts[0]->getType())
2707 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002708 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002709 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002710 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002711
Jay Foad83be3612011-06-22 09:24:39 +00002712 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002713 ID.Kind = ValID::t_Constant;
2714 return false;
2715 }
2716 case lltok::kw_c: // c "foo"
2717 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002718 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2719 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002720 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2721 ID.Kind = ValID::t_Constant;
2722 return false;
2723
2724 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002725 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2726 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002727 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002728 Lex.Lex();
2729 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002730 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002731 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002732 ParseStringConstant(ID.StrVal) ||
2733 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002734 ParseToken(lltok::StringConstant, "expected constraint string"))
2735 return true;
2736 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002737 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002738 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002739 ID.Kind = ValID::t_InlineAsm;
2740 return false;
2741 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002742
Chris Lattner3432c622009-10-28 03:39:23 +00002743 case lltok::kw_blockaddress: {
2744 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2745 Lex.Lex();
2746
2747 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002748
Chris Lattner3432c622009-10-28 03:39:23 +00002749 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2750 ParseValID(Fn) ||
2751 ParseToken(lltok::comma, "expected comma in block address expression")||
2752 ParseValID(Label) ||
2753 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2754 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002755
Chris Lattner3432c622009-10-28 03:39:23 +00002756 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2757 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002758 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002759 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002760
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002761 // Try to find the function (but skip it if it's forward-referenced).
2762 GlobalValue *GV = nullptr;
2763 if (Fn.Kind == ValID::t_GlobalID) {
2764 if (Fn.UIntVal < NumberedVals.size())
2765 GV = NumberedVals[Fn.UIntVal];
2766 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2767 GV = M->getNamedValue(Fn.StrVal);
2768 }
2769 Function *F = nullptr;
2770 if (GV) {
2771 // Confirm that it's actually a function with a definition.
2772 if (!isa<Function>(GV))
2773 return Error(Fn.Loc, "expected function name in blockaddress");
2774 F = cast<Function>(GV);
2775 if (F->isDeclaration())
2776 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2777 }
2778
2779 if (!F) {
2780 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002781 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002782 ForwardRefBlockAddresses.insert(std::make_pair(
2783 std::move(Fn),
2784 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002785 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2786 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002787 if (!FwdRef)
2788 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2789 GlobalValue::InternalLinkage, nullptr, "");
2790 ID.ConstantVal = FwdRef;
2791 ID.Kind = ValID::t_Constant;
2792 return false;
2793 }
2794
2795 // We found the function; now find the basic block. Don't use PFS, since we
2796 // might be inside a constant expression.
2797 BasicBlock *BB;
2798 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2799 if (Label.Kind == ValID::t_LocalID)
2800 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2801 else
2802 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2803 if (!BB)
2804 return Error(Label.Loc, "referenced value is not a basic block");
2805 } else {
2806 if (Label.Kind == ValID::t_LocalID)
2807 return Error(Label.Loc, "cannot take address of numeric label after "
2808 "the function is defined");
2809 BB = dyn_cast_or_null<BasicBlock>(
2810 F->getValueSymbolTable().lookup(Label.StrVal));
2811 if (!BB)
2812 return Error(Label.Loc, "referenced value is not a basic block");
2813 }
2814
2815 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002816 ID.Kind = ValID::t_Constant;
2817 return false;
2818 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002819
Chris Lattnerac161bf2009-01-02 07:01:27 +00002820 case lltok::kw_trunc:
2821 case lltok::kw_zext:
2822 case lltok::kw_sext:
2823 case lltok::kw_fptrunc:
2824 case lltok::kw_fpext:
2825 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002826 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002827 case lltok::kw_uitofp:
2828 case lltok::kw_sitofp:
2829 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002830 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002831 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002832 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002833 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002834 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002835 Constant *SrcVal;
2836 Lex.Lex();
2837 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2838 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002839 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002840 ParseType(DestTy) ||
2841 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2842 return true;
2843 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2844 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002845 getTypeString(SrcVal->getType()) + "' to '" +
2846 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002847 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002848 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002849 ID.Kind = ValID::t_Constant;
2850 return false;
2851 }
2852 case lltok::kw_extractvalue: {
2853 Lex.Lex();
2854 Constant *Val;
2855 SmallVector<unsigned, 4> Indices;
2856 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2857 ParseGlobalTypeAndValue(Val) ||
2858 ParseIndexList(Indices) ||
2859 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2860 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002861
Chris Lattner392be582010-02-12 20:49:41 +00002862 if (!Val->getType()->isAggregateType())
2863 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002864 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002865 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002866 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002867 ID.Kind = ValID::t_Constant;
2868 return false;
2869 }
2870 case lltok::kw_insertvalue: {
2871 Lex.Lex();
2872 Constant *Val0, *Val1;
2873 SmallVector<unsigned, 4> Indices;
2874 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2875 ParseGlobalTypeAndValue(Val0) ||
2876 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2877 ParseGlobalTypeAndValue(Val1) ||
2878 ParseIndexList(Indices) ||
2879 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2880 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002881 if (!Val0->getType()->isAggregateType())
2882 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002883 Type *IndexedType =
2884 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2885 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002886 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002887 if (IndexedType != Val1->getType())
2888 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2889 getTypeString(Val1->getType()) +
2890 "' instead of '" + getTypeString(IndexedType) +
2891 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002892 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002893 ID.Kind = ValID::t_Constant;
2894 return false;
2895 }
2896 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002897 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002898 unsigned PredVal, Opc = Lex.getUIntVal();
2899 Constant *Val0, *Val1;
2900 Lex.Lex();
2901 if (ParseCmpPredicate(PredVal, Opc) ||
2902 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2903 ParseGlobalTypeAndValue(Val0) ||
2904 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2905 ParseGlobalTypeAndValue(Val1) ||
2906 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2907 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002908
Chris Lattnerac161bf2009-01-02 07:01:27 +00002909 if (Val0->getType() != Val1->getType())
2910 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002911
Chris Lattnerac161bf2009-01-02 07:01:27 +00002912 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002913
Chris Lattnerac161bf2009-01-02 07:01:27 +00002914 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002915 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002916 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002917 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002918 } else {
2919 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002920 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002921 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002922 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002923 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002924 }
2925 ID.Kind = ValID::t_Constant;
2926 return false;
2927 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002928
Chris Lattnerac161bf2009-01-02 07:01:27 +00002929 // Binary Operators.
2930 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002931 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002932 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002933 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002934 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002935 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002936 case lltok::kw_udiv:
2937 case lltok::kw_sdiv:
2938 case lltok::kw_fdiv:
2939 case lltok::kw_urem:
2940 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002941 case lltok::kw_frem:
2942 case lltok::kw_shl:
2943 case lltok::kw_lshr:
2944 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002945 bool NUW = false;
2946 bool NSW = false;
2947 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002948 unsigned Opc = Lex.getUIntVal();
2949 Constant *Val0, *Val1;
2950 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002951 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002952 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2953 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002954 if (EatIfPresent(lltok::kw_nuw))
2955 NUW = true;
2956 if (EatIfPresent(lltok::kw_nsw)) {
2957 NSW = true;
2958 if (EatIfPresent(lltok::kw_nuw))
2959 NUW = true;
2960 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002961 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2962 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002963 if (EatIfPresent(lltok::kw_exact))
2964 Exact = true;
2965 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002966 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2967 ParseGlobalTypeAndValue(Val0) ||
2968 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2969 ParseGlobalTypeAndValue(Val1) ||
2970 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2971 return true;
2972 if (Val0->getType() != Val1->getType())
2973 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002974 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002975 if (NUW)
2976 return Error(ModifierLoc, "nuw only applies to integer operations");
2977 if (NSW)
2978 return Error(ModifierLoc, "nsw only applies to integer operations");
2979 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002980 // Check that the type is valid for the operator.
2981 switch (Opc) {
2982 case Instruction::Add:
2983 case Instruction::Sub:
2984 case Instruction::Mul:
2985 case Instruction::UDiv:
2986 case Instruction::SDiv:
2987 case Instruction::URem:
2988 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002989 case Instruction::Shl:
2990 case Instruction::AShr:
2991 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002992 if (!Val0->getType()->isIntOrIntVectorTy())
2993 return Error(ID.Loc, "constexpr requires integer operands");
2994 break;
2995 case Instruction::FAdd:
2996 case Instruction::FSub:
2997 case Instruction::FMul:
2998 case Instruction::FDiv:
2999 case Instruction::FRem:
3000 if (!Val0->getType()->isFPOrFPVectorTy())
3001 return Error(ID.Loc, "constexpr requires fp operands");
3002 break;
3003 default: llvm_unreachable("Unknown binary operator!");
3004 }
Dan Gohman1b849082009-09-07 23:54:19 +00003005 unsigned Flags = 0;
3006 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3007 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003008 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003009 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003010 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003011 ID.Kind = ValID::t_Constant;
3012 return false;
3013 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003014
Chris Lattnerac161bf2009-01-02 07:01:27 +00003015 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003016 case lltok::kw_and:
3017 case lltok::kw_or:
3018 case lltok::kw_xor: {
3019 unsigned Opc = Lex.getUIntVal();
3020 Constant *Val0, *Val1;
3021 Lex.Lex();
3022 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3023 ParseGlobalTypeAndValue(Val0) ||
3024 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3025 ParseGlobalTypeAndValue(Val1) ||
3026 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3027 return true;
3028 if (Val0->getType() != Val1->getType())
3029 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003030 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003031 return Error(ID.Loc,
3032 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003033 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003034 ID.Kind = ValID::t_Constant;
3035 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003036 }
3037
Chris Lattnerac161bf2009-01-02 07:01:27 +00003038 case lltok::kw_getelementptr:
3039 case lltok::kw_shufflevector:
3040 case lltok::kw_insertelement:
3041 case lltok::kw_extractelement:
3042 case lltok::kw_select: {
3043 unsigned Opc = Lex.getUIntVal();
3044 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003045 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003046 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003047 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003048
Dan Gohman1639c392009-07-27 21:53:46 +00003049 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003050 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003051
3052 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3053 return true;
3054
3055 LocTy ExplicitTypeLoc = Lex.getLoc();
3056 if (Opc == Instruction::GetElementPtr) {
3057 if (ParseType(Ty) ||
3058 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3059 return true;
3060 }
3061
3062 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003063 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3064 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003065
Chris Lattnerac161bf2009-01-02 07:01:27 +00003066 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003067 if (Elts.size() == 0 ||
3068 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003069 return Error(ID.Loc, "base of getelementptr must be a pointer");
3070
3071 Type *BaseType = Elts[0]->getType();
3072 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003073 if (Ty != BasePointerType->getElementType())
3074 return Error(
3075 ExplicitTypeLoc,
3076 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003077
Jay Foaded8db7d2011-07-21 14:31:17 +00003078 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003079 for (Constant *Val : Indices) {
3080 Type *ValTy = Val->getType();
3081 if (!ValTy->getScalarType()->isIntegerTy())
3082 return Error(ID.Loc, "getelementptr index must be an integer");
3083 if (ValTy->isVectorTy() != BaseType->isVectorTy())
3084 return Error(ID.Loc, "getelementptr index type missmatch");
3085 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003086 unsigned ValNumEl = ValTy->getVectorNumElements();
3087 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00003088 if (ValNumEl != PtrNumEl)
3089 return Error(
3090 ID.Loc,
3091 "getelementptr vector index has a wrong number of elements");
3092 }
3093 }
3094
Craig Toppere3dcce92015-08-01 22:20:21 +00003095 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003096 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003097 return Error(ID.Loc, "base element of getelementptr must be sized");
3098
David Blaikie4a2e73b2015-04-02 18:55:32 +00003099 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003100 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003101 ID.ConstantVal =
3102 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003103 } else if (Opc == Instruction::Select) {
3104 if (Elts.size() != 3)
3105 return Error(ID.Loc, "expected three operands to select");
3106 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3107 Elts[2]))
3108 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003109 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003110 } else if (Opc == Instruction::ShuffleVector) {
3111 if (Elts.size() != 3)
3112 return Error(ID.Loc, "expected three operands to shufflevector");
3113 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3114 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003115 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003116 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003117 } else if (Opc == Instruction::ExtractElement) {
3118 if (Elts.size() != 2)
3119 return Error(ID.Loc, "expected two operands to extractelement");
3120 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3121 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003122 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003123 } else {
3124 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3125 if (Elts.size() != 3)
3126 return Error(ID.Loc, "expected three operands to insertelement");
3127 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3128 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003129 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003130 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003131 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003132
Chris Lattnerac161bf2009-01-02 07:01:27 +00003133 ID.Kind = ValID::t_Constant;
3134 return false;
3135 }
3136 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003137
Chris Lattnerac161bf2009-01-02 07:01:27 +00003138 Lex.Lex();
3139 return false;
3140}
3141
3142/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003143bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003144 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003145 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003146 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003147 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003148 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003149 if (V && !(C = dyn_cast<Constant>(V)))
3150 return Error(ID.Loc, "global values must be constants");
3151 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003152}
3153
Victor Hernandez9d75c962010-01-11 22:31:58 +00003154bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003155 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003156 return ParseType(Ty) ||
3157 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003158}
3159
Rafael Espindola83a362c2015-01-06 22:55:16 +00003160bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003161 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003162
3163 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003164 if (!EatIfPresent(lltok::kw_comdat))
3165 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003166
3167 if (EatIfPresent(lltok::lparen)) {
3168 if (Lex.getKind() != lltok::ComdatVar)
3169 return TokError("expected comdat variable");
3170 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3171 Lex.Lex();
3172 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3173 return true;
3174 } else {
3175 if (GlobalName.empty())
3176 return TokError("comdat cannot be unnamed");
3177 C = getComdat(GlobalName, KwLoc);
3178 }
3179
David Majnemerdad0a642014-06-27 18:19:56 +00003180 return false;
3181}
3182
Victor Hernandez9d75c962010-01-11 22:31:58 +00003183/// ParseGlobalValueVector
3184/// ::= /*empty*/
3185/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003186bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003187 // Empty list.
3188 if (Lex.getKind() == lltok::rbrace ||
3189 Lex.getKind() == lltok::rsquare ||
3190 Lex.getKind() == lltok::greater ||
3191 Lex.getKind() == lltok::rparen)
3192 return false;
3193
3194 Constant *C;
3195 if (ParseGlobalTypeAndValue(C)) return true;
3196 Elts.push_back(C);
3197
3198 while (EatIfPresent(lltok::comma)) {
3199 if (ParseGlobalTypeAndValue(C)) return true;
3200 Elts.push_back(C);
3201 }
3202
3203 return false;
3204}
3205
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003206bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003207 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003208 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003209 return true;
3210
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003211 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003212 return false;
3213}
3214
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003215/// MDNode:
3216/// ::= !{ ... }
3217/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003218/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003219bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003220 if (Lex.getKind() == lltok::MetadataVar)
3221 return ParseSpecializedMDNode(N);
3222
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003223 return ParseToken(lltok::exclaim, "expected '!' here") ||
3224 ParseMDNodeTail(N);
3225}
3226
3227bool LLParser::ParseMDNodeTail(MDNode *&N) {
3228 // !{ ... }
3229 if (Lex.getKind() == lltok::lbrace)
3230 return ParseMDTuple(N);
3231
3232 // !42
3233 return ParseMDNodeID(N);
3234}
3235
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003236namespace {
3237
3238/// Structure to represent an optional metadata field.
3239template <class FieldTy> struct MDFieldImpl {
3240 typedef MDFieldImpl ImplTy;
3241 FieldTy Val;
3242 bool Seen;
3243
3244 void assign(FieldTy Val) {
3245 Seen = true;
3246 this->Val = std::move(Val);
3247 }
3248
3249 explicit MDFieldImpl(FieldTy Default)
3250 : Val(std::move(Default)), Seen(false) {}
3251};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003252
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003253struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3254 uint64_t Max;
3255
3256 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3257 : ImplTy(Default), Max(Max) {}
3258};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003259struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003260 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003261};
3262struct ColumnField : public MDUnsignedField {
3263 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3264};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003265struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003266 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003267 DwarfTagField(dwarf::Tag DefaultTag)
3268 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003269};
Amjad Abouda9bcf162015-12-10 12:56:35 +00003270struct DwarfMacinfoTypeField : public MDUnsignedField {
3271 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3272 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3273 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3274};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003275struct DwarfAttEncodingField : public MDUnsignedField {
3276 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3277};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003278struct DwarfVirtualityField : public MDUnsignedField {
3279 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3280};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003281struct DwarfLangField : public MDUnsignedField {
3282 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3283};
Adrian Prantlb939a252016-03-31 23:56:58 +00003284struct EmissionKindField : public MDUnsignedField {
3285 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3286};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003287
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003288struct DIFlagField : public MDUnsignedField {
3289 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3290};
3291
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003292struct MDSignedField : public MDFieldImpl<int64_t> {
3293 int64_t Min;
3294 int64_t Max;
3295
3296 MDSignedField(int64_t Default = 0)
3297 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3298 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3299 : ImplTy(Default), Min(Min), Max(Max) {}
3300};
3301
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003302struct MDBoolField : public MDFieldImpl<bool> {
3303 MDBoolField(bool Default = false) : ImplTy(Default) {}
3304};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003305struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003306 bool AllowNull;
3307
3308 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003309};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003310struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3311 MDConstant() : ImplTy(nullptr) {}
3312};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003313struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003314 bool AllowEmpty;
3315 MDStringField(bool AllowEmpty = true)
3316 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003317};
3318struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3319 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3320};
3321
3322} // end namespace
3323
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003324namespace llvm {
3325
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003326template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003327bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003328 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003329 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3330 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003331
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003332 auto &U = Lex.getAPSIntVal();
3333 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003334 return TokError("value for '" + Name + "' too large, limit is " +
3335 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003336 Result.assign(U.getZExtValue());
3337 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003338 Lex.Lex();
3339 return false;
3340}
3341
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003342template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003343bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3344 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3345}
3346template <>
3347bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3348 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3349}
3350
3351template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003352bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3353 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003354 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003355
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003356 if (Lex.getKind() != lltok::DwarfTag)
3357 return TokError("expected DWARF tag");
3358
3359 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3360 if (Tag == dwarf::DW_TAG_invalid)
3361 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003362 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003363
3364 Result.assign(Tag);
3365 Lex.Lex();
3366 return false;
3367}
3368
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003369template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003370bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003371 DwarfMacinfoTypeField &Result) {
3372 if (Lex.getKind() == lltok::APSInt)
3373 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3374
3375 if (Lex.getKind() != lltok::DwarfMacinfo)
3376 return TokError("expected DWARF macinfo type");
3377
3378 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3379 if (Macinfo == dwarf::DW_MACINFO_invalid)
3380 return TokError(
3381 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3382 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3383
3384 Result.assign(Macinfo);
3385 Lex.Lex();
3386 return false;
3387}
3388
3389template <>
3390bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003391 DwarfVirtualityField &Result) {
3392 if (Lex.getKind() == lltok::APSInt)
3393 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3394
3395 if (Lex.getKind() != lltok::DwarfVirtuality)
3396 return TokError("expected DWARF virtuality code");
3397
3398 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003399 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003400 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3401 Lex.getStrVal() + "'");
3402 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3403 Result.assign(Virtuality);
3404 Lex.Lex();
3405 return false;
3406}
3407
3408template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003409bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3410 if (Lex.getKind() == lltok::APSInt)
3411 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3412
3413 if (Lex.getKind() != lltok::DwarfLang)
3414 return TokError("expected DWARF language");
3415
3416 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3417 if (!Lang)
3418 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3419 "'");
3420 assert(Lang <= Result.Max && "Expected valid DWARF language");
3421 Result.assign(Lang);
3422 Lex.Lex();
3423 return false;
3424}
3425
3426template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003427bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3428 if (Lex.getKind() == lltok::APSInt)
3429 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3430
3431 if (Lex.getKind() != lltok::EmissionKind)
3432 return TokError("expected emission kind");
3433
3434 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3435 if (!Kind)
3436 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3437 "'");
3438 assert(*Kind <= Result.Max && "Expected valid emission kind");
3439 Result.assign(*Kind);
3440 Lex.Lex();
3441 return false;
3442}
3443
3444template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003445bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003446 DwarfAttEncodingField &Result) {
3447 if (Lex.getKind() == lltok::APSInt)
3448 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3449
3450 if (Lex.getKind() != lltok::DwarfAttEncoding)
3451 return TokError("expected DWARF type attribute encoding");
3452
3453 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3454 if (!Encoding)
3455 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3456 Lex.getStrVal() + "'");
3457 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3458 Result.assign(Encoding);
3459 Lex.Lex();
3460 return false;
3461}
3462
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003463/// DIFlagField
3464/// ::= uint32
3465/// ::= DIFlagVector
3466/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3467template <>
3468bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3469 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3470
3471 // Parser for a single flag.
3472 auto parseFlag = [&](unsigned &Val) {
3473 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3474 return ParseUInt32(Val);
3475
3476 if (Lex.getKind() != lltok::DIFlag)
3477 return TokError("expected debug info flag");
3478
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003479 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003480 if (!Val)
3481 return TokError(Twine("invalid debug info flag flag '") +
3482 Lex.getStrVal() + "'");
3483 Lex.Lex();
3484 return false;
3485 };
3486
3487 // Parse the flags and combine them together.
3488 unsigned Combined = 0;
3489 do {
3490 unsigned Val;
3491 if (parseFlag(Val))
3492 return true;
3493 Combined |= Val;
3494 } while (EatIfPresent(lltok::bar));
3495
3496 Result.assign(Combined);
3497 return false;
3498}
3499
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003500template <>
3501bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003502 MDSignedField &Result) {
3503 if (Lex.getKind() != lltok::APSInt)
3504 return TokError("expected signed integer");
3505
3506 auto &S = Lex.getAPSIntVal();
3507 if (S < Result.Min)
3508 return TokError("value for '" + Name + "' too small, limit is " +
3509 Twine(Result.Min));
3510 if (S > Result.Max)
3511 return TokError("value for '" + Name + "' too large, limit is " +
3512 Twine(Result.Max));
3513 Result.assign(S.getExtValue());
3514 assert(Result.Val >= Result.Min && "Expected value in range");
3515 assert(Result.Val <= Result.Max && "Expected value in range");
3516 Lex.Lex();
3517 return false;
3518}
3519
3520template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003521bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3522 switch (Lex.getKind()) {
3523 default:
3524 return TokError("expected 'true' or 'false'");
3525 case lltok::kw_true:
3526 Result.assign(true);
3527 break;
3528 case lltok::kw_false:
3529 Result.assign(false);
3530 break;
3531 }
3532 Lex.Lex();
3533 return false;
3534}
3535
3536template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003537bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003538 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003539 if (!Result.AllowNull)
3540 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003541 Lex.Lex();
3542 Result.assign(nullptr);
3543 return false;
3544 }
3545
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003546 Metadata *MD;
3547 if (ParseMetadata(MD, nullptr))
3548 return true;
3549
3550 Result.assign(MD);
3551 return false;
3552}
3553
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003554template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003555bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3556 Metadata *MD;
3557 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3558 return true;
3559
3560 Result.assign(cast<ConstantAsMetadata>(MD));
3561 return false;
3562}
3563
3564template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003565bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003566 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003567 std::string S;
3568 if (ParseStringConstant(S))
3569 return true;
3570
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003571 if (!Result.AllowEmpty && S.empty())
3572 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3573
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003574 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003575 return false;
3576}
3577
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003578template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003579bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3580 SmallVector<Metadata *, 4> MDs;
3581 if (ParseMDNodeVector(MDs))
3582 return true;
3583
3584 Result.assign(std::move(MDs));
3585 return false;
3586}
3587
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003588} // end namespace llvm
3589
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003590template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003591bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003592 do {
3593 if (Lex.getKind() != lltok::LabelStr)
3594 return TokError("expected field label here");
3595
3596 if (parseField())
3597 return true;
3598 } while (EatIfPresent(lltok::comma));
3599
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003600 return false;
3601}
3602
3603template <class ParserTy>
3604bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3605 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3606 Lex.Lex();
3607
3608 if (ParseToken(lltok::lparen, "expected '(' here"))
3609 return true;
3610 if (Lex.getKind() != lltok::rparen)
3611 if (ParseMDFieldsImplBody(parseField))
3612 return true;
3613
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003614 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003615 return ParseToken(lltok::rparen, "expected ')' here");
3616}
3617
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003618template <class FieldTy>
3619bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3620 if (Result.Seen)
3621 return TokError("field '" + Name + "' cannot be specified more than once");
3622
3623 LocTy Loc = Lex.getLoc();
3624 Lex.Lex();
3625 return ParseMDField(Loc, Name, Result);
3626}
3627
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003628bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3629 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003630
3631#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003632 if (Lex.getStrVal() == #CLASS) \
3633 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003634#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003635
3636 return TokError("expected metadata type");
3637}
3638
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003639#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3640#define NOP_FIELD(NAME, TYPE, INIT)
3641#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3642 if (!NAME.Seen) \
3643 return Error(ClosingLoc, "missing required field '" #NAME "'");
3644#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003645 if (Lex.getStrVal() == #NAME) \
3646 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003647#define PARSE_MD_FIELDS() \
3648 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3649 do { \
3650 LocTy ClosingLoc; \
3651 if (ParseMDFieldsImpl([&]() -> bool { \
3652 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3653 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3654 }, ClosingLoc)) \
3655 return true; \
3656 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3657 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003658#define GET_OR_DISTINCT(CLASS, ARGS) \
3659 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003660
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003661/// ParseDILocationFields:
3662/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3663bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003664#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003665 OPTIONAL(line, LineField, ); \
3666 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003667 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003668 OPTIONAL(inlinedAt, MDField, );
3669 PARSE_MD_FIELDS();
3670#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003671
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003672 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003673 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003674 return false;
3675}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003676
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003677/// ParseGenericDINode:
3678/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3679bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003680#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003681 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003682 OPTIONAL(header, MDStringField, ); \
3683 OPTIONAL(operands, MDFieldList, );
3684 PARSE_MD_FIELDS();
3685#undef VISIT_MD_FIELDS
3686
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003687 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003688 (Context, tag.Val, header.Val, operands.Val));
3689 return false;
3690}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003691
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003692/// ParseDISubrange:
3693/// ::= !DISubrange(count: 30, lowerBound: 2)
3694bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003695#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003696 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003697 OPTIONAL(lowerBound, MDSignedField, );
3698 PARSE_MD_FIELDS();
3699#undef VISIT_MD_FIELDS
3700
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003701 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003702 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003703}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003704
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003705/// ParseDIEnumerator:
3706/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3707bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003708#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003709 REQUIRED(name, MDStringField, ); \
3710 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003711 PARSE_MD_FIELDS();
3712#undef VISIT_MD_FIELDS
3713
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003714 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003715 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003716}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003717
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003718/// ParseDIBasicType:
3719/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3720bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003721#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003722 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003723 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003724 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3725 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003726 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003727 PARSE_MD_FIELDS();
3728#undef VISIT_MD_FIELDS
3729
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003730 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003731 align.Val, encoding.Val));
3732 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003733}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003734
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003735/// ParseDIDerivedType:
3736/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003737/// line: 7, scope: !1, baseType: !2, size: 32,
3738/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003739bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003740#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3741 REQUIRED(tag, DwarfTagField, ); \
3742 OPTIONAL(name, MDStringField, ); \
3743 OPTIONAL(file, MDField, ); \
3744 OPTIONAL(line, LineField, ); \
3745 OPTIONAL(scope, MDField, ); \
3746 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003747 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3748 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3749 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003750 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003751 OPTIONAL(extraData, MDField, );
3752 PARSE_MD_FIELDS();
3753#undef VISIT_MD_FIELDS
3754
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003755 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003756 (Context, tag.Val, name.Val, file.Val, line.Val,
3757 scope.Val, baseType.Val, size.Val, align.Val,
3758 offset.Val, flags.Val, extraData.Val));
3759 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003760}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003761
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003762bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003763#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3764 REQUIRED(tag, DwarfTagField, ); \
3765 OPTIONAL(name, MDStringField, ); \
3766 OPTIONAL(file, MDField, ); \
3767 OPTIONAL(line, LineField, ); \
3768 OPTIONAL(scope, MDField, ); \
3769 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003770 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3771 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3772 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003773 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003774 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003775 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003776 OPTIONAL(vtableHolder, MDField, ); \
3777 OPTIONAL(templateParams, MDField, ); \
3778 OPTIONAL(identifier, MDStringField, );
3779 PARSE_MD_FIELDS();
3780#undef VISIT_MD_FIELDS
3781
3782 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003783 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003784 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3785 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3786 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3787 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003788}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003789
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003790bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003791#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003792 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003793 REQUIRED(types, MDField, );
3794 PARSE_MD_FIELDS();
3795#undef VISIT_MD_FIELDS
3796
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003797 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003798 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003799}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003800
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003801/// ParseDIFileType:
3802/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3803bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003804#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3805 REQUIRED(filename, MDStringField, ); \
3806 REQUIRED(directory, MDStringField, );
3807 PARSE_MD_FIELDS();
3808#undef VISIT_MD_FIELDS
3809
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003810 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003811 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003812}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003813
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003814/// ParseDICompileUnit:
3815/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003816/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00003817/// splitDebugFilename: "abc.debug",
3818/// emissionKind: FullDebug,
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003819/// enums: !1, retainedTypes: !2, subprograms: !3,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003820/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003821bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003822 if (!IsDistinct)
3823 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3824
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003825#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3826 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003827 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003828 OPTIONAL(producer, MDStringField, ); \
3829 OPTIONAL(isOptimized, MDBoolField, ); \
3830 OPTIONAL(flags, MDStringField, ); \
3831 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3832 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00003833 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003834 OPTIONAL(enums, MDField, ); \
3835 OPTIONAL(retainedTypes, MDField, ); \
3836 OPTIONAL(subprograms, MDField, ); \
3837 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003838 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00003839 OPTIONAL(macros, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003840 OPTIONAL(dwoId, MDUnsignedField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003841 PARSE_MD_FIELDS();
3842#undef VISIT_MD_FIELDS
3843
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003844 Result = DICompileUnit::getDistinct(
3845 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3846 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003847 retainedTypes.Val, subprograms.Val, globals.Val, imports.Val, macros.Val,
3848 dwoId.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003849 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003850}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003851
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003852/// ParseDISubprogram:
3853/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003854/// file: !1, line: 7, type: !2, isLocal: false,
3855/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003856/// virtuality: DW_VIRTUALTIY_pure_virtual,
3857/// virtualIndex: 10, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00003858/// isOptimized: false, templateParams: !4, declaration: !5,
3859/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003860bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003861 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003862#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3863 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003864 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003865 OPTIONAL(linkageName, MDStringField, ); \
3866 OPTIONAL(file, MDField, ); \
3867 OPTIONAL(line, LineField, ); \
3868 OPTIONAL(type, MDField, ); \
3869 OPTIONAL(isLocal, MDBoolField, ); \
3870 OPTIONAL(isDefinition, MDBoolField, (true)); \
3871 OPTIONAL(scopeLine, LineField, ); \
3872 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003873 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003874 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003875 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003876 OPTIONAL(isOptimized, MDBoolField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003877 OPTIONAL(templateParams, MDField, ); \
3878 OPTIONAL(declaration, MDField, ); \
3879 OPTIONAL(variables, MDField, );
3880 PARSE_MD_FIELDS();
3881#undef VISIT_MD_FIELDS
3882
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003883 if (isDefinition.Val && !IsDistinct)
3884 return Lex.Error(
3885 Loc,
3886 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
3887
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003888 Result = GET_OR_DISTINCT(
Peter Collingbourned4bff302015-11-05 22:03:56 +00003889 DISubprogram,
3890 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
3891 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
3892 containingType.Val, virtuality.Val, virtualIndex.Val, flags.Val,
3893 isOptimized.Val, templateParams.Val, declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003894 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003895}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003896
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003897/// ParseDILexicalBlock:
3898/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3899bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003900#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003901 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003902 OPTIONAL(file, MDField, ); \
3903 OPTIONAL(line, LineField, ); \
3904 OPTIONAL(column, ColumnField, );
3905 PARSE_MD_FIELDS();
3906#undef VISIT_MD_FIELDS
3907
3908 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003909 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003910 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003911}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003912
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003913/// ParseDILexicalBlockFile:
3914/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3915bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003916#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003917 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003918 OPTIONAL(file, MDField, ); \
3919 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3920 PARSE_MD_FIELDS();
3921#undef VISIT_MD_FIELDS
3922
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003923 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003924 (Context, scope.Val, file.Val, discriminator.Val));
3925 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003926}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003927
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003928/// ParseDINamespace:
3929/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3930bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003931#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3932 REQUIRED(scope, MDField, ); \
3933 OPTIONAL(file, MDField, ); \
3934 OPTIONAL(name, MDStringField, ); \
3935 OPTIONAL(line, LineField, );
3936 PARSE_MD_FIELDS();
3937#undef VISIT_MD_FIELDS
3938
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003939 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003940 (Context, scope.Val, file.Val, name.Val, line.Val));
3941 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003942}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003943
Amjad Abouda9bcf162015-12-10 12:56:35 +00003944/// ParseDIMacro:
3945/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
3946bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
3947#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3948 REQUIRED(type, DwarfMacinfoTypeField, ); \
3949 REQUIRED(line, LineField, ); \
3950 REQUIRED(name, MDStringField, ); \
3951 OPTIONAL(value, MDStringField, );
3952 PARSE_MD_FIELDS();
3953#undef VISIT_MD_FIELDS
3954
3955 Result = GET_OR_DISTINCT(DIMacro,
3956 (Context, type.Val, line.Val, name.Val, value.Val));
3957 return false;
3958}
3959
3960/// ParseDIMacroFile:
3961/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
3962bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
3963#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3964 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
3965 REQUIRED(line, LineField, ); \
3966 REQUIRED(file, MDField, ); \
3967 OPTIONAL(nodes, MDField, );
3968 PARSE_MD_FIELDS();
3969#undef VISIT_MD_FIELDS
3970
3971 Result = GET_OR_DISTINCT(DIMacroFile,
3972 (Context, type.Val, line.Val, file.Val, nodes.Val));
3973 return false;
3974}
3975
3976
Adrian Prantlab1243f2015-06-29 23:03:47 +00003977/// ParseDIModule:
3978/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
3979/// includePath: "/usr/include", isysroot: "/")
3980bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
3981#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3982 REQUIRED(scope, MDField, ); \
3983 REQUIRED(name, MDStringField, ); \
3984 OPTIONAL(configMacros, MDStringField, ); \
3985 OPTIONAL(includePath, MDStringField, ); \
3986 OPTIONAL(isysroot, MDStringField, );
3987 PARSE_MD_FIELDS();
3988#undef VISIT_MD_FIELDS
3989
3990 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
3991 configMacros.Val, includePath.Val, isysroot.Val));
3992 return false;
3993}
3994
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003995/// ParseDITemplateTypeParameter:
3996/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3997bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003998#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003999 OPTIONAL(name, MDStringField, ); \
4000 REQUIRED(type, MDField, );
4001 PARSE_MD_FIELDS();
4002#undef VISIT_MD_FIELDS
4003
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004004 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004005 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004006 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004007}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004008
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004009/// ParseDITemplateValueParameter:
4010/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004011/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004012bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004013#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004014 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004015 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004016 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004017 REQUIRED(value, MDField, );
4018 PARSE_MD_FIELDS();
4019#undef VISIT_MD_FIELDS
4020
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004021 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004022 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004023 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004024}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004025
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004026/// ParseDIGlobalVariable:
4027/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004028/// file: !1, line: 7, type: !2, isLocal: false,
4029/// isDefinition: true, variable: i32* @foo,
4030/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004031bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004032#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004033 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004034 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004035 OPTIONAL(linkageName, MDStringField, ); \
4036 OPTIONAL(file, MDField, ); \
4037 OPTIONAL(line, LineField, ); \
4038 OPTIONAL(type, MDField, ); \
4039 OPTIONAL(isLocal, MDBoolField, ); \
4040 OPTIONAL(isDefinition, MDBoolField, (true)); \
4041 OPTIONAL(variable, MDConstant, ); \
4042 OPTIONAL(declaration, MDField, );
4043 PARSE_MD_FIELDS();
4044#undef VISIT_MD_FIELDS
4045
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004046 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004047 (Context, scope.Val, name.Val, linkageName.Val,
4048 file.Val, line.Val, type.Val, isLocal.Val,
4049 isDefinition.Val, variable.Val, declaration.Val));
4050 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004051}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004052
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004053/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004054/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4055/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
4056/// ::= !DILocalVariable(scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004057/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004058bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004059#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004060 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004061 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004062 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004063 OPTIONAL(file, MDField, ); \
4064 OPTIONAL(line, LineField, ); \
4065 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004066 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004067 PARSE_MD_FIELDS();
4068#undef VISIT_MD_FIELDS
4069
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004070 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004071 (Context, scope.Val, name.Val, file.Val, line.Val,
4072 type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004073 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004074}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004075
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004076/// ParseDIExpression:
4077/// ::= !DIExpression(0, 7, -1)
4078bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004079 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4080 Lex.Lex();
4081
4082 if (ParseToken(lltok::lparen, "expected '(' here"))
4083 return true;
4084
4085 SmallVector<uint64_t, 8> Elements;
4086 if (Lex.getKind() != lltok::rparen)
4087 do {
4088 if (Lex.getKind() == lltok::DwarfOp) {
4089 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4090 Lex.Lex();
4091 Elements.push_back(Op);
4092 continue;
4093 }
4094 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4095 }
4096
4097 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4098 return TokError("expected unsigned integer");
4099
4100 auto &U = Lex.getAPSIntVal();
4101 if (U.ugt(UINT64_MAX))
4102 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4103 Elements.push_back(U.getZExtValue());
4104 Lex.Lex();
4105 } while (EatIfPresent(lltok::comma));
4106
4107 if (ParseToken(lltok::rparen, "expected ')' here"))
4108 return true;
4109
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004110 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004111 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004112}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004113
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004114/// ParseDIObjCProperty:
4115/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004116/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004117bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004118#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004119 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004120 OPTIONAL(file, MDField, ); \
4121 OPTIONAL(line, LineField, ); \
4122 OPTIONAL(setter, MDStringField, ); \
4123 OPTIONAL(getter, MDStringField, ); \
4124 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4125 OPTIONAL(type, MDField, );
4126 PARSE_MD_FIELDS();
4127#undef VISIT_MD_FIELDS
4128
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004129 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004130 (Context, name.Val, file.Val, line.Val, setter.Val,
4131 getter.Val, attributes.Val, type.Val));
4132 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004133}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004134
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004135/// ParseDIImportedEntity:
4136/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004137/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004138bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004139#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4140 REQUIRED(tag, DwarfTagField, ); \
4141 REQUIRED(scope, MDField, ); \
4142 OPTIONAL(entity, MDField, ); \
4143 OPTIONAL(line, LineField, ); \
4144 OPTIONAL(name, MDStringField, );
4145 PARSE_MD_FIELDS();
4146#undef VISIT_MD_FIELDS
4147
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004148 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004149 entity.Val, line.Val, name.Val));
4150 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004151}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004152
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004153#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004154#undef NOP_FIELD
4155#undef REQUIRE_FIELD
4156#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004157
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004158/// ParseMetadataAsValue
4159/// ::= metadata i32 %local
4160/// ::= metadata i32 @global
4161/// ::= metadata i32 7
4162/// ::= metadata !0
4163/// ::= metadata !{...}
4164/// ::= metadata !"string"
4165bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4166 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004167 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004168 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004169 return true;
4170
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004171 V = MetadataAsValue::get(Context, MD);
4172 return false;
4173}
4174
4175/// ParseValueAsMetadata
4176/// ::= i32 %local
4177/// ::= i32 @global
4178/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004179bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4180 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004181 Type *Ty;
4182 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004183 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004184 return true;
4185 if (Ty->isMetadataTy())
4186 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4187
4188 Value *V;
4189 if (ParseValue(Ty, V, PFS))
4190 return true;
4191
4192 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004193 return false;
4194}
4195
4196/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004197/// ::= i32 %local
4198/// ::= i32 @global
4199/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004200/// ::= !42
4201/// ::= !{...}
4202/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004203/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004204bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004205 if (Lex.getKind() == lltok::MetadataVar) {
4206 MDNode *N;
4207 if (ParseSpecializedMDNode(N))
4208 return true;
4209 MD = N;
4210 return false;
4211 }
4212
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004213 // ValueAsMetadata:
4214 // <type> <value>
4215 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004216 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004217
4218 // '!'.
4219 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4220 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004221
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004222 // MDString:
4223 // ::= '!' STRINGCONSTANT
4224 if (Lex.getKind() == lltok::StringConstant) {
4225 MDString *S;
4226 if (ParseMDString(S))
4227 return true;
4228 MD = S;
4229 return false;
4230 }
4231
Dan Gohman8939ba332010-07-14 18:26:50 +00004232 // MDNode:
4233 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004234 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004235 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004236 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004237 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004238 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004239 return false;
4240}
4241
Victor Hernandez9d75c962010-01-11 22:31:58 +00004242
4243//===----------------------------------------------------------------------===//
4244// Function Parsing.
4245//===----------------------------------------------------------------------===//
4246
Chris Lattner229907c2011-07-18 04:54:35 +00004247bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004248 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004249 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004250 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004251
Chris Lattnerac161bf2009-01-02 07:01:27 +00004252 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004253 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004254 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004255 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004256 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004257 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004258 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004259 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004260 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004261 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004262 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004263 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004264 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4265 (ID.UIntVal >> 1) & 1,
4266 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004267 return false;
4268 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004269 case ValID::t_GlobalName:
4270 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004271 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004272 case ValID::t_GlobalID:
4273 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004274 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004275 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004276 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004277 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004278 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004279 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004280 return false;
4281 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004282 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004283 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4284 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004285
Dan Gohman518cda42011-12-17 00:04:22 +00004286 // The lexer has no type info, so builds all half, float, and double FP
4287 // constants as double. Fix this here. Long double does not need this.
4288 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004289 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004290 if (Ty->isHalfTy())
4291 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4292 &Ignored);
4293 else if (Ty->isFloatTy())
4294 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4295 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004296 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004297 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004298
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004299 if (V->getType() != Ty)
4300 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004301 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004302
Chris Lattnerac161bf2009-01-02 07:01:27 +00004303 return false;
4304 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004305 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004306 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004307 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004308 return false;
4309 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004310 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004311 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004312 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004313 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004314 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004315 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004316 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004317 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004318 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004319 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004320 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004321 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004322 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004323 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004324 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004325 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004326 case ValID::t_None:
4327 if (!Ty->isTokenTy())
4328 return Error(ID.Loc, "invalid type for none constant");
4329 V = Constant::getNullValue(Ty);
4330 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004331 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004332 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004333 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004334
Chris Lattnerac161bf2009-01-02 07:01:27 +00004335 V = ID.ConstantVal;
4336 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004337 case ValID::t_ConstantStruct:
4338 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004339 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004340 if (ST->getNumElements() != ID.UIntVal)
4341 return Error(ID.Loc,
4342 "initializer with struct type has wrong # elements");
4343 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4344 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004345
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004346 // Verify that the elements are compatible with the structtype.
4347 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4348 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4349 return Error(ID.Loc, "element " + Twine(i) +
4350 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004351
David Blaikieadbda4b2015-08-03 20:08:41 +00004352 V = ConstantStruct::get(
4353 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004354 } else
4355 return Error(ID.Loc, "constant expression type mismatch");
4356 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004357 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004358 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004359}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004360
Alex Lorenzd2255952015-07-17 22:07:03 +00004361bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4362 C = nullptr;
4363 ValID ID;
4364 auto Loc = Lex.getLoc();
4365 if (ParseValID(ID, /*PFS=*/nullptr))
4366 return true;
4367 switch (ID.Kind) {
4368 case ValID::t_APSInt:
4369 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004370 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004371 case ValID::t_Constant:
4372 case ValID::t_ConstantStruct:
4373 case ValID::t_PackedConstantStruct: {
4374 Value *V;
4375 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4376 return true;
4377 assert(isa<Constant>(V) && "Expected a constant value");
4378 C = cast<Constant>(V);
4379 return false;
4380 }
4381 default:
4382 return Error(Loc, "expected a constant value");
4383 }
4384}
4385
David Majnemer8a1c45d2015-12-12 05:38:55 +00004386bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004387 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004388 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004389 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004390}
4391
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004392bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004393 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004394 return ParseType(Ty) ||
4395 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004396}
4397
Chris Lattner3ed871f2009-10-27 19:13:16 +00004398bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4399 PerFunctionState &PFS) {
4400 Value *V;
4401 Loc = Lex.getLoc();
4402 if (ParseTypeAndValue(V, PFS)) return true;
4403 if (!isa<BasicBlock>(V))
4404 return Error(Loc, "expected a basic block");
4405 BB = cast<BasicBlock>(V);
4406 return false;
4407}
4408
4409
Chris Lattnerac161bf2009-01-02 07:01:27 +00004410/// FunctionHeader
4411/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004412/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004413/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004414bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4415 // Parse the linkage.
4416 LocTy LinkageLoc = Lex.getLoc();
4417 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004418
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004419 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004420 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004421 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004422 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004423 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004424 LocTy RetTypeLoc = Lex.getLoc();
4425 if (ParseOptionalLinkage(Linkage) ||
4426 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00004427 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004428 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004429 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004430 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004431 return true;
4432
4433 // Verify that the linkage is ok.
4434 switch ((GlobalValue::LinkageTypes)Linkage) {
4435 case GlobalValue::ExternalLinkage:
4436 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004437 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004438 if (isDefine)
4439 return Error(LinkageLoc, "invalid linkage for function definition");
4440 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004441 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004442 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004443 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004444 case GlobalValue::LinkOnceAnyLinkage:
4445 case GlobalValue::LinkOnceODRLinkage:
4446 case GlobalValue::WeakAnyLinkage:
4447 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004448 if (!isDefine)
4449 return Error(LinkageLoc, "invalid linkage for function declaration");
4450 break;
4451 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004452 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004453 return Error(LinkageLoc, "invalid function linkage type");
4454 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004455
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004456 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4457 return Error(LinkageLoc,
4458 "symbol with local linkage must have default visibility");
4459
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004460 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004461 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004462
Chris Lattnerac161bf2009-01-02 07:01:27 +00004463 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004464
4465 std::string FunctionName;
4466 if (Lex.getKind() == lltok::GlobalVar) {
4467 FunctionName = Lex.getStrVal();
4468 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4469 unsigned NameID = Lex.getUIntVal();
4470
4471 if (NameID != NumberedVals.size())
4472 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004473 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004474 } else {
4475 return TokError("expected function name");
4476 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004477
Chris Lattner3822f632009-01-02 08:05:26 +00004478 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004479
Chris Lattner3822f632009-01-02 08:05:26 +00004480 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004481 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004482
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004483 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004484 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004485 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004486 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004487 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004488 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004489 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004490 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004491 bool UnnamedAddr;
4492 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004493 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004494 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004495 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004496 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004497
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004498 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004499 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4500 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004501 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004502 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004503 (EatIfPresent(lltok::kw_section) &&
4504 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004505 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004506 ParseOptionalAlignment(Alignment) ||
4507 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004508 ParseStringConstant(GC)) ||
4509 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004510 ParseGlobalTypeAndValue(Prefix)) ||
4511 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004512 ParseGlobalTypeAndValue(Prologue)) ||
4513 (EatIfPresent(lltok::kw_personality) &&
4514 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004515 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004516
Michael Gottesman41748d72013-06-27 00:25:01 +00004517 if (FuncAttrs.contains(Attribute::Builtin))
4518 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004519
Chris Lattnerac161bf2009-01-02 07:01:27 +00004520 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004521 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004522 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004523 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004524 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004525
Chris Lattnerac161bf2009-01-02 07:01:27 +00004526 // Okay, if we got here, the function is syntactically valid. Convert types
4527 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004528 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004529 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004530
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004531 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004532 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4533 AttributeSet::ReturnIndex,
4534 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004535
Chris Lattnerac161bf2009-01-02 07:01:27 +00004536 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004537 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004538 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4539 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004540 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4541 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004542 }
4543
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004544 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004545 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4546 AttributeSet::FunctionIndex,
4547 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004548
Bill Wendlinge94d8432012-12-07 23:16:57 +00004549 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004550
Bill Wendling749a43d2012-12-30 13:50:49 +00004551 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004552 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4553
Chris Lattner229907c2011-07-18 04:54:35 +00004554 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004555 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004556 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004557
Craig Topper2617dcc2014-04-15 06:32:26 +00004558 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004559 if (!FunctionName.empty()) {
4560 // If this was a definition of a forward reference, remove the definition
4561 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004562 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004563 if (FRVI != ForwardRefVals.end()) {
4564 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004565 if (!Fn)
4566 return Error(FRVI->second.second, "invalid forward reference to "
4567 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004568 if (Fn->getType() != PFT)
4569 return Error(FRVI->second.second, "invalid forward reference to "
4570 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004571
Chris Lattnerac161bf2009-01-02 07:01:27 +00004572 ForwardRefVals.erase(FRVI);
4573 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004574 // Reject redefinitions.
4575 return Error(NameLoc, "invalid redefinition of function '" +
4576 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004577 } else if (M->getNamedValue(FunctionName)) {
4578 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004579 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004580
Dan Gohman399d6ae2009-08-29 23:37:49 +00004581 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004582 // If this is a definition of a forward referenced function, make sure the
4583 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004584 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004585 if (I != ForwardRefValIDs.end()) {
4586 Fn = cast<Function>(I->second.first);
4587 if (Fn->getType() != PFT)
4588 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004589 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004590 ForwardRefValIDs.erase(I);
4591 }
4592 }
4593
Craig Topper2617dcc2014-04-15 06:32:26 +00004594 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004595 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4596 else // Move the forward-reference to the correct spot in the module.
4597 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4598
4599 if (FunctionName.empty())
4600 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004601
Chris Lattnerac161bf2009-01-02 07:01:27 +00004602 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4603 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004604 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004605 Fn->setCallingConv(CC);
4606 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004607 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004608 Fn->setAlignment(Alignment);
4609 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004610 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004611 Fn->setPersonalityFn(PersonalityFn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004612 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004613 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004614 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004615 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004616
Chris Lattnerac161bf2009-01-02 07:01:27 +00004617 // Add all of the arguments we parsed to the function.
4618 Function::arg_iterator ArgIt = Fn->arg_begin();
4619 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4620 // If the argument has a name, insert it into the argument symbol table.
4621 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004622
Chris Lattnerac161bf2009-01-02 07:01:27 +00004623 // Set the name, if it conflicted, it will be auto-renamed.
4624 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004625
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004626 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004627 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4628 ArgList[i].Name + "'");
4629 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004630
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004631 if (isDefine)
4632 return false;
4633
Robin Morisset039781e2014-08-29 21:53:01 +00004634 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004635 ValID ID;
4636 if (FunctionName.empty()) {
4637 ID.Kind = ValID::t_GlobalID;
4638 ID.UIntVal = NumberedVals.size() - 1;
4639 } else {
4640 ID.Kind = ValID::t_GlobalName;
4641 ID.StrVal = FunctionName;
4642 }
4643 auto Blocks = ForwardRefBlockAddresses.find(ID);
4644 if (Blocks != ForwardRefBlockAddresses.end())
4645 return Error(Blocks->first.Loc,
4646 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004647 return false;
4648}
4649
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004650bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4651 ValID ID;
4652 if (FunctionNumber == -1) {
4653 ID.Kind = ValID::t_GlobalName;
4654 ID.StrVal = F.getName();
4655 } else {
4656 ID.Kind = ValID::t_GlobalID;
4657 ID.UIntVal = FunctionNumber;
4658 }
4659
4660 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4661 if (Blocks == P.ForwardRefBlockAddresses.end())
4662 return false;
4663
4664 for (const auto &I : Blocks->second) {
4665 const ValID &BBID = I.first;
4666 GlobalValue *GV = I.second;
4667
4668 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4669 "Expected local id or name");
4670 BasicBlock *BB;
4671 if (BBID.Kind == ValID::t_LocalName)
4672 BB = GetBB(BBID.StrVal, BBID.Loc);
4673 else
4674 BB = GetBB(BBID.UIntVal, BBID.Loc);
4675 if (!BB)
4676 return P.Error(BBID.Loc, "referenced value is not a basic block");
4677
4678 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4679 GV->eraseFromParent();
4680 }
4681
4682 P.ForwardRefBlockAddresses.erase(Blocks);
4683 return false;
4684}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004685
4686/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004687/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004688bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004689 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004690 return TokError("expected '{' in function body");
4691 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004692
Chris Lattner3432c622009-10-28 03:39:23 +00004693 int FunctionNumber = -1;
4694 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004695
Chris Lattner3432c622009-10-28 03:39:23 +00004696 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004697
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004698 // Resolve block addresses and allow basic blocks to be forward-declared
4699 // within this function.
4700 if (PFS.resolveForwardRefBlockAddresses())
4701 return true;
4702 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4703
Chris Lattnerbbddd962010-01-09 19:20:07 +00004704 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004705 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004706 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004707
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004708 while (Lex.getKind() != lltok::rbrace &&
4709 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004710 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004711
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004712 while (Lex.getKind() != lltok::rbrace)
4713 if (ParseUseListOrder(&PFS))
4714 return true;
4715
Chris Lattnerac161bf2009-01-02 07:01:27 +00004716 // Eat the }.
4717 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004718
Chris Lattnerac161bf2009-01-02 07:01:27 +00004719 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004720 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004721}
4722
4723/// ParseBasicBlock
4724/// ::= LabelStr? Instruction*
4725bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4726 // If this basic block starts out with a name, remember it.
4727 std::string Name;
4728 LocTy NameLoc = Lex.getLoc();
4729 if (Lex.getKind() == lltok::LabelStr) {
4730 Name = Lex.getStrVal();
4731 Lex.Lex();
4732 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004733
Chris Lattnerac161bf2009-01-02 07:01:27 +00004734 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004735 if (!BB)
4736 return Error(NameLoc,
4737 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004738
Chris Lattnerac161bf2009-01-02 07:01:27 +00004739 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004740
Chris Lattnerac161bf2009-01-02 07:01:27 +00004741 // Parse the instructions in this block until we get a terminator.
4742 Instruction *Inst;
4743 do {
4744 // This instruction may have three possibilities for a name: a) none
4745 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4746 LocTy NameLoc = Lex.getLoc();
4747 int NameID = -1;
4748 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004749
Chris Lattnerac161bf2009-01-02 07:01:27 +00004750 if (Lex.getKind() == lltok::LocalVarID) {
4751 NameID = Lex.getUIntVal();
4752 Lex.Lex();
4753 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4754 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004755 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004756 NameStr = Lex.getStrVal();
4757 Lex.Lex();
4758 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4759 return true;
4760 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004761
Chris Lattner77b89dc2009-12-30 05:23:43 +00004762 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004763 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004764 case InstError: return true;
4765 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004766 BB->getInstList().push_back(Inst);
4767
Chris Lattner77b89dc2009-12-30 05:23:43 +00004768 // With a normal result, we check to see if the instruction is followed by
4769 // a comma and metadata.
4770 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004771 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004772 return true;
4773 break;
4774 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004775 BB->getInstList().push_back(Inst);
4776
Chris Lattner77b89dc2009-12-30 05:23:43 +00004777 // If the instruction parser ate an extra comma at the end of it, it
4778 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004779 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004780 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004781 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004782 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004783
Chris Lattnerac161bf2009-01-02 07:01:27 +00004784 // Set the name on the instruction.
4785 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4786 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004787
Chris Lattnerac161bf2009-01-02 07:01:27 +00004788 return false;
4789}
4790
4791//===----------------------------------------------------------------------===//
4792// Instruction Parsing.
4793//===----------------------------------------------------------------------===//
4794
4795/// ParseInstruction - Parse one of the many different instructions.
4796///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004797int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4798 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004799 lltok::Kind Token = Lex.getKind();
4800 if (Token == lltok::Eof)
4801 return TokError("found end of file when expecting more instructions");
4802 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004803 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004804 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004805
Chris Lattnerac161bf2009-01-02 07:01:27 +00004806 switch (Token) {
4807 default: return Error(Loc, "expected instruction opcode");
4808 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004809 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004810 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4811 case lltok::kw_br: return ParseBr(Inst, PFS);
4812 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004813 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004814 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004815 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00004816 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4817 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004818 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
4819 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004820 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004821 // Binary Operators.
4822 case lltok::kw_add:
4823 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004824 case lltok::kw_mul:
4825 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004826 bool NUW = EatIfPresent(lltok::kw_nuw);
4827 bool NSW = EatIfPresent(lltok::kw_nsw);
4828 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004829
Chris Lattnera676c0f2011-02-07 16:40:21 +00004830 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004831
Chris Lattnera676c0f2011-02-07 16:40:21 +00004832 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4833 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4834 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004835 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004836 case lltok::kw_fadd:
4837 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004838 case lltok::kw_fmul:
4839 case lltok::kw_fdiv:
4840 case lltok::kw_frem: {
4841 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4842 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4843 if (Res != 0)
4844 return Res;
4845 if (FMF.any())
4846 Inst->setFastMathFlags(FMF);
4847 return 0;
4848 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004849
Chris Lattner35315d02011-02-06 21:44:57 +00004850 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004851 case lltok::kw_udiv:
4852 case lltok::kw_lshr:
4853 case lltok::kw_ashr: {
4854 bool Exact = EatIfPresent(lltok::kw_exact);
4855
4856 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4857 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4858 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004859 }
4860
Chris Lattnerac161bf2009-01-02 07:01:27 +00004861 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004862 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004863 case lltok::kw_and:
4864 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004865 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00004866 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4867 case lltok::kw_fcmp: {
4868 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4869 int Res = ParseCompare(Inst, PFS, KeywordVal);
4870 if (Res != 0)
4871 return Res;
4872 if (FMF.any())
4873 Inst->setFastMathFlags(FMF);
4874 return 0;
4875 }
4876
Chris Lattnerac161bf2009-01-02 07:01:27 +00004877 // Casts.
4878 case lltok::kw_trunc:
4879 case lltok::kw_zext:
4880 case lltok::kw_sext:
4881 case lltok::kw_fptrunc:
4882 case lltok::kw_fpext:
4883 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004884 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004885 case lltok::kw_uitofp:
4886 case lltok::kw_sitofp:
4887 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004888 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004889 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004890 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004891 // Other.
4892 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004893 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004894 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4895 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4896 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4897 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004898 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004899 // Call.
4900 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4901 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4902 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00004903 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004904 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004905 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004906 case lltok::kw_load: return ParseLoad(Inst, PFS);
4907 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004908 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4909 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004910 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004911 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4912 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4913 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4914 }
4915}
4916
4917/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4918bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004919 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004920 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004921 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004922 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4923 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4924 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4925 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4926 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4927 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4928 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4929 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4930 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4931 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4932 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4933 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4934 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4935 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4936 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4937 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4938 }
4939 } else {
4940 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004941 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004942 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4943 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4944 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4945 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4946 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4947 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4948 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4949 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4950 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4951 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4952 }
4953 }
4954 Lex.Lex();
4955 return false;
4956}
4957
4958//===----------------------------------------------------------------------===//
4959// Terminator Instructions.
4960//===----------------------------------------------------------------------===//
4961
4962/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00004963/// ::= 'ret' void (',' !dbg, !1)*
4964/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00004965bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004966 PerFunctionState &PFS) {
4967 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00004968 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00004969 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004970
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004971 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004972
Chris Lattnerfdd87902009-10-05 05:54:46 +00004973 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004974 if (!ResType->isVoidTy())
4975 return Error(TypeLoc, "value doesn't match function result type '" +
4976 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004977
Owen Anderson55f1c092009-08-13 21:58:54 +00004978 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004979 return false;
4980 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004981
Chris Lattnerac161bf2009-01-02 07:01:27 +00004982 Value *RV;
4983 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004984
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004985 if (ResType != RV->getType())
4986 return Error(TypeLoc, "value doesn't match function result type '" +
4987 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004988
Owen Anderson55f1c092009-08-13 21:58:54 +00004989 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00004990 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004991}
4992
4993
4994/// ParseBr
4995/// ::= 'br' TypeAndValue
4996/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4997bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4998 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004999 Value *Op0;
5000 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005001 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005002
Chris Lattnerac161bf2009-01-02 07:01:27 +00005003 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5004 Inst = BranchInst::Create(BB);
5005 return false;
5006 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005007
Owen Anderson55f1c092009-08-13 21:58:54 +00005008 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005009 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005010
Chris Lattnerac161bf2009-01-02 07:01:27 +00005011 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005012 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005013 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005014 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005015 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005016
Chris Lattner3ed871f2009-10-27 19:13:16 +00005017 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005018 return false;
5019}
5020
5021/// ParseSwitch
5022/// Instruction
5023/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5024/// JumpTable
5025/// ::= (TypeAndValue ',' TypeAndValue)*
5026bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5027 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005028 Value *Cond;
5029 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005030 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5031 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005032 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005033 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5034 return true;
5035
Duncan Sands19d0b472010-02-16 11:11:14 +00005036 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005037 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005038
Chris Lattnerac161bf2009-01-02 07:01:27 +00005039 // Parse the jump table pairs.
5040 SmallPtrSet<Value*, 32> SeenCases;
5041 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5042 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005043 Value *Constant;
5044 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005045
Chris Lattnerac161bf2009-01-02 07:01:27 +00005046 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5047 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005048 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005049 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005050
David Blaikie70573dc2014-11-19 07:49:26 +00005051 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005052 return Error(CondLoc, "duplicate case value in switch");
5053 if (!isa<ConstantInt>(Constant))
5054 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005055
Chris Lattner3ed871f2009-10-27 19:13:16 +00005056 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005057 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005058
Chris Lattnerac161bf2009-01-02 07:01:27 +00005059 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005060
Chris Lattner3ed871f2009-10-27 19:13:16 +00005061 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005062 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5063 SI->addCase(Table[i].first, Table[i].second);
5064 Inst = SI;
5065 return false;
5066}
5067
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005068/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005069/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005070/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5071bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005072 LocTy AddrLoc;
5073 Value *Address;
5074 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005075 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5076 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005077 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005078
Duncan Sands19d0b472010-02-16 11:11:14 +00005079 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005080 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005081
Chris Lattner3ed871f2009-10-27 19:13:16 +00005082 // Parse the destination list.
5083 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005084
Chris Lattner3ed871f2009-10-27 19:13:16 +00005085 if (Lex.getKind() != lltok::rsquare) {
5086 BasicBlock *DestBB;
5087 if (ParseTypeAndBasicBlock(DestBB, PFS))
5088 return true;
5089 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005090
Chris Lattner3ed871f2009-10-27 19:13:16 +00005091 while (EatIfPresent(lltok::comma)) {
5092 if (ParseTypeAndBasicBlock(DestBB, PFS))
5093 return true;
5094 DestList.push_back(DestBB);
5095 }
5096 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005097
Chris Lattner3ed871f2009-10-27 19:13:16 +00005098 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5099 return true;
5100
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005101 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005102 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5103 IBI->addDestination(DestList[i]);
5104 Inst = IBI;
5105 return false;
5106}
5107
5108
Chris Lattnerac161bf2009-01-02 07:01:27 +00005109/// ParseInvoke
5110/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5111/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5112bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5113 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005114 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005115 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005116 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005117 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005118 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005119 LocTy RetTypeLoc;
5120 ValID CalleeID;
5121 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005122 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005123
Chris Lattner3ed871f2009-10-27 19:13:16 +00005124 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005125 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005126 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005127 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005128 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5129 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005130 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005131 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005132 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005133 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005134 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005135 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005136
Chris Lattnerac161bf2009-01-02 07:01:27 +00005137 // If RetType is a non-function pointer type, then this is the short syntax
5138 // for the call, which means that RetType is just the return type. Infer the
5139 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005140 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5141 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005142 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005143 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005144 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5145 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005146
Chris Lattnerac161bf2009-01-02 07:01:27 +00005147 if (!FunctionType::isValidReturnType(RetType))
5148 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005149
Owen Anderson4056ca92009-07-29 22:17:13 +00005150 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005151 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005152
David Blaikie41ba2b42015-07-27 23:32:19 +00005153 CalleeID.FTy = Ty;
5154
Chris Lattnerac161bf2009-01-02 07:01:27 +00005155 // Look up the callee.
5156 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005157 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5158 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005159
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005160 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005161 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005162 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005163 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5164 AttributeSet::ReturnIndex,
5165 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005166
Chris Lattnerac161bf2009-01-02 07:01:27 +00005167 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005168
Chris Lattnerac161bf2009-01-02 07:01:27 +00005169 // Loop through FunctionType's arguments and ensure they are specified
5170 // correctly. Also, gather any parameter attributes.
5171 FunctionType::param_iterator I = Ty->param_begin();
5172 FunctionType::param_iterator E = Ty->param_end();
5173 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005174 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005175 if (I != E) {
5176 ExpectedTy = *I++;
5177 } else if (!Ty->isVarArg()) {
5178 return Error(ArgList[i].Loc, "too many arguments specified");
5179 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005180
Chris Lattnerac161bf2009-01-02 07:01:27 +00005181 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5182 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005183 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005184 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005185 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5186 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005187 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5188 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005189 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005190
Chris Lattnerac161bf2009-01-02 07:01:27 +00005191 if (I != E)
5192 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005193
David Majnemer8d22abd2015-02-23 00:01:32 +00005194 if (FnAttrs.hasAttributes()) {
5195 if (FnAttrs.hasAlignmentAttr())
5196 return Error(CallLoc, "invoke instructions may not have an alignment");
5197
Bill Wendlingf5075a42013-01-27 02:24:02 +00005198 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5199 AttributeSet::FunctionIndex,
5200 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005201 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005202
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005203 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005204 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005205
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005206 InvokeInst *II =
5207 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005208 II->setCallingConv(CC);
5209 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005210 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005211 Inst = II;
5212 return false;
5213}
5214
Bill Wendlingf891bf82011-07-31 06:30:59 +00005215/// ParseResume
5216/// ::= 'resume' TypeAndValue
5217bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5218 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005219 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5220 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005221
Bill Wendlingf891bf82011-07-31 06:30:59 +00005222 ResumeInst *RI = ResumeInst::Create(Exn);
5223 Inst = RI;
5224 return false;
5225}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005226
David Majnemer654e1302015-07-31 17:58:14 +00005227bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5228 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005229 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005230 return true;
5231
5232 while (Lex.getKind() != lltok::rsquare) {
5233 // If this isn't the first argument, we need a comma.
5234 if (!Args.empty() &&
5235 ParseToken(lltok::comma, "expected ',' in argument list"))
5236 return true;
5237
5238 // Parse the argument.
5239 LocTy ArgLoc;
5240 Type *ArgTy = nullptr;
5241 if (ParseType(ArgTy, ArgLoc))
5242 return true;
5243
5244 Value *V;
5245 if (ArgTy->isMetadataTy()) {
5246 if (ParseMetadataAsValue(V, PFS))
5247 return true;
5248 } else {
5249 if (ParseValue(ArgTy, V, PFS))
5250 return true;
5251 }
5252 Args.push_back(V);
5253 }
5254
5255 Lex.Lex(); // Lex the ']'.
5256 return false;
5257}
5258
5259/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005260/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005261bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005262 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005263
David Majnemer8a1c45d2015-12-12 05:38:55 +00005264 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5265 return true;
5266
5267 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005268 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005269
5270 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5271 return true;
5272
5273 BasicBlock *UnwindBB = nullptr;
5274 if (Lex.getKind() == lltok::kw_to) {
5275 Lex.Lex();
5276 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5277 return true;
5278 } else {
5279 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5280 return true;
5281 }
5282 }
5283
David Majnemer8a1c45d2015-12-12 05:38:55 +00005284 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005285 return false;
5286}
5287
5288/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005289/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005290bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005291 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005292
David Majnemer8a1c45d2015-12-12 05:38:55 +00005293 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5294 return true;
5295
5296 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005297 return true;
5298
David Majnemer0bc0eef2015-08-15 02:46:08 +00005299 BasicBlock *BB;
5300 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5301 ParseTypeAndBasicBlock(BB, PFS))
5302 return true;
5303
David Majnemer8a1c45d2015-12-12 05:38:55 +00005304 Inst = CatchReturnInst::Create(CatchPad, BB);
5305 return false;
5306}
5307
5308/// ParseCatchSwitch
5309/// ::= 'catchswitch' within Parent
5310bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5311 Value *ParentPad;
5312 LocTy BBLoc;
5313
5314 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5315 return true;
5316
5317 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5318 Lex.getKind() != lltok::LocalVarID)
5319 return TokError("expected scope value for catchswitch");
5320
5321 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5322 return true;
5323
5324 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5325 return true;
5326
5327 SmallVector<BasicBlock *, 32> Table;
5328 do {
5329 BasicBlock *DestBB;
5330 if (ParseTypeAndBasicBlock(DestBB, PFS))
5331 return true;
5332 Table.push_back(DestBB);
5333 } while (EatIfPresent(lltok::comma));
5334
5335 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5336 return true;
5337
5338 if (ParseToken(lltok::kw_unwind,
5339 "expected 'unwind' after catchswitch scope"))
5340 return true;
5341
5342 BasicBlock *UnwindBB = nullptr;
5343 if (EatIfPresent(lltok::kw_to)) {
5344 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5345 return true;
5346 } else {
5347 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5348 return true;
5349 }
5350
5351 auto *CatchSwitch =
5352 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5353 for (BasicBlock *DestBB : Table)
5354 CatchSwitch->addHandler(DestBB);
5355 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005356 return false;
5357}
5358
5359/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005360/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005361bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005362 Value *CatchSwitch = nullptr;
5363
5364 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5365 return true;
5366
5367 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5368 return TokError("expected scope value for catchpad");
5369
5370 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5371 return true;
5372
David Majnemer654e1302015-07-31 17:58:14 +00005373 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005374 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005375 return true;
5376
David Majnemer8a1c45d2015-12-12 05:38:55 +00005377 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005378 return false;
5379}
5380
David Majnemer654e1302015-07-31 17:58:14 +00005381/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005382/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005383bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005384 Value *ParentPad = nullptr;
5385
5386 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5387 return true;
5388
5389 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5390 Lex.getKind() != lltok::LocalVarID)
5391 return TokError("expected scope value for cleanuppad");
5392
5393 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5394 return true;
5395
David Majnemer654e1302015-07-31 17:58:14 +00005396 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005397 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005398 return true;
5399
David Majnemer8a1c45d2015-12-12 05:38:55 +00005400 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005401 return false;
5402}
5403
Chris Lattnerac161bf2009-01-02 07:01:27 +00005404//===----------------------------------------------------------------------===//
5405// Binary Operators.
5406//===----------------------------------------------------------------------===//
5407
5408/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005409/// ::= ArithmeticOps TypeAndValue ',' Value
5410///
5411/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5412/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005413bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005414 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005415 LocTy Loc; Value *LHS, *RHS;
5416 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5417 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5418 ParseValue(LHS->getType(), RHS, PFS))
5419 return true;
5420
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005421 bool Valid;
5422 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005423 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005424 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005425 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5426 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005427 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005428 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5429 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005430 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005431
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005432 if (!Valid)
5433 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005434
Chris Lattnerac161bf2009-01-02 07:01:27 +00005435 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5436 return false;
5437}
5438
5439/// ParseLogical
5440/// ::= ArithmeticOps TypeAndValue ',' Value {
5441bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5442 unsigned Opc) {
5443 LocTy Loc; Value *LHS, *RHS;
5444 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5445 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5446 ParseValue(LHS->getType(), RHS, PFS))
5447 return true;
5448
Duncan Sands9dff9be2010-02-15 16:12:20 +00005449 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005450 return Error(Loc,"instruction requires integer or integer vector operands");
5451
5452 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5453 return false;
5454}
5455
5456
5457/// ParseCompare
5458/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5459/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005460bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5461 unsigned Opc) {
5462 // Parse the integer/fp comparison predicate.
5463 LocTy Loc;
5464 unsigned Pred;
5465 Value *LHS, *RHS;
5466 if (ParseCmpPredicate(Pred, Opc) ||
5467 ParseTypeAndValue(LHS, Loc, PFS) ||
5468 ParseToken(lltok::comma, "expected ',' after compare value") ||
5469 ParseValue(LHS->getType(), RHS, PFS))
5470 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005471
Chris Lattnerac161bf2009-01-02 07:01:27 +00005472 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005473 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005474 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005475 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005476 } else {
5477 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005478 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005479 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005480 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005481 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005482 }
5483 return false;
5484}
5485
5486//===----------------------------------------------------------------------===//
5487// Other Instructions.
5488//===----------------------------------------------------------------------===//
5489
5490
5491/// ParseCast
5492/// ::= CastOpc TypeAndValue 'to' Type
5493bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5494 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005495 LocTy Loc;
5496 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005497 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005498 if (ParseTypeAndValue(Op, Loc, PFS) ||
5499 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5500 ParseType(DestTy))
5501 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005502
Chris Lattner89d856e2009-03-01 00:53:13 +00005503 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5504 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005505 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005506 getTypeString(Op->getType()) + "' to '" +
5507 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005508 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005509 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5510 return false;
5511}
5512
5513/// ParseSelect
5514/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5515bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5516 LocTy Loc;
5517 Value *Op0, *Op1, *Op2;
5518 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5519 ParseToken(lltok::comma, "expected ',' after select condition") ||
5520 ParseTypeAndValue(Op1, PFS) ||
5521 ParseToken(lltok::comma, "expected ',' after select value") ||
5522 ParseTypeAndValue(Op2, PFS))
5523 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005524
Chris Lattnerac161bf2009-01-02 07:01:27 +00005525 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5526 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005527
Chris Lattnerac161bf2009-01-02 07:01:27 +00005528 Inst = SelectInst::Create(Op0, Op1, Op2);
5529 return false;
5530}
5531
Chris Lattnerb55ab542009-01-05 08:18:44 +00005532/// ParseVA_Arg
5533/// ::= 'va_arg' TypeAndValue ',' Type
5534bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005535 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005536 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005537 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005538 if (ParseTypeAndValue(Op, PFS) ||
5539 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005540 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005541 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005542
Chris Lattnerb55ab542009-01-05 08:18:44 +00005543 if (!EltTy->isFirstClassType())
5544 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005545
5546 Inst = new VAArgInst(Op, EltTy);
5547 return false;
5548}
5549
5550/// ParseExtractElement
5551/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5552bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5553 LocTy Loc;
5554 Value *Op0, *Op1;
5555 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5556 ParseToken(lltok::comma, "expected ',' after extract value") ||
5557 ParseTypeAndValue(Op1, PFS))
5558 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005559
Chris Lattnerac161bf2009-01-02 07:01:27 +00005560 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5561 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005562
Eric Christopherc9742252009-07-25 02:28:41 +00005563 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005564 return false;
5565}
5566
5567/// ParseInsertElement
5568/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5569bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5570 LocTy Loc;
5571 Value *Op0, *Op1, *Op2;
5572 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5573 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5574 ParseTypeAndValue(Op1, PFS) ||
5575 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5576 ParseTypeAndValue(Op2, PFS))
5577 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005578
Chris Lattnerac161bf2009-01-02 07:01:27 +00005579 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005580 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005581
Chris Lattnerac161bf2009-01-02 07:01:27 +00005582 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5583 return false;
5584}
5585
5586/// ParseShuffleVector
5587/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5588bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5589 LocTy Loc;
5590 Value *Op0, *Op1, *Op2;
5591 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5592 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5593 ParseTypeAndValue(Op1, PFS) ||
5594 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5595 ParseTypeAndValue(Op2, PFS))
5596 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005597
Chris Lattnerac161bf2009-01-02 07:01:27 +00005598 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005599 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005600
Chris Lattnerac161bf2009-01-02 07:01:27 +00005601 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5602 return false;
5603}
5604
5605/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005606/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005607int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005608 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005609 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005610
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005611 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005612 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5613 ParseValue(Ty, Op0, PFS) ||
5614 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005615 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005616 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5617 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005618
Chris Lattnerf4f03422009-12-30 05:27:33 +00005619 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005620 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5621 while (1) {
5622 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005623
Chris Lattner3822f632009-01-02 08:05:26 +00005624 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005625 break;
5626
Chris Lattnerf4f03422009-12-30 05:27:33 +00005627 if (Lex.getKind() == lltok::MetadataVar) {
5628 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005629 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005630 }
Devang Patel8f842d32009-10-16 18:45:49 +00005631
Chris Lattner3822f632009-01-02 08:05:26 +00005632 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005633 ParseValue(Ty, Op0, PFS) ||
5634 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005635 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005636 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5637 return true;
5638 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005639
Chris Lattnerac161bf2009-01-02 07:01:27 +00005640 if (!Ty->isFirstClassType())
5641 return Error(TypeLoc, "phi node must have first class type");
5642
Jay Foad52131342011-03-30 11:28:46 +00005643 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005644 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5645 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5646 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005647 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005648}
5649
Bill Wendlingfae14752011-08-12 20:24:12 +00005650/// ParseLandingPad
5651/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5652/// Clause
5653/// ::= 'catch' TypeAndValue
5654/// ::= 'filter'
5655/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5656bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005657 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005658
David Majnemer7fddecc2015-06-17 20:52:32 +00005659 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005660 return true;
5661
David Majnemer7fddecc2015-06-17 20:52:32 +00005662 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005663 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5664
5665 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5666 LandingPadInst::ClauseType CT;
5667 if (EatIfPresent(lltok::kw_catch))
5668 CT = LandingPadInst::Catch;
5669 else if (EatIfPresent(lltok::kw_filter))
5670 CT = LandingPadInst::Filter;
5671 else
5672 return TokError("expected 'catch' or 'filter' clause type");
5673
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005674 Value *V;
5675 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005676 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005677 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005678
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005679 // A 'catch' type expects a non-array constant. A filter clause expects an
5680 // array constant.
5681 if (CT == LandingPadInst::Catch) {
5682 if (isa<ArrayType>(V->getType()))
5683 Error(VLoc, "'catch' clause has an invalid type");
5684 } else {
5685 if (!isa<ArrayType>(V->getType()))
5686 Error(VLoc, "'filter' clause has an invalid type");
5687 }
5688
Owen Andersonf8f259d2015-03-09 07:13:42 +00005689 Constant *CV = dyn_cast<Constant>(V);
5690 if (!CV)
5691 return Error(VLoc, "clause argument must be a constant");
5692 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005693 }
5694
Owen Andersonf8f259d2015-03-09 07:13:42 +00005695 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005696 return false;
5697}
5698
Chris Lattnerac161bf2009-01-02 07:01:27 +00005699/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005700/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5701/// OptionalAttrs Type Value ParameterList OptionalAttrs
5702/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5703/// OptionalAttrs Type Value ParameterList OptionalAttrs
5704/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5705/// OptionalAttrs Type Value ParameterList OptionalAttrs
5706/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5707/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005708bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005709 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005710 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005711 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005712 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005713 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005714 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005715 LocTy RetTypeLoc;
5716 ValID CalleeID;
5717 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005718 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005719 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005720
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005721 if (TCK != CallInst::TCK_None &&
5722 ParseToken(lltok::kw_call,
5723 "expected 'tail call', 'musttail call', or 'notail call'"))
5724 return true;
5725
5726 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5727
5728 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005729 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005730 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005731 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5732 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005733 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5734 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005735 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005736
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005737 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5738 return Error(CallLoc, "fast-math-flags specified for call without "
5739 "floating-point scalar or vector return type");
5740
Chris Lattnerac161bf2009-01-02 07:01:27 +00005741 // If RetType is a non-function pointer type, then this is the short syntax
5742 // for the call, which means that RetType is just the return type. Infer the
5743 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005744 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5745 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005746 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005747 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005748 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5749 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005750
Chris Lattnerac161bf2009-01-02 07:01:27 +00005751 if (!FunctionType::isValidReturnType(RetType))
5752 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005753
Owen Anderson4056ca92009-07-29 22:17:13 +00005754 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005755 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005756
David Blaikie41ba2b42015-07-27 23:32:19 +00005757 CalleeID.FTy = Ty;
5758
Chris Lattnerac161bf2009-01-02 07:01:27 +00005759 // Look up the callee.
5760 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005761 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5762 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005763
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005764 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005765 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005766 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005767 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5768 AttributeSet::ReturnIndex,
5769 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005770
Chris Lattnerac161bf2009-01-02 07:01:27 +00005771 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005772
Chris Lattnerac161bf2009-01-02 07:01:27 +00005773 // Loop through FunctionType's arguments and ensure they are specified
5774 // correctly. Also, gather any parameter attributes.
5775 FunctionType::param_iterator I = Ty->param_begin();
5776 FunctionType::param_iterator E = Ty->param_end();
5777 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005778 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005779 if (I != E) {
5780 ExpectedTy = *I++;
5781 } else if (!Ty->isVarArg()) {
5782 return Error(ArgList[i].Loc, "too many arguments specified");
5783 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005784
Chris Lattnerac161bf2009-01-02 07:01:27 +00005785 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5786 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005787 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005788 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005789 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5790 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005791 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5792 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005793 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005794
Chris Lattnerac161bf2009-01-02 07:01:27 +00005795 if (I != E)
5796 return Error(CallLoc, "not enough parameters specified for call");
5797
David Majnemer8d22abd2015-02-23 00:01:32 +00005798 if (FnAttrs.hasAttributes()) {
5799 if (FnAttrs.hasAlignmentAttr())
5800 return Error(CallLoc, "call instructions may not have an alignment");
5801
Bill Wendlingf5075a42013-01-27 02:24:02 +00005802 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5803 AttributeSet::FunctionIndex,
5804 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005805 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005806
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005807 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005808 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005809
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005810 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00005811 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005812 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005813 if (FMF.any())
5814 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005815 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005816 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005817 Inst = CI;
5818 return false;
5819}
5820
5821//===----------------------------------------------------------------------===//
5822// Memory Instructions.
5823//===----------------------------------------------------------------------===//
5824
5825/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00005826/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
5827/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005828int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005829 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005830 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005831 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005832 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005833
5834 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005835 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00005836
David Majnemera3b0eb22015-02-16 08:38:03 +00005837 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005838
David Majnemera3b0eb22015-02-16 08:38:03 +00005839 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5840 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005841
Chris Lattnerb2f39502009-12-30 05:44:30 +00005842 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005843 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005844 if (Lex.getKind() == lltok::kw_align) {
5845 if (ParseOptionalAlignment(Alignment)) return true;
5846 } else if (Lex.getKind() == lltok::MetadataVar) {
5847 AteExtraComma = true;
5848 } else {
5849 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5850 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5851 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005852 }
5853 }
5854
Dan Gohman2140a742010-05-28 01:14:11 +00005855 if (Size && !Size->getType()->isIntegerTy())
5856 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005857
Reid Kleckner436c42e2014-01-17 23:58:17 +00005858 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5859 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005860 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00005861 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005862 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005863}
5864
5865/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005866/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005867/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005868/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005869int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005870 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005871 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005872 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005873 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005874 AtomicOrdering Ordering = NotAtomic;
5875 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005876
5877 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005878 isAtomic = true;
5879 Lex.Lex();
5880 }
5881
Chris Lattnerbc639292011-11-27 06:56:53 +00005882 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005883 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005884 isVolatile = true;
5885 Lex.Lex();
5886 }
5887
David Blaikie15d9a4c2015-04-06 20:59:48 +00005888 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005889 LocTy ExplicitTypeLoc = Lex.getLoc();
5890 if (ParseType(Ty) ||
5891 ParseToken(lltok::comma, "expected comma after load's type") ||
5892 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005893 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005894 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5895 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005896
David Blaikie15d9a4c2015-04-06 20:59:48 +00005897 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005898 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005899 if (isAtomic && !Alignment)
5900 return Error(Loc, "atomic load must have explicit non-zero alignment");
5901 if (Ordering == Release || Ordering == AcquireRelease)
5902 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005903
David Blaikiea79ac142015-02-27 21:17:42 +00005904 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5905 return Error(ExplicitTypeLoc,
5906 "explicit pointee type doesn't match operand's pointee type");
5907
David Blaikie15d9a4c2015-04-06 20:59:48 +00005908 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005909 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005910}
5911
5912/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005913
5914/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5915/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005916/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005917int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005918 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005919 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005920 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005921 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005922 AtomicOrdering Ordering = NotAtomic;
5923 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005924
5925 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005926 isAtomic = true;
5927 Lex.Lex();
5928 }
5929
Chris Lattnerbc639292011-11-27 06:56:53 +00005930 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005931 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005932 isVolatile = true;
5933 Lex.Lex();
5934 }
5935
Chris Lattnerac161bf2009-01-02 07:01:27 +00005936 if (ParseTypeAndValue(Val, Loc, PFS) ||
5937 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005938 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005939 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005940 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005941 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00005942
Duncan Sands19d0b472010-02-16 11:11:14 +00005943 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005944 return Error(PtrLoc, "store operand must be a pointer");
5945 if (!Val->getType()->isFirstClassType())
5946 return Error(Loc, "store operand must be a first class value");
5947 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5948 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00005949 if (isAtomic && !Alignment)
5950 return Error(Loc, "atomic store must have explicit non-zero alignment");
5951 if (Ordering == Acquire || Ordering == AcquireRelease)
5952 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005953
Eli Friedman59b66882011-08-09 23:02:53 +00005954 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005955 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005956}
5957
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005958/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00005959/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5960/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00005961int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005962 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5963 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00005964 AtomicOrdering SuccessOrdering = NotAtomic;
5965 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005966 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005967 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00005968 bool isWeak = false;
5969
5970 if (EatIfPresent(lltok::kw_weak))
5971 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00005972
5973 if (EatIfPresent(lltok::kw_volatile))
5974 isVolatile = true;
5975
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005976 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5977 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5978 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5979 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5980 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00005981 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5982 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005983 return true;
5984
Tim Northovere94a5182014-03-11 10:48:52 +00005985 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005986 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00005987 if (SuccessOrdering < FailureOrdering)
5988 return TokError("cmpxchg must be at least as ordered on success as failure");
5989 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5990 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005991 if (!Ptr->getType()->isPointerTy())
5992 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5993 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5994 return Error(CmpLoc, "compare value and pointer type do not match");
5995 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5996 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00005997 if (!New->getType()->isFirstClassType())
5998 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00005999 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6000 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006001 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006002 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006003 Inst = CXI;
6004 return AteExtraComma ? InstExtraComma : InstNormal;
6005}
6006
6007/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006008/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6009/// 'singlethread'? AtomicOrdering
6010int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006011 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6012 bool AteExtraComma = false;
6013 AtomicOrdering Ordering = NotAtomic;
6014 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006015 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006016 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006017
6018 if (EatIfPresent(lltok::kw_volatile))
6019 isVolatile = true;
6020
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006021 switch (Lex.getKind()) {
6022 default: return TokError("expected binary operation in atomicrmw");
6023 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6024 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6025 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6026 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6027 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6028 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6029 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6030 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6031 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6032 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6033 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6034 }
6035 Lex.Lex(); // Eat the operation.
6036
6037 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6038 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6039 ParseTypeAndValue(Val, ValLoc, PFS) ||
6040 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6041 return true;
6042
6043 if (Ordering == Unordered)
6044 return TokError("atomicrmw cannot be unordered");
6045 if (!Ptr->getType()->isPointerTy())
6046 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6047 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6048 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6049 if (!Val->getType()->isIntegerTy())
6050 return Error(ValLoc, "atomicrmw operand must be an integer");
6051 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6052 if (Size < 8 || (Size & (Size - 1)))
6053 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6054 " integer");
6055
6056 AtomicRMWInst *RMWI =
6057 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6058 RMWI->setVolatile(isVolatile);
6059 Inst = RMWI;
6060 return AteExtraComma ? InstExtraComma : InstNormal;
6061}
6062
Eli Friedmanfee02c62011-07-25 23:16:38 +00006063/// ParseFence
6064/// ::= 'fence' 'singlethread'? AtomicOrdering
6065int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
6066 AtomicOrdering Ordering = NotAtomic;
6067 SynchronizationScope Scope = CrossThread;
6068 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6069 return true;
6070
6071 if (Ordering == Unordered)
6072 return TokError("fence cannot be unordered");
6073 if (Ordering == Monotonic)
6074 return TokError("fence cannot be monotonic");
6075
6076 Inst = new FenceInst(Context, Ordering, Scope);
6077 return InstNormal;
6078}
6079
Chris Lattnerac161bf2009-01-02 07:01:27 +00006080/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006081/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006082int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006083 Value *Ptr = nullptr;
6084 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006085 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006086
Dan Gohman16cbbe42009-07-29 15:58:36 +00006087 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006088
David Blaikie79e6c742015-02-27 19:29:02 +00006089 Type *Ty = nullptr;
6090 LocTy ExplicitTypeLoc = Lex.getLoc();
6091 if (ParseType(Ty) ||
6092 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6093 ParseTypeAndValue(Ptr, Loc, PFS))
6094 return true;
6095
Eli Benderskyd9806682013-04-22 17:03:42 +00006096 Type *BaseType = Ptr->getType();
6097 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6098 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006099 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006100
David Blaikie8d757942015-03-09 23:08:44 +00006101 if (Ty != BasePointerType->getElementType())
6102 return Error(ExplicitTypeLoc,
6103 "explicit pointee type doesn't match operand's pointee type");
6104
Chris Lattnerac161bf2009-01-02 07:01:27 +00006105 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006106 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006107 // GEP returns a vector of pointers if at least one of parameters is a vector.
6108 // All vector parameters should have the same vector width.
6109 unsigned GEPWidth = BaseType->isVectorTy() ?
6110 BaseType->getVectorNumElements() : 0;
6111
Chris Lattner3822f632009-01-02 08:05:26 +00006112 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006113 if (Lex.getKind() == lltok::MetadataVar) {
6114 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006115 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006116 }
Chris Lattner3822f632009-01-02 08:05:26 +00006117 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006118 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006119 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006120
Nadav Rotem3924cb02011-12-05 06:29:09 +00006121 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006122 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6123 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006124 return Error(EltLoc,
6125 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006126 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006127 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006128 Indices.push_back(Val);
6129 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006130
Craig Toppere3dcce92015-08-01 22:20:21 +00006131 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006132 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006133 return Error(Loc, "base element of getelementptr must be sized");
6134
David Blaikied33bad32015-04-17 22:32:13 +00006135 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006136 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006137 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006138 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006139 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006140 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006141}
6142
6143/// ParseExtractValue
6144/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006145int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006146 Value *Val; LocTy Loc;
6147 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006148 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006149 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006150 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006151 return true;
6152
Chris Lattner392be582010-02-12 20:49:41 +00006153 if (!Val->getType()->isAggregateType())
6154 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006155
Jay Foad57aa6362011-07-13 10:26:04 +00006156 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006157 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006158 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006159 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006160}
6161
6162/// ParseInsertValue
6163/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006164int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006165 Value *Val0, *Val1; LocTy Loc0, Loc1;
6166 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006167 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006168 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6169 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6170 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006171 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006172 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006173
Chris Lattner392be582010-02-12 20:49:41 +00006174 if (!Val0->getType()->isAggregateType())
6175 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006176
David Majnemer30074532015-02-11 07:43:58 +00006177 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6178 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006179 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006180 if (IndexedType != Val1->getType())
6181 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6182 getTypeString(Val1->getType()) + "' instead of '" +
6183 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006184 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006185 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006186}
Nick Lewycky49f89192009-04-04 07:22:01 +00006187
6188//===----------------------------------------------------------------------===//
6189// Embedded metadata.
6190//===----------------------------------------------------------------------===//
6191
6192/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006193/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006194/// Element
6195/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006196bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006197 if (ParseToken(lltok::lbrace, "expected '{' here"))
6198 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006199
Dan Gohman1e0213a2010-07-13 19:33:27 +00006200 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006201 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006202 return false;
6203
Nick Lewycky49f89192009-04-04 07:22:01 +00006204 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006205 // Null is a special case since it is typeless.
6206 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006207 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006208 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006209 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006210
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006211 Metadata *MD;
6212 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006213 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006214 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006215 } while (EatIfPresent(lltok::comma));
6216
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006217 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006218}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006219
6220//===----------------------------------------------------------------------===//
6221// Use-list order directives.
6222//===----------------------------------------------------------------------===//
6223bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6224 SMLoc Loc) {
6225 if (V->use_empty())
6226 return Error(Loc, "value has no uses");
6227
6228 unsigned NumUses = 0;
6229 SmallDenseMap<const Use *, unsigned, 16> Order;
6230 for (const Use &U : V->uses()) {
6231 if (++NumUses > Indexes.size())
6232 break;
6233 Order[&U] = Indexes[NumUses - 1];
6234 }
6235 if (NumUses < 2)
6236 return Error(Loc, "value only has one use");
6237 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6238 return Error(Loc, "wrong number of indexes, expected " +
6239 Twine(std::distance(V->use_begin(), V->use_end())));
6240
6241 V->sortUseList([&](const Use &L, const Use &R) {
6242 return Order.lookup(&L) < Order.lookup(&R);
6243 });
6244 return false;
6245}
6246
6247/// ParseUseListOrderIndexes
6248/// ::= '{' uint32 (',' uint32)+ '}'
6249bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6250 SMLoc Loc = Lex.getLoc();
6251 if (ParseToken(lltok::lbrace, "expected '{' here"))
6252 return true;
6253 if (Lex.getKind() == lltok::rbrace)
6254 return Lex.Error("expected non-empty list of uselistorder indexes");
6255
6256 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6257 // indexes should be distinct numbers in the range [0, size-1], and should
6258 // not be in order.
6259 unsigned Offset = 0;
6260 unsigned Max = 0;
6261 bool IsOrdered = true;
6262 assert(Indexes.empty() && "Expected empty order vector");
6263 do {
6264 unsigned Index;
6265 if (ParseUInt32(Index))
6266 return true;
6267
6268 // Update consistency checks.
6269 Offset += Index - Indexes.size();
6270 Max = std::max(Max, Index);
6271 IsOrdered &= Index == Indexes.size();
6272
6273 Indexes.push_back(Index);
6274 } while (EatIfPresent(lltok::comma));
6275
6276 if (ParseToken(lltok::rbrace, "expected '}' here"))
6277 return true;
6278
6279 if (Indexes.size() < 2)
6280 return Error(Loc, "expected >= 2 uselistorder indexes");
6281 if (Offset != 0 || Max >= Indexes.size())
6282 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6283 if (IsOrdered)
6284 return Error(Loc, "expected uselistorder indexes to change the order");
6285
6286 return false;
6287}
6288
6289/// ParseUseListOrder
6290/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6291bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6292 SMLoc Loc = Lex.getLoc();
6293 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6294 return true;
6295
6296 Value *V;
6297 SmallVector<unsigned, 16> Indexes;
6298 if (ParseTypeAndValue(V, PFS) ||
6299 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6300 ParseUseListOrderIndexes(Indexes))
6301 return true;
6302
6303 return sortUseListOrder(V, Indexes, Loc);
6304}
6305
6306/// ParseUseListOrderBB
6307/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6308bool LLParser::ParseUseListOrderBB() {
6309 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6310 SMLoc Loc = Lex.getLoc();
6311 Lex.Lex();
6312
6313 ValID Fn, Label;
6314 SmallVector<unsigned, 16> Indexes;
6315 if (ParseValID(Fn) ||
6316 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6317 ParseValID(Label) ||
6318 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6319 ParseUseListOrderIndexes(Indexes))
6320 return true;
6321
6322 // Check the function.
6323 GlobalValue *GV;
6324 if (Fn.Kind == ValID::t_GlobalName)
6325 GV = M->getNamedValue(Fn.StrVal);
6326 else if (Fn.Kind == ValID::t_GlobalID)
6327 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6328 else
6329 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6330 if (!GV)
6331 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6332 auto *F = dyn_cast<Function>(GV);
6333 if (!F)
6334 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6335 if (F->isDeclaration())
6336 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6337
6338 // Check the basic block.
6339 if (Label.Kind == ValID::t_LocalID)
6340 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6341 if (Label.Kind != ValID::t_LocalName)
6342 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6343 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6344 if (!V)
6345 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6346 if (!isa<BasicBlock>(V))
6347 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6348
6349 return sortUseListOrder(V, Indexes, Loc);
6350}