blob: 991cbd093322969046a03d516fa6e6ffaaf16a7d [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
Chris Lattnerad6f3352009-01-04 20:44:11 +000049 return ParseTopLevelEntities() ||
50 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000051}
52
Alex Lorenz1de2acd2015-08-21 21:32:39 +000053bool LLParser::parseStandaloneConstantValue(Constant *&C,
54 const SlotMapping *Slots) {
55 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000056 Lex.Lex();
57
58 Type *Ty = nullptr;
59 if (ParseType(Ty) || parseConstantValue(Ty, C))
60 return true;
61 if (Lex.getKind() != lltok::Eof)
62 return Error(Lex.getLoc(), "expected end of string");
63 return false;
64}
65
Alex Lorenz1de2acd2015-08-21 21:32:39 +000066void LLParser::restoreParsingState(const SlotMapping *Slots) {
67 if (!Slots)
68 return;
69 NumberedVals = Slots->GlobalValues;
70 NumberedMetadata = Slots->MetadataNodes;
71 for (const auto &I : Slots->NamedTypes)
72 NamedTypes.insert(
73 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
74 for (const auto &I : Slots->Types)
75 NumberedTypes.insert(
76 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
77}
78
Chris Lattnerac161bf2009-01-02 07:01:27 +000079/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
80/// module.
81bool LLParser::ValidateEndOfModule() {
Manman Ren209b17c2013-09-28 00:22:27 +000082 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
83 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
84
Bill Wendlingb32b0412013-02-08 06:32:06 +000085 // Handle any function attribute group forward references.
86 for (std::map<Value*, std::vector<unsigned> >::iterator
87 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
88 I != E; ++I) {
89 Value *V = I->first;
90 std::vector<unsigned> &Vec = I->second;
91 AttrBuilder B;
92
93 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
94 VI != VE; ++VI)
95 B.merge(NumberedAttrBuilders[*VI]);
96
97 if (Function *Fn = dyn_cast<Function>(V)) {
98 AttributeSet AS = Fn->getAttributes();
99 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
100 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
101 AS.getFnAttributes());
102
103 FnAttrs.merge(B);
104
105 // If the alignment was parsed as an attribute, move to the alignment
106 // field.
107 if (FnAttrs.hasAlignmentAttr()) {
108 Fn->setAlignment(FnAttrs.getAlignment());
109 FnAttrs.removeAttribute(Attribute::Alignment);
110 }
111
112 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
113 AttributeSet::get(Context,
114 AttributeSet::FunctionIndex,
115 FnAttrs));
116 Fn->setAttributes(AS);
117 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
118 AttributeSet AS = CI->getAttributes();
119 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
120 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
121 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000122 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000123 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
124 AttributeSet::get(Context,
125 AttributeSet::FunctionIndex,
126 FnAttrs));
127 CI->setAttributes(AS);
128 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
129 AttributeSet AS = II->getAttributes();
130 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
131 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
132 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000133 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000134 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
135 AttributeSet::get(Context,
136 AttributeSet::FunctionIndex,
137 FnAttrs));
138 II->setAttributes(AS);
139 } else {
140 llvm_unreachable("invalid object with forward attribute group reference");
141 }
142 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000143
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000144 // If there are entries in ForwardRefBlockAddresses at this point, the
145 // function was never defined.
146 if (!ForwardRefBlockAddresses.empty())
147 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
148 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000149
David Majnemer19b51052015-02-11 07:43:56 +0000150 for (const auto &NT : NumberedTypes)
151 if (NT.second.second.isValid())
152 return Error(NT.second.second,
153 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000154
155 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
156 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
157 if (I->second.second.isValid())
158 return Error(I->second.second,
159 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000160
David Majnemerdad0a642014-06-27 18:19:56 +0000161 if (!ForwardRefComdats.empty())
162 return Error(ForwardRefComdats.begin()->second,
163 "use of undefined comdat '$" +
164 ForwardRefComdats.begin()->first + "'");
165
Chris Lattnerac161bf2009-01-02 07:01:27 +0000166 if (!ForwardRefVals.empty())
167 return Error(ForwardRefVals.begin()->second.second,
168 "use of undefined value '@" + ForwardRefVals.begin()->first +
169 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000170
Chris Lattnerac161bf2009-01-02 07:01:27 +0000171 if (!ForwardRefValIDs.empty())
172 return Error(ForwardRefValIDs.begin()->second.second,
173 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000174 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000175
Devang Pateld2541152009-07-08 19:23:54 +0000176 if (!ForwardRefMDNodes.empty())
177 return Error(ForwardRefMDNodes.begin()->second.second,
178 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000179 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000180
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000181 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000182 for (auto &N : NumberedMetadata) {
183 if (N.second && !N.second->isResolved())
184 N.second->resolveCycles();
185 }
Devang Pateld2541152009-07-08 19:23:54 +0000186
Chris Lattnerac161bf2009-01-02 07:01:27 +0000187 // Look for intrinsic functions and CallInst that need to be upgraded
188 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000189 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000190
Manman Ren8b4306c2013-12-02 21:29:56 +0000191 UpgradeDebugInfo(*M);
192
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000193 if (!Slots)
194 return false;
195 // Initialize the slot mapping.
196 // Because by this point we've parsed and validated everything, we can "steal"
197 // the mapping from LLParser as it doesn't need it anymore.
198 Slots->GlobalValues = std::move(NumberedVals);
199 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000200 for (const auto &I : NamedTypes)
201 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
202 for (const auto &I : NumberedTypes)
203 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000204
Chris Lattnerac161bf2009-01-02 07:01:27 +0000205 return false;
206}
207
208//===----------------------------------------------------------------------===//
209// Top-Level Entities
210//===----------------------------------------------------------------------===//
211
212bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000213 while (1) {
214 switch (Lex.getKind()) {
215 default: return TokError("expected top-level entity");
216 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000217 case lltok::kw_declare: if (ParseDeclare()) return true; break;
218 case lltok::kw_define: if (ParseDefine()) return true; break;
219 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
220 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000221 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000222 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000223 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000224 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000225 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000226 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000227 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000228 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000229
230 // The Global variable production with no name can have many different
231 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000232 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000233 // OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000234 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000235 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000236 case lltok::kw_internal: // OptionalLinkage
237 case lltok::kw_weak: // OptionalLinkage
238 case lltok::kw_weak_odr: // OptionalLinkage
239 case lltok::kw_linkonce: // OptionalLinkage
240 case lltok::kw_linkonce_odr: // OptionalLinkage
241 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000242 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000243 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000244 case lltok::kw_external: // OptionalLinkage
245 case lltok::kw_default: // OptionalVisibility
246 case lltok::kw_hidden: // OptionalVisibility
247 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000248 case lltok::kw_dllimport: // OptionalDLLStorageClass
249 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000250 case lltok::kw_thread_local: // OptionalThreadLocal
251 case lltok::kw_addrspace: // OptionalAddrSpace
252 case lltok::kw_constant: // GlobalType
253 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000254 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000255 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000256 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000257 bool HasLinkage;
258 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000259 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000260 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000261 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000262 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000263 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000264 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000265 return true;
266 break;
267 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000268
269 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000270 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
271 case lltok::kw_uselistorder_bb:
272 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000273 }
274 }
275}
276
277
278/// toplevelentity
279/// ::= 'module' 'asm' STRINGCONSTANT
280bool LLParser::ParseModuleAsm() {
281 assert(Lex.getKind() == lltok::kw_module);
282 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000283
284 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000285 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
286 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000287
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000288 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000289 return false;
290}
291
292/// toplevelentity
293/// ::= 'target' 'triple' '=' STRINGCONSTANT
294/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
295bool LLParser::ParseTargetDefinition() {
296 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000297 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000298 switch (Lex.Lex()) {
299 default: return TokError("unknown target property");
300 case lltok::kw_triple:
301 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000302 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
303 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000304 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000305 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000306 return false;
307 case lltok::kw_datalayout:
308 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000309 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
310 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000311 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000312 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000313 return false;
314 }
315}
316
Bill Wendling706d3d62012-11-28 08:41:48 +0000317/// toplevelentity
318/// ::= 'deplibs' '=' '[' ']'
319/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
320/// FIXME: Remove in 4.0. Currently parse, but ignore.
321bool LLParser::ParseDepLibs() {
322 assert(Lex.getKind() == lltok::kw_deplibs);
323 Lex.Lex();
324 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
325 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
326 return true;
327
328 if (EatIfPresent(lltok::rsquare))
329 return false;
330
331 do {
332 std::string Str;
333 if (ParseStringConstant(Str)) return true;
334 } while (EatIfPresent(lltok::comma));
335
336 return ParseToken(lltok::rsquare, "expected ']' at end of list");
337}
338
Dan Gohman466876b2009-08-12 23:32:33 +0000339/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000340/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000341bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000342 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000343 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000344 Lex.Lex(); // eat LocalVarID;
345
346 if (ParseToken(lltok::equal, "expected '=' after name") ||
347 ParseToken(lltok::kw_type, "expected 'type' after '='"))
348 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000349
Craig Topper2617dcc2014-04-15 06:32:26 +0000350 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000351 if (ParseStructDefinition(TypeLoc, "",
352 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000353
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000354 if (!isa<StructType>(Result)) {
355 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
356 if (Entry.first)
357 return Error(TypeLoc, "non-struct types may not be recursive");
358 Entry.first = Result;
359 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000360 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000361
Chris Lattnerac161bf2009-01-02 07:01:27 +0000362 return false;
363}
364
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000365
Chris Lattnerac161bf2009-01-02 07:01:27 +0000366/// toplevelentity
367/// ::= LocalVar '=' 'type' type
368bool LLParser::ParseNamedType() {
369 std::string Name = Lex.getStrVal();
370 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000371 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000372
Chris Lattner3822f632009-01-02 08:05:26 +0000373 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000374 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000375 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000376
Craig Topper2617dcc2014-04-15 06:32:26 +0000377 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000378 if (ParseStructDefinition(NameLoc, Name,
379 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000380
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000381 if (!isa<StructType>(Result)) {
382 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
383 if (Entry.first)
384 return Error(NameLoc, "non-struct types may not be recursive");
385 Entry.first = Result;
386 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000387 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000388
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000389 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000390}
391
392
393/// toplevelentity
394/// ::= 'declare' FunctionHeader
395bool LLParser::ParseDeclare() {
396 assert(Lex.getKind() == lltok::kw_declare);
397 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000398
Chris Lattnerac161bf2009-01-02 07:01:27 +0000399 Function *F;
400 return ParseFunctionHeader(F, false);
401}
402
403/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000404/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000405bool LLParser::ParseDefine() {
406 assert(Lex.getKind() == lltok::kw_define);
407 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000408
Chris Lattnerac161bf2009-01-02 07:01:27 +0000409 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000410 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000411 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000412 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000413}
414
Chris Lattner3822f632009-01-02 08:05:26 +0000415/// ParseGlobalType
416/// ::= 'constant'
417/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000418bool LLParser::ParseGlobalType(bool &IsConstant) {
419 if (Lex.getKind() == lltok::kw_constant)
420 IsConstant = true;
421 else if (Lex.getKind() == lltok::kw_global)
422 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000423 else {
424 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000425 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000426 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000427 Lex.Lex();
428 return false;
429}
430
Dan Gohman466876b2009-08-12 23:32:33 +0000431/// ParseUnnamedGlobal:
432/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000433/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
434/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000435/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000436/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
437/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000438bool LLParser::ParseUnnamedGlobal() {
439 unsigned VarID = NumberedVals.size();
440 std::string Name;
441 LocTy NameLoc = Lex.getLoc();
442
443 // Handle the GlobalID form.
444 if (Lex.getKind() == lltok::GlobalID) {
445 if (Lex.getUIntVal() != VarID)
446 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000447 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000448 Lex.Lex(); // eat GlobalID;
449
450 if (ParseToken(lltok::equal, "expected '=' after name"))
451 return true;
452 }
453
454 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000455 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000456 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000457 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000458 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000459 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000460 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000461 ParseOptionalThreadLocal(TLM) ||
462 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000463 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000464
Rafael Espindola464fe022014-07-30 22:51:54 +0000465 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000466 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000467 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000468 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000469 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000470}
471
Chris Lattnerac161bf2009-01-02 07:01:27 +0000472/// ParseNamedGlobal:
473/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000474/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
475/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000476bool LLParser::ParseNamedGlobal() {
477 assert(Lex.getKind() == lltok::GlobalVar);
478 LocTy NameLoc = Lex.getLoc();
479 std::string Name = Lex.getStrVal();
480 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000481
Chris Lattnerac161bf2009-01-02 07:01:27 +0000482 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000483 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000484 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000485 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000486 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
487 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000488 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000489 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000490 ParseOptionalThreadLocal(TLM) ||
491 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000492 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000493
Rafael Espindola464fe022014-07-30 22:51:54 +0000494 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000495 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000496 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000497
498 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000499 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000500}
501
David Majnemerdad0a642014-06-27 18:19:56 +0000502bool LLParser::parseComdat() {
503 assert(Lex.getKind() == lltok::ComdatVar);
504 std::string Name = Lex.getStrVal();
505 LocTy NameLoc = Lex.getLoc();
506 Lex.Lex();
507
508 if (ParseToken(lltok::equal, "expected '=' here"))
509 return true;
510
511 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
512 return TokError("expected comdat type");
513
514 Comdat::SelectionKind SK;
515 switch (Lex.getKind()) {
516 default:
517 return TokError("unknown selection kind");
518 case lltok::kw_any:
519 SK = Comdat::Any;
520 break;
521 case lltok::kw_exactmatch:
522 SK = Comdat::ExactMatch;
523 break;
524 case lltok::kw_largest:
525 SK = Comdat::Largest;
526 break;
527 case lltok::kw_noduplicates:
528 SK = Comdat::NoDuplicates;
529 break;
530 case lltok::kw_samesize:
531 SK = Comdat::SameSize;
532 break;
533 }
534 Lex.Lex();
535
536 // See if the comdat was forward referenced, if so, use the comdat.
537 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
538 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
539 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
540 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
541
542 Comdat *C;
543 if (I != ComdatSymTab.end())
544 C = &I->second;
545 else
546 C = M->getOrInsertComdat(Name);
547 C->setSelectionKind(SK);
548
549 return false;
550}
551
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000552// MDString:
553// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000554bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000555 std::string Str;
556 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000557 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000558 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000559 return false;
560}
561
562// MDNode:
563// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000564bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000565 // !{ ..., !42, ... }
566 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000567 if (ParseUInt32(MID))
568 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000569
Chris Lattner8eff0152010-04-01 05:14:45 +0000570 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000571 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000572 Result = NumberedMetadata[MID];
573 return false;
574 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000575
Chris Lattner8eff0152010-04-01 05:14:45 +0000576 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000577 auto &FwdRef = ForwardRefMDNodes[MID];
578 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000579
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000580 Result = FwdRef.first.get();
581 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000582 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000583}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000584
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000585/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000586/// !foo = !{ !1, !2 }
587bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000588 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000589 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000590 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000591
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000592 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000593 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000594 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000595 return true;
596
Dan Gohman2637cc12010-07-21 23:38:33 +0000597 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000598 if (Lex.getKind() != lltok::rbrace)
599 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000600 if (ParseToken(lltok::exclaim, "Expected '!' here"))
601 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000602
Craig Topper2617dcc2014-04-15 06:32:26 +0000603 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000604 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000605 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000606 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000607
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000608 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000609}
610
Devang Patel39e64d42009-07-01 19:21:12 +0000611/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000612/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000613bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000614 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000615 Lex.Lex();
616 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000617
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000618 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000619 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000620 ParseToken(lltok::equal, "expected '=' here"))
621 return true;
622
623 // Detect common error, from old metadata syntax.
624 if (Lex.getKind() == lltok::Type)
625 return TokError("unexpected type in metadata definition");
626
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000627 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000628 if (Lex.getKind() == lltok::MetadataVar) {
629 if (ParseSpecializedMDNode(Init, IsDistinct))
630 return true;
631 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
632 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000633 return true;
634
Chris Lattnerfc58af22009-12-30 04:51:58 +0000635 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000636 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000637 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000638 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000639 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000640
Chris Lattnerfc58af22009-12-30 04:51:58 +0000641 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
642 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000643 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000644 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000645 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000646 }
647
Devang Patel39e64d42009-07-01 19:21:12 +0000648 return false;
649}
650
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000651static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
652 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
653 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
654}
655
Chris Lattnerac161bf2009-01-02 07:01:27 +0000656/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000657/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
658/// OptionalDLLStorageClass OptionalThreadLocal
Eric Christopher536f0a92015-05-28 23:07:39 +0000659/// OptionalUnnamedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000660///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000661/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000662/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000663///
Eric Christopher536f0a92015-05-28 23:07:39 +0000664/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000665///
Rafael Espindola464fe022014-07-30 22:51:54 +0000666bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000667 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000668 GlobalVariable::ThreadLocalMode TLM,
669 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000670 assert(Lex.getKind() == lltok::kw_alias);
671 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000672
Rafael Espindola78527052013-10-06 15:10:43 +0000673 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
674
Rafael Espindolacaa43562013-10-09 16:07:32 +0000675 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000676 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000677
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000678 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000679 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000680 "symbol with local linkage must have default visibility");
681
David Blaikie2f408302015-09-11 03:22:04 +0000682 Type *Ty;
683 LocTy ExplicitTypeLoc = Lex.getLoc();
684 if (ParseType(Ty) ||
685 ParseToken(lltok::comma, "expected comma after alias's type"))
686 return true;
687
Rafael Espindola64c1e182014-06-03 02:41:57 +0000688 Constant *Aliasee;
689 LocTy AliaseeLoc = Lex.getLoc();
690 if (Lex.getKind() != lltok::kw_bitcast &&
691 Lex.getKind() != lltok::kw_getelementptr &&
692 Lex.getKind() != lltok::kw_addrspacecast &&
693 Lex.getKind() != lltok::kw_inttoptr) {
694 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000695 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000696 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000697 // The bitcast dest type is not present, it is implied by the dest type.
698 ValID ID;
699 if (ParseValID(ID))
700 return true;
701 if (ID.Kind != ValID::t_Constant)
702 return Error(AliaseeLoc, "invalid aliasee");
703 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000704 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000705
Rafael Espindola64c1e182014-06-03 02:41:57 +0000706 Type *AliaseeType = Aliasee->getType();
707 auto *PTy = dyn_cast<PointerType>(AliaseeType);
708 if (!PTy)
709 return Error(AliaseeLoc, "An alias must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000710 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000711
David Blaikie2f408302015-09-11 03:22:04 +0000712 if (Ty != PTy->getElementType())
713 return Error(
714 ExplicitTypeLoc,
715 "explicit pointee type doesn't match operand's pointee type");
716
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000717 GlobalValue *GVal = nullptr;
718
719 // See if the alias was forward referenced, if so, prepare to replace the
720 // forward reference.
721 if (!Name.empty()) {
722 GVal = M->getNamedValue(Name);
723 if (GVal) {
724 if (!ForwardRefVals.erase(Name))
725 return Error(NameLoc, "redefinition of global '@" + Name + "'");
726 }
727 } else {
728 auto I = ForwardRefValIDs.find(NumberedVals.size());
729 if (I != ForwardRefValIDs.end()) {
730 GVal = I->second.first;
731 ForwardRefValIDs.erase(I);
732 }
733 }
734
Chris Lattnerac161bf2009-01-02 07:01:27 +0000735 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000736 std::unique_ptr<GlobalAlias> GA(
David Blaikie16a2f3e2015-09-14 18:01:59 +0000737 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
738 Name, Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000739 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000740 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000741 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000742 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000743
Rafael Espindola54fc2982015-06-17 17:53:31 +0000744 if (Name.empty())
745 NumberedVals.push_back(GA.get());
746
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000747 if (GVal) {
748 // Verify that types agree.
749 if (GVal->getType() != GA->getType())
750 return Error(
751 ExplicitTypeLoc,
752 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000753
Chris Lattnerac161bf2009-01-02 07:01:27 +0000754 // If they agree, just RAUW the old value with the alias and remove the
755 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000756 GVal->replaceAllUsesWith(GA.get());
757 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000758 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000759
Chris Lattnerac161bf2009-01-02 07:01:27 +0000760 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000761 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000762 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000763
Rafael Espindolaaa273822014-05-09 21:49:17 +0000764 // The module owns this now
765 GA.release();
766
Chris Lattnerac161bf2009-01-02 07:01:27 +0000767 return false;
768}
769
770/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000771/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000772/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000773/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000774/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000775/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000776/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000777///
Eric Christopher536f0a92015-05-28 23:07:39 +0000778/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000779/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000780///
781bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
782 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000783 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000784 GlobalVariable::ThreadLocalMode TLM,
785 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000786 if (!isValidVisibilityForLinkage(Visibility, Linkage))
787 return Error(NameLoc,
788 "symbol with local linkage must have default visibility");
789
Chris Lattnerac161bf2009-01-02 07:01:27 +0000790 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000791 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000792 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000793 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000794
Craig Topper2617dcc2014-04-15 06:32:26 +0000795 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000796 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000797 ParseOptionalToken(lltok::kw_externally_initialized,
798 IsExternallyInitialized,
799 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000800 ParseGlobalType(IsConstant) ||
801 ParseType(Ty, TyLoc))
802 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000803
Chris Lattnerac161bf2009-01-02 07:01:27 +0000804 // If the linkage is specified and is external, then no initializer is
805 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000806 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000807 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000808 Linkage != GlobalValue::ExternalLinkage)) {
809 if (ParseGlobalValue(Ty, Init))
810 return true;
811 }
812
David Majnemer49b3d9b2015-02-16 08:41:08 +0000813 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000814 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000815
David Majnemer598bd052014-12-09 05:56:09 +0000816 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000817
818 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000819 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000820 GVal = M->getNamedValue(Name);
821 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000822 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000823 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000824 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000825 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000826 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000827 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000828 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000829 ForwardRefValIDs.erase(I);
830 }
831 }
832
David Majnemer598bd052014-12-09 05:56:09 +0000833 GlobalVariable *GV;
834 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000835 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
836 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000837 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000838 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000839 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000840 return Error(TyLoc,
841 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000842
David Majnemer598bd052014-12-09 05:56:09 +0000843 GV = cast<GlobalVariable>(GVal);
844
Chris Lattnerac161bf2009-01-02 07:01:27 +0000845 // Move the forward-reference to the correct spot in the module.
846 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
847 }
848
849 if (Name.empty())
850 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000851
Chris Lattnerac161bf2009-01-02 07:01:27 +0000852 // Set the parsed properties on the global.
853 if (Init)
854 GV->setInitializer(Init);
855 GV->setConstant(IsConstant);
856 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
857 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000858 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000859 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000860 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000861 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000862
Chris Lattnerac161bf2009-01-02 07:01:27 +0000863 // Parse attributes on the global.
864 while (Lex.getKind() == lltok::comma) {
865 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000866
Chris Lattnerac161bf2009-01-02 07:01:27 +0000867 if (Lex.getKind() == lltok::kw_section) {
868 Lex.Lex();
869 GV->setSection(Lex.getStrVal());
870 if (ParseToken(lltok::StringConstant, "expected global section string"))
871 return true;
872 } else if (Lex.getKind() == lltok::kw_align) {
873 unsigned Alignment;
874 if (ParseOptionalAlignment(Alignment)) return true;
875 GV->setAlignment(Alignment);
876 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000877 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000878 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000879 return true;
880 if (C)
881 GV->setComdat(C);
882 else
883 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000884 }
885 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000886
Chris Lattnerac161bf2009-01-02 07:01:27 +0000887 return false;
888}
889
Bill Wendling63b88192013-02-06 06:52:58 +0000890/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000891/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000892bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000893 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000894 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000895 Lex.Lex();
896
David Majnemerb39e22b2014-12-09 18:33:57 +0000897 if (Lex.getKind() != lltok::AttrGrpID)
898 return TokError("expected attribute group id");
899
Bill Wendling63b88192013-02-06 06:52:58 +0000900 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000901 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000902 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000903 Lex.Lex();
904
905 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000906 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000907 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000908 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000909 ParseToken(lltok::rbrace, "expected end of attribute group"))
910 return true;
911
Bill Wendlingb32b0412013-02-08 06:32:06 +0000912 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000913 return Error(AttrGrpLoc, "attribute group has no attributes");
914
915 return false;
916}
917
Bill Wendling8b0321d2013-02-08 00:52:31 +0000918/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000919/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000920bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
921 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000922 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000923 bool HaveError = false;
924
925 B.clear();
926
Bill Wendling63b88192013-02-06 06:52:58 +0000927 while (true) {
928 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000929 if (Token == lltok::kw_builtin)
930 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000931 switch (Token) {
932 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000933 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000934 return Error(Lex.getLoc(), "unterminated attribute group");
935 case lltok::rbrace:
936 // Finished.
937 return false;
938
Bill Wendlingb32b0412013-02-08 06:32:06 +0000939 case lltok::AttrGrpID: {
940 // Allow a function to reference an attribute group:
941 //
942 // define void @foo() #1 { ... }
943 if (inAttrGrp)
944 HaveError |=
945 Error(Lex.getLoc(),
946 "cannot have an attribute group reference in an attribute group");
947
948 unsigned AttrGrpNum = Lex.getUIntVal();
949 if (inAttrGrp) break;
950
951 // Save the reference to the attribute group. We'll fill it in later.
952 FwdRefAttrGrps.push_back(AttrGrpNum);
953 break;
954 }
Bill Wendling63b88192013-02-06 06:52:58 +0000955 // Target-dependent attributes:
956 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +0000957 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +0000958 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000959 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000960 }
961
962 // Target-independent attributes:
963 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000964 // As a hack, we allow function alignment to be initially parsed as an
965 // attribute on a function declaration/definition or added to an attribute
966 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000967 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000968 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000969 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000970 if (ParseToken(lltok::equal, "expected '=' here") ||
971 ParseUInt32(Alignment))
972 return true;
973 } else {
974 if (ParseOptionalAlignment(Alignment))
975 return true;
976 }
Bill Wendling63b88192013-02-06 06:52:58 +0000977 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000978 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000979 }
980 case lltok::kw_alignstack: {
981 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000982 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000983 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000984 if (ParseToken(lltok::equal, "expected '=' here") ||
985 ParseUInt32(Alignment))
986 return true;
987 } else {
988 if (ParseOptionalStackAlignment(Alignment))
989 return true;
990 }
Bill Wendling63b88192013-02-06 06:52:58 +0000991 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000992 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000993 }
Igor Laevsky39d662f2015-07-11 10:30:36 +0000994 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
995 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
996 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
997 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
998 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +0000999 case lltok::kw_inaccessiblememonly:
1000 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1001 case lltok::kw_inaccessiblemem_or_argmemonly:
1002 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001003 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1004 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1005 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1006 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1007 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1008 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1009 case lltok::kw_noimplicitfloat:
1010 B.addAttribute(Attribute::NoImplicitFloat); break;
1011 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1012 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1013 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1014 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001015 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001016 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1017 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1018 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1019 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1020 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1021 case lltok::kw_returns_twice:
1022 B.addAttribute(Attribute::ReturnsTwice); break;
1023 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1024 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1025 case lltok::kw_sspstrong:
1026 B.addAttribute(Attribute::StackProtectStrong); break;
1027 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1028 case lltok::kw_sanitize_address:
1029 B.addAttribute(Attribute::SanitizeAddress); break;
1030 case lltok::kw_sanitize_thread:
1031 B.addAttribute(Attribute::SanitizeThread); break;
1032 case lltok::kw_sanitize_memory:
1033 B.addAttribute(Attribute::SanitizeMemory); break;
1034 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001035
1036 // Error handling.
1037 case lltok::kw_inreg:
1038 case lltok::kw_signext:
1039 case lltok::kw_zeroext:
1040 HaveError |=
1041 Error(Lex.getLoc(),
1042 "invalid use of attribute on a function");
1043 break;
1044 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001045 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001046 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001047 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001048 case lltok::kw_nest:
1049 case lltok::kw_noalias:
1050 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001051 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001052 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001053 case lltok::kw_sret:
1054 HaveError |=
1055 Error(Lex.getLoc(),
1056 "invalid use of parameter-only attribute on a function");
1057 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001058 }
1059
1060 Lex.Lex();
1061 }
1062}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001063
1064//===----------------------------------------------------------------------===//
1065// GlobalValue Reference/Resolution Routines.
1066//===----------------------------------------------------------------------===//
1067
Karl Schimpf77729782015-09-03 18:06:44 +00001068static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1069 const std::string &Name) {
1070 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1071 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1072 else
1073 return new GlobalVariable(*M, PTy->getElementType(), false,
1074 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1075 nullptr, GlobalVariable::NotThreadLocal,
1076 PTy->getAddressSpace());
1077}
1078
Chris Lattnerac161bf2009-01-02 07:01:27 +00001079/// GetGlobalVal - Get a value with the specified name or ID, creating a
1080/// forward reference record if needed. This can return null if the value
1081/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001082GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001083 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001084 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001085 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001086 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001087 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001088 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001089
Chris Lattnerac161bf2009-01-02 07:01:27 +00001090 // Look this name up in the normal function symbol table.
1091 GlobalValue *Val =
1092 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001093
Chris Lattnerac161bf2009-01-02 07:01:27 +00001094 // If this is a forward reference for the value, see if we already created a
1095 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001096 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001097 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001098 if (I != ForwardRefVals.end())
1099 Val = I->second.first;
1100 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001101
Chris Lattnerac161bf2009-01-02 07:01:27 +00001102 // If we have the value in the symbol table or fwd-ref table, return it.
1103 if (Val) {
1104 if (Val->getType() == Ty) return Val;
1105 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001106 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001107 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001108 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001109
Chris Lattnerac161bf2009-01-02 07:01:27 +00001110 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001111 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001112 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1113 return FwdVal;
1114}
1115
Chris Lattner229907c2011-07-18 04:54:35 +00001116GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1117 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001118 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001119 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001120 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001121 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001122
Craig Topper2617dcc2014-04-15 06:32:26 +00001123 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001124
Chris Lattnerac161bf2009-01-02 07:01:27 +00001125 // If this is a forward reference for the value, see if we already created a
1126 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001127 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001128 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001129 if (I != ForwardRefValIDs.end())
1130 Val = I->second.first;
1131 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001132
Chris Lattnerac161bf2009-01-02 07:01:27 +00001133 // If we have the value in the symbol table or fwd-ref table, return it.
1134 if (Val) {
1135 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001136 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001137 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001138 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001139 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001140
Chris Lattnerac161bf2009-01-02 07:01:27 +00001141 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001142 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001143 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1144 return FwdVal;
1145}
1146
1147
1148//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001149// Comdat Reference/Resolution Routines.
1150//===----------------------------------------------------------------------===//
1151
1152Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1153 // Look this name up in the comdat symbol table.
1154 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1155 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1156 if (I != ComdatSymTab.end())
1157 return &I->second;
1158
1159 // Otherwise, create a new forward reference for this value and remember it.
1160 Comdat *C = M->getOrInsertComdat(Name);
1161 ForwardRefComdats[Name] = Loc;
1162 return C;
1163}
1164
1165
1166//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001167// Helper Routines.
1168//===----------------------------------------------------------------------===//
1169
1170/// ParseToken - If the current token has the specified kind, eat it and return
1171/// success. Otherwise, emit the specified error and return failure.
1172bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1173 if (Lex.getKind() != T)
1174 return TokError(ErrMsg);
1175 Lex.Lex();
1176 return false;
1177}
1178
Chris Lattner3822f632009-01-02 08:05:26 +00001179/// ParseStringConstant
1180/// ::= StringConstant
1181bool LLParser::ParseStringConstant(std::string &Result) {
1182 if (Lex.getKind() != lltok::StringConstant)
1183 return TokError("expected string constant");
1184 Result = Lex.getStrVal();
1185 Lex.Lex();
1186 return false;
1187}
1188
1189/// ParseUInt32
1190/// ::= uint32
1191bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001192 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1193 return TokError("expected integer");
1194 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1195 if (Val64 != unsigned(Val64))
1196 return TokError("expected 32-bit integer (too large)");
1197 Val = Val64;
1198 Lex.Lex();
1199 return false;
1200}
1201
Hal Finkelb0407ba2014-07-18 15:51:28 +00001202/// ParseUInt64
1203/// ::= uint64
1204bool LLParser::ParseUInt64(uint64_t &Val) {
1205 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1206 return TokError("expected integer");
1207 Val = Lex.getAPSIntVal().getLimitedValue();
1208 Lex.Lex();
1209 return false;
1210}
1211
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001212/// ParseTLSModel
1213/// := 'localdynamic'
1214/// := 'initialexec'
1215/// := 'localexec'
1216bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1217 switch (Lex.getKind()) {
1218 default:
1219 return TokError("expected localdynamic, initialexec or localexec");
1220 case lltok::kw_localdynamic:
1221 TLM = GlobalVariable::LocalDynamicTLSModel;
1222 break;
1223 case lltok::kw_initialexec:
1224 TLM = GlobalVariable::InitialExecTLSModel;
1225 break;
1226 case lltok::kw_localexec:
1227 TLM = GlobalVariable::LocalExecTLSModel;
1228 break;
1229 }
1230
1231 Lex.Lex();
1232 return false;
1233}
1234
1235/// ParseOptionalThreadLocal
1236/// := /*empty*/
1237/// := 'thread_local'
1238/// := 'thread_local' '(' tlsmodel ')'
1239bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1240 TLM = GlobalVariable::NotThreadLocal;
1241 if (!EatIfPresent(lltok::kw_thread_local))
1242 return false;
1243
1244 TLM = GlobalVariable::GeneralDynamicTLSModel;
1245 if (Lex.getKind() == lltok::lparen) {
1246 Lex.Lex();
1247 return ParseTLSModel(TLM) ||
1248 ParseToken(lltok::rparen, "expected ')' after thread local model");
1249 }
1250 return false;
1251}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001252
1253/// ParseOptionalAddrSpace
1254/// := /*empty*/
1255/// := 'addrspace' '(' uint32 ')'
1256bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1257 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001258 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001259 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001260 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001261 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001262 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001263}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001264
Artur Pilipenko17376c42015-08-03 14:31:49 +00001265/// ParseStringAttribute
1266/// := StringConstant
1267/// := StringConstant '=' StringConstant
1268bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1269 std::string Attr = Lex.getStrVal();
1270 Lex.Lex();
1271 std::string Val;
1272 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1273 return true;
1274 B.addAttribute(Attr, Val);
1275 return false;
1276}
1277
Bill Wendling34c2eb22012-12-04 23:40:58 +00001278/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1279bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1280 bool HaveError = false;
1281
1282 B.clear();
1283
1284 while (1) {
1285 lltok::Kind Token = Lex.getKind();
1286 switch (Token) {
1287 default: // End of attributes.
1288 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001289 case lltok::StringConstant: {
1290 if (ParseStringAttribute(B))
1291 return true;
1292 continue;
1293 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001294 case lltok::kw_align: {
1295 unsigned Alignment;
1296 if (ParseOptionalAlignment(Alignment))
1297 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001298 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001299 continue;
1300 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001301 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001302 case lltok::kw_dereferenceable: {
1303 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001304 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001305 return true;
1306 B.addDereferenceableAttr(Bytes);
1307 continue;
1308 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001309 case lltok::kw_dereferenceable_or_null: {
1310 uint64_t Bytes;
1311 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1312 return true;
1313 B.addDereferenceableOrNullAttr(Bytes);
1314 continue;
1315 }
Reid Klecknera534a382013-12-19 02:14:12 +00001316 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001317 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1318 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1319 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1320 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001321 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001322 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1323 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001324 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001325 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1326 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1327 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001328
Stephen Lin7577ed52013-04-20 13:16:13 +00001329 case lltok::kw_alignstack:
1330 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001331 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001332 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001333 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001334 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001335 case lltok::kw_minsize:
1336 case lltok::kw_naked:
1337 case lltok::kw_nobuiltin:
1338 case lltok::kw_noduplicate:
1339 case lltok::kw_noimplicitfloat:
1340 case lltok::kw_noinline:
1341 case lltok::kw_nonlazybind:
1342 case lltok::kw_noredzone:
1343 case lltok::kw_noreturn:
1344 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001345 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001346 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001347 case lltok::kw_returns_twice:
1348 case lltok::kw_sanitize_address:
1349 case lltok::kw_sanitize_memory:
1350 case lltok::kw_sanitize_thread:
1351 case lltok::kw_ssp:
1352 case lltok::kw_sspreq:
1353 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001354 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001355 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001356 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1357 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001358 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001359
Bill Wendling34c2eb22012-12-04 23:40:58 +00001360 Lex.Lex();
1361 }
1362}
1363
1364/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1365bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1366 bool HaveError = false;
1367
1368 B.clear();
1369
1370 while (1) {
1371 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001372 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001373 default: // End of attributes.
1374 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001375 case lltok::StringConstant: {
1376 if (ParseStringAttribute(B))
1377 return true;
1378 continue;
1379 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001380 case lltok::kw_dereferenceable: {
1381 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001382 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001383 return true;
1384 B.addDereferenceableAttr(Bytes);
1385 continue;
1386 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001387 case lltok::kw_dereferenceable_or_null: {
1388 uint64_t Bytes;
1389 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1390 return true;
1391 B.addDereferenceableOrNullAttr(Bytes);
1392 continue;
1393 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001394 case lltok::kw_align: {
1395 unsigned Alignment;
1396 if (ParseOptionalAlignment(Alignment))
1397 return true;
1398 B.addAlignmentAttr(Alignment);
1399 continue;
1400 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001401 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1402 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001403 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001404 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1405 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001406
Bill Wendling34c2eb22012-12-04 23:40:58 +00001407 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001408 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001409 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001410 case lltok::kw_nest:
1411 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001412 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001413 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001414 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001415 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001416
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001417 case lltok::kw_alignstack:
1418 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001419 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001420 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001421 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001422 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001423 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001424 case lltok::kw_minsize:
1425 case lltok::kw_naked:
1426 case lltok::kw_nobuiltin:
1427 case lltok::kw_noduplicate:
1428 case lltok::kw_noimplicitfloat:
1429 case lltok::kw_noinline:
1430 case lltok::kw_nonlazybind:
1431 case lltok::kw_noredzone:
1432 case lltok::kw_noreturn:
1433 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001434 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001435 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001436 case lltok::kw_returns_twice:
1437 case lltok::kw_sanitize_address:
1438 case lltok::kw_sanitize_memory:
1439 case lltok::kw_sanitize_thread:
1440 case lltok::kw_ssp:
1441 case lltok::kw_sspreq:
1442 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001443 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001444 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001445 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001446 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001447
1448 case lltok::kw_readnone:
1449 case lltok::kw_readonly:
1450 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001451 }
1452
Chris Lattnerac161bf2009-01-02 07:01:27 +00001453 Lex.Lex();
1454 }
1455}
1456
1457/// ParseOptionalLinkage
1458/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001459/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001460/// ::= 'internal'
1461/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001462/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001463/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001464/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001465/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001466/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001467/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001468/// ::= 'extern_weak'
1469/// ::= 'external'
1470bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1471 HasLinkage = false;
1472 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001473 default: Res=GlobalValue::ExternalLinkage; return false;
1474 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001475 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1476 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1477 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1478 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1479 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001480 case lltok::kw_available_externally:
1481 Res = GlobalValue::AvailableExternallyLinkage;
1482 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001483 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001484 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001485 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1486 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001487 }
1488 Lex.Lex();
1489 HasLinkage = true;
1490 return false;
1491}
1492
1493/// ParseOptionalVisibility
1494/// ::= /*empty*/
1495/// ::= 'default'
1496/// ::= 'hidden'
1497/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001498///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001499bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1500 switch (Lex.getKind()) {
1501 default: Res = GlobalValue::DefaultVisibility; return false;
1502 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1503 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1504 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1505 }
1506 Lex.Lex();
1507 return false;
1508}
1509
Nico Rieck7157bb72014-01-14 15:22:47 +00001510/// ParseOptionalDLLStorageClass
1511/// ::= /*empty*/
1512/// ::= 'dllimport'
1513/// ::= 'dllexport'
1514///
1515bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1516 switch (Lex.getKind()) {
1517 default: Res = GlobalValue::DefaultStorageClass; return false;
1518 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1519 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1520 }
1521 Lex.Lex();
1522 return false;
1523}
1524
Chris Lattnerac161bf2009-01-02 07:01:27 +00001525/// ParseOptionalCallingConv
1526/// ::= /*empty*/
1527/// ::= 'ccc'
1528/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001529/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001530/// ::= 'coldcc'
1531/// ::= 'x86_stdcallcc'
1532/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001533/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001534/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001535/// ::= 'arm_apcscc'
1536/// ::= 'arm_aapcscc'
1537/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001538/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001539/// ::= 'ptx_kernel'
1540/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001541/// ::= 'spir_func'
1542/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001543/// ::= 'x86_64_sysvcc'
1544/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001545/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001546/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001547/// ::= 'preserve_mostcc'
1548/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001549/// ::= 'ghccc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001550/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001551/// ::= 'hhvmcc'
1552/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001553/// ::= 'cxx_fast_tlscc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001554/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001555///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001556bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001557 switch (Lex.getKind()) {
1558 default: CC = CallingConv::C; return false;
1559 case lltok::kw_ccc: CC = CallingConv::C; break;
1560 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1561 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1562 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1563 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001564 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001565 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001566 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1567 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1568 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001569 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001570 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1571 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001572 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1573 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001574 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001575 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1576 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001577 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001578 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001579 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1580 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001581 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001582 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001583 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1584 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001585 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001586 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001587 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001588 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001589 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001590 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001591
Chris Lattnerac161bf2009-01-02 07:01:27 +00001592 Lex.Lex();
1593 return false;
1594}
1595
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001596/// ParseMetadataAttachment
1597/// ::= !dbg !42
1598bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1599 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1600
1601 std::string Name = Lex.getStrVal();
1602 Kind = M->getMDKindID(Name);
1603 Lex.Lex();
1604
1605 return ParseMDNode(MD);
1606}
1607
Chris Lattner5c427632009-12-30 05:31:19 +00001608/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001609/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001610bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001611 do {
1612 if (Lex.getKind() != lltok::MetadataVar)
1613 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001614
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001615 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001616 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001617 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001618 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001619
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001620 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001621 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001622 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001623
Chris Lattner596760d2009-12-29 21:25:40 +00001624 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001625 } while (EatIfPresent(lltok::comma));
1626 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001627}
1628
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001629/// ParseOptionalFunctionMetadata
1630/// ::= (!dbg !57)*
1631bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1632 while (Lex.getKind() == lltok::MetadataVar) {
1633 unsigned MDK;
1634 MDNode *N;
1635 if (ParseMetadataAttachment(MDK, N))
1636 return true;
1637
1638 F.setMetadata(MDK, N);
1639 }
1640 return false;
1641}
1642
Chris Lattnerac161bf2009-01-02 07:01:27 +00001643/// ParseOptionalAlignment
1644/// ::= /* empty */
1645/// ::= 'align' 4
1646bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1647 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001648 if (!EatIfPresent(lltok::kw_align))
1649 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001650 LocTy AlignLoc = Lex.getLoc();
1651 if (ParseUInt32(Alignment)) return true;
1652 if (!isPowerOf2_32(Alignment))
1653 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001654 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001655 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001656 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001657}
1658
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001659/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001660/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001661/// ::= AttrKind '(' 4 ')'
1662///
1663/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1664bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1665 uint64_t &Bytes) {
1666 assert((AttrKind == lltok::kw_dereferenceable ||
1667 AttrKind == lltok::kw_dereferenceable_or_null) &&
1668 "contract!");
1669
Hal Finkelb0407ba2014-07-18 15:51:28 +00001670 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001671 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001672 return false;
1673 LocTy ParenLoc = Lex.getLoc();
1674 if (!EatIfPresent(lltok::lparen))
1675 return Error(ParenLoc, "expected '('");
1676 LocTy DerefLoc = Lex.getLoc();
1677 if (ParseUInt64(Bytes)) return true;
1678 ParenLoc = Lex.getLoc();
1679 if (!EatIfPresent(lltok::rparen))
1680 return Error(ParenLoc, "expected ')'");
1681 if (!Bytes)
1682 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1683 return false;
1684}
1685
Chris Lattnerb2f39502009-12-30 05:44:30 +00001686/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001687/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001688/// ::= ',' align 4
1689///
1690/// This returns with AteExtraComma set to true if it ate an excess comma at the
1691/// end.
1692bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1693 bool &AteExtraComma) {
1694 AteExtraComma = false;
1695 while (EatIfPresent(lltok::comma)) {
1696 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001697 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001698 AteExtraComma = true;
1699 return false;
1700 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001701
Chris Lattner95b0ff42010-04-23 00:50:50 +00001702 if (Lex.getKind() != lltok::kw_align)
1703 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001704
Chris Lattner95b0ff42010-04-23 00:50:50 +00001705 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001706 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001707
Devang Patelea8a4b92009-09-17 23:04:48 +00001708 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001709}
1710
Eli Friedmanfee02c62011-07-25 23:16:38 +00001711/// ParseScopeAndOrdering
1712/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1713/// else: ::=
1714///
1715/// This sets Scope and Ordering to the parsed values.
1716bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1717 AtomicOrdering &Ordering) {
1718 if (!isAtomic)
1719 return false;
1720
1721 Scope = CrossThread;
1722 if (EatIfPresent(lltok::kw_singlethread))
1723 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001724
1725 return ParseOrdering(Ordering);
1726}
1727
1728/// ParseOrdering
1729/// ::= AtomicOrdering
1730///
1731/// This sets Ordering to the parsed value.
1732bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001733 switch (Lex.getKind()) {
1734 default: return TokError("Expected ordering on atomic instruction");
1735 case lltok::kw_unordered: Ordering = Unordered; break;
1736 case lltok::kw_monotonic: Ordering = Monotonic; break;
1737 case lltok::kw_acquire: Ordering = Acquire; break;
1738 case lltok::kw_release: Ordering = Release; break;
1739 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1740 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1741 }
1742 Lex.Lex();
1743 return false;
1744}
1745
Charles Davisbe5557e2010-02-12 00:31:15 +00001746/// ParseOptionalStackAlignment
1747/// ::= /* empty */
1748/// ::= 'alignstack' '(' 4 ')'
1749bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1750 Alignment = 0;
1751 if (!EatIfPresent(lltok::kw_alignstack))
1752 return false;
1753 LocTy ParenLoc = Lex.getLoc();
1754 if (!EatIfPresent(lltok::lparen))
1755 return Error(ParenLoc, "expected '('");
1756 LocTy AlignLoc = Lex.getLoc();
1757 if (ParseUInt32(Alignment)) return true;
1758 ParenLoc = Lex.getLoc();
1759 if (!EatIfPresent(lltok::rparen))
1760 return Error(ParenLoc, "expected ')'");
1761 if (!isPowerOf2_32(Alignment))
1762 return Error(AlignLoc, "stack alignment is not a power of two");
1763 return false;
1764}
Devang Patelea8a4b92009-09-17 23:04:48 +00001765
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001766/// ParseIndexList - This parses the index list for an insert/extractvalue
1767/// instruction. This sets AteExtraComma in the case where we eat an extra
1768/// comma at the end of the line and find that it is followed by metadata.
1769/// Clients that don't allow metadata can call the version of this function that
1770/// only takes one argument.
1771///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001772/// ParseIndexList
1773/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001774///
1775bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1776 bool &AteExtraComma) {
1777 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001778
Chris Lattnerac161bf2009-01-02 07:01:27 +00001779 if (Lex.getKind() != lltok::comma)
1780 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001781
Chris Lattner3822f632009-01-02 08:05:26 +00001782 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001783 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001784 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001785 AteExtraComma = true;
1786 return false;
1787 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001788 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001789 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001790 Indices.push_back(Idx);
1791 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001792
Chris Lattnerac161bf2009-01-02 07:01:27 +00001793 return false;
1794}
1795
1796//===----------------------------------------------------------------------===//
1797// Type Parsing.
1798//===----------------------------------------------------------------------===//
1799
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001800/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001801bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001802 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001803 switch (Lex.getKind()) {
1804 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001805 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001806 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001807 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001808 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001809 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001810 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001811 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001812 // Type ::= StructType
1813 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001814 return true;
1815 break;
1816 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001817 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001818 Lex.Lex(); // eat the lsquare.
1819 if (ParseArrayVectorType(Result, false))
1820 return true;
1821 break;
1822 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001823 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001824 Lex.Lex();
1825 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001826 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001827 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001828 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001829 } else if (ParseArrayVectorType(Result, true))
1830 return true;
1831 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001832 case lltok::LocalVar: {
1833 // Type ::= %foo
1834 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001835
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001836 // If the type hasn't been defined yet, create a forward definition and
1837 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001838 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001839 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001840 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001841 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001842 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001843 Lex.Lex();
1844 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001845 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001846
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001847 case lltok::LocalVarID: {
1848 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001849 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001850
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001851 // If the type hasn't been defined yet, create a forward definition and
1852 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001853 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001854 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001855 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001856 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001857 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001858 Lex.Lex();
1859 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001860 }
1861 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001862
1863 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001864 while (1) {
1865 switch (Lex.getKind()) {
1866 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001867 default:
1868 if (!AllowVoid && Result->isVoidTy())
1869 return Error(TypeLoc, "void type only allowed for function results");
1870 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001871
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001872 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001873 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001874 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001875 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001876 if (Result->isVoidTy())
1877 return TokError("pointers to void are invalid - use i8* instead");
1878 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001879 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001880 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001881 Lex.Lex();
1882 break;
1883
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001884 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001885 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001886 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001887 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001888 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001889 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001890 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001891 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001892 unsigned AddrSpace;
1893 if (ParseOptionalAddrSpace(AddrSpace) ||
1894 ParseToken(lltok::star, "expected '*' in address space"))
1895 return true;
1896
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001897 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001898 break;
1899 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001900
Chris Lattnerac161bf2009-01-02 07:01:27 +00001901 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1902 case lltok::lparen:
1903 if (ParseFunctionType(Result))
1904 return true;
1905 break;
1906 }
1907 }
1908}
1909
1910/// ParseParameterList
1911/// ::= '(' ')'
1912/// ::= '(' Arg (',' Arg)* ')'
1913/// Arg
1914/// ::= Type OptionalAttributes Value OptionalAttributes
1915bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001916 PerFunctionState &PFS, bool IsMustTailCall,
1917 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001918 if (ParseToken(lltok::lparen, "expected '(' in call"))
1919 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001920
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001921 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001922 while (Lex.getKind() != lltok::rparen) {
1923 // If this isn't the first argument, we need a comma.
1924 if (!ArgList.empty() &&
1925 ParseToken(lltok::comma, "expected ',' in argument list"))
1926 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001927
Reid Kleckner83498642014-08-26 00:33:28 +00001928 // Parse an ellipsis if this is a musttail call in a variadic function.
1929 if (Lex.getKind() == lltok::dotdotdot) {
1930 const char *Msg = "unexpected ellipsis in argument list for ";
1931 if (!IsMustTailCall)
1932 return TokError(Twine(Msg) + "non-musttail call");
1933 if (!InVarArgsFunc)
1934 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1935 Lex.Lex(); // Lex the '...', it is purely for readability.
1936 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1937 }
1938
Chris Lattnerac161bf2009-01-02 07:01:27 +00001939 // Parse the argument.
1940 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001941 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001942 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001943 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001944 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001945 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001946
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001947 if (ArgTy->isMetadataTy()) {
1948 if (ParseMetadataAsValue(V, PFS))
1949 return true;
1950 } else {
1951 // Otherwise, handle normal operands.
1952 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1953 return true;
1954 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001955 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1956 AttrIndex++,
1957 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001958 }
1959
Reid Kleckner83498642014-08-26 00:33:28 +00001960 if (IsMustTailCall && InVarArgsFunc)
1961 return TokError("expected '...' at end of argument list for musttail call "
1962 "in varargs function");
1963
Chris Lattnerac161bf2009-01-02 07:01:27 +00001964 Lex.Lex(); // Lex the ')'.
1965 return false;
1966}
1967
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001968/// ParseOptionalOperandBundles
1969/// ::= /*empty*/
1970/// ::= '[' OperandBundle [, OperandBundle ]* ']'
1971///
1972/// OperandBundle
1973/// ::= bundle-tag '(' ')'
1974/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
1975///
1976/// bundle-tag ::= String Constant
1977bool LLParser::ParseOptionalOperandBundles(
1978 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
1979 LocTy BeginLoc = Lex.getLoc();
1980 if (!EatIfPresent(lltok::lsquare))
1981 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001982
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001983 while (Lex.getKind() != lltok::rsquare) {
1984 // If this isn't the first operand bundle, we need a comma.
1985 if (!BundleList.empty() &&
1986 ParseToken(lltok::comma, "expected ',' in input list"))
1987 return true;
1988
1989 std::string Tag;
1990 if (ParseStringConstant(Tag))
1991 return true;
1992
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001993 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
1994 return true;
1995
Sanjoy Dasf79d3442015-11-18 08:30:07 +00001996 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001997 while (Lex.getKind() != lltok::rparen) {
1998 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00001999 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002000 ParseToken(lltok::comma, "expected ',' in input list"))
2001 return true;
2002
2003 Type *Ty = nullptr;
2004 Value *Input = nullptr;
2005 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2006 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002007 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002008 }
2009
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002010 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2011
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002012 Lex.Lex(); // Lex the ')'.
2013 }
2014
2015 if (BundleList.empty())
2016 return Error(BeginLoc, "operand bundle set must not be empty");
2017
2018 Lex.Lex(); // Lex the ']'.
2019 return false;
2020}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002021
Chris Lattner2ed06b42009-01-05 18:34:07 +00002022/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002023/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002024/// ::= '(' ArgTypeListI ')'
2025/// ArgTypeListI
2026/// ::= /*empty*/
2027/// ::= '...'
2028/// ::= ArgTypeList ',' '...'
2029/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002030///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002031bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2032 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002033 isVarArg = false;
2034 assert(Lex.getKind() == lltok::lparen);
2035 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002036
Chris Lattnerac161bf2009-01-02 07:01:27 +00002037 if (Lex.getKind() == lltok::rparen) {
2038 // empty
2039 } else if (Lex.getKind() == lltok::dotdotdot) {
2040 isVarArg = true;
2041 Lex.Lex();
2042 } else {
2043 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002044 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002045 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002046 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002047
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002048 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002049 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002050
Chris Lattnerfdd87902009-10-05 05:54:46 +00002051 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002052 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002053
Chris Lattnerdef19492011-06-17 06:36:20 +00002054 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002055 Name = Lex.getStrVal();
2056 Lex.Lex();
2057 }
Chris Lattner3822f632009-01-02 08:05:26 +00002058
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002059 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002060 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002061
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002062 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002063 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2064 AttrIndex++, Attrs),
2065 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002066
Chris Lattner3822f632009-01-02 08:05:26 +00002067 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002068 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002069 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002070 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002071 break;
2072 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002073
Chris Lattnerac161bf2009-01-02 07:01:27 +00002074 // Otherwise must be an argument type.
2075 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002076 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002077
Chris Lattnerfdd87902009-10-05 05:54:46 +00002078 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002079 return Error(TypeLoc, "argument can not have void type");
2080
Chris Lattnerdef19492011-06-17 06:36:20 +00002081 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002082 Name = Lex.getStrVal();
2083 Lex.Lex();
2084 } else {
2085 Name = "";
2086 }
Chris Lattner3822f632009-01-02 08:05:26 +00002087
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002088 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002089 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002090
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002091 ArgList.emplace_back(
2092 TypeLoc, ArgTy,
2093 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2094 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002095 }
2096 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002097
Chris Lattner3822f632009-01-02 08:05:26 +00002098 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002099}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002100
Chris Lattnerac161bf2009-01-02 07:01:27 +00002101/// ParseFunctionType
2102/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002103bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002104 assert(Lex.getKind() == lltok::lparen);
2105
Chris Lattnerce473c72009-01-05 08:04:33 +00002106 if (!FunctionType::isValidReturnType(Result))
2107 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002108
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002109 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002110 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002111 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002112 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002113
Chris Lattnerac161bf2009-01-02 07:01:27 +00002114 // Reject names on the arguments lists.
2115 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2116 if (!ArgList[i].Name.empty())
2117 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002118 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002119 return Error(ArgList[i].Loc,
2120 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002121 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002122
Jay Foadb804a2b2011-07-12 14:06:48 +00002123 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002124 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002125 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002126
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002127 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002128 return false;
2129}
2130
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002131/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2132/// other structs.
2133bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2134 SmallVector<Type*, 8> Elts;
2135 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002136
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002137 Result = StructType::get(Context, Elts, Packed);
2138 return false;
2139}
2140
2141/// ParseStructDefinition - Parse a struct in a 'type' definition.
2142bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2143 std::pair<Type*, LocTy> &Entry,
2144 Type *&ResultTy) {
2145 // If the type was already defined, diagnose the redefinition.
2146 if (Entry.first && !Entry.second.isValid())
2147 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002148
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002149 // If we have opaque, just return without filling in the definition for the
2150 // struct. This counts as a definition as far as the .ll file goes.
2151 if (EatIfPresent(lltok::kw_opaque)) {
2152 // This type is being defined, so clear the location to indicate this.
2153 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002154
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002155 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002156 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002157 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002158 ResultTy = Entry.first;
2159 return false;
2160 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002161
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002162 // If the type starts with '<', then it is either a packed struct or a vector.
2163 bool isPacked = EatIfPresent(lltok::less);
2164
2165 // If we don't have a struct, then we have a random type alias, which we
2166 // accept for compatibility with old files. These types are not allowed to be
2167 // forward referenced and not allowed to be recursive.
2168 if (Lex.getKind() != lltok::lbrace) {
2169 if (Entry.first)
2170 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002171
Craig Topper2617dcc2014-04-15 06:32:26 +00002172 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002173 if (isPacked)
2174 return ParseArrayVectorType(ResultTy, true);
2175 return ParseType(ResultTy);
2176 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002177
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002178 // This type is being defined, so clear the location to indicate this.
2179 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002180
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002181 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002182 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002183 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002184
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002185 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002186
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002187 SmallVector<Type*, 8> Body;
2188 if (ParseStructBody(Body) ||
2189 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2190 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002191
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002192 STy->setBody(Body, isPacked);
2193 ResultTy = STy;
2194 return false;
2195}
2196
2197
Chris Lattnerac161bf2009-01-02 07:01:27 +00002198/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002199/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002200/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002201/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002202/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002203/// ::= '<' '{' Type (',' Type)* '}' '>'
2204bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002205 assert(Lex.getKind() == lltok::lbrace);
2206 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002207
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002208 // Handle the empty struct.
2209 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002210 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002211
Chris Lattnerf880ca22009-03-09 04:49:14 +00002212 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002213 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002214 if (ParseType(Ty)) return true;
2215 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002216
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002217 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002218 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002219
Chris Lattner3822f632009-01-02 08:05:26 +00002220 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002221 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002222 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002223
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002224 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002225 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002226
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002227 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002228 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002229
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002230 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002231}
2232
2233/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2234/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002235/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002236/// ::= '[' APSINTVAL 'x' Types ']'
2237/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002238bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002239 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2240 Lex.getAPSIntVal().getBitWidth() > 64)
2241 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002242
Chris Lattnerac161bf2009-01-02 07:01:27 +00002243 LocTy SizeLoc = Lex.getLoc();
2244 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002245 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002246
Chris Lattner3822f632009-01-02 08:05:26 +00002247 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2248 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002249
2250 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002251 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002252 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002253
Chris Lattner3822f632009-01-02 08:05:26 +00002254 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2255 "expected end of sequential type"))
2256 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002257
Chris Lattnerac161bf2009-01-02 07:01:27 +00002258 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002259 if (Size == 0)
2260 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002261 if ((unsigned)Size != Size)
2262 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002263 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002264 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002265 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002266 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002267 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002268 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002269 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002270 }
2271 return false;
2272}
2273
2274//===----------------------------------------------------------------------===//
2275// Function Semantic Analysis.
2276//===----------------------------------------------------------------------===//
2277
Chris Lattner3432c622009-10-28 03:39:23 +00002278LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2279 int functionNumber)
2280 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002281
2282 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002283 for (Argument &A : F.args())
2284 if (!A.hasName())
2285 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002286}
2287
2288LLParser::PerFunctionState::~PerFunctionState() {
2289 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002290
David Blaikie9ebdc692015-09-21 21:07:50 +00002291 for (const auto &P : ForwardRefVals) {
2292 if (isa<BasicBlock>(P.second.first))
2293 continue;
2294 P.second.first->replaceAllUsesWith(
2295 UndefValue::get(P.second.first->getType()));
2296 delete P.second.first;
2297 }
2298
2299 for (const auto &P : ForwardRefValIDs) {
2300 if (isa<BasicBlock>(P.second.first))
2301 continue;
2302 P.second.first->replaceAllUsesWith(
2303 UndefValue::get(P.second.first->getType()));
2304 delete P.second.first;
2305 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002306}
2307
Chris Lattner3432c622009-10-28 03:39:23 +00002308bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002309 if (!ForwardRefVals.empty())
2310 return P.Error(ForwardRefVals.begin()->second.second,
2311 "use of undefined value '%" + ForwardRefVals.begin()->first +
2312 "'");
2313 if (!ForwardRefValIDs.empty())
2314 return P.Error(ForwardRefValIDs.begin()->second.second,
2315 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002316 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002317 return false;
2318}
2319
2320
2321/// GetVal - Get a value with the specified name or ID, creating a
2322/// forward reference record if needed. This can return null if the value
2323/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002324Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002325 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002326 // Look this name up in the normal function symbol table.
2327 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002328
Chris Lattnerac161bf2009-01-02 07:01:27 +00002329 // If this is a forward reference for the value, see if we already created a
2330 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002331 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002332 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002333 if (I != ForwardRefVals.end())
2334 Val = I->second.first;
2335 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002336
Chris Lattnerac161bf2009-01-02 07:01:27 +00002337 // If we have the value in the symbol table or fwd-ref table, return it.
2338 if (Val) {
2339 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002340 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002341 P.Error(Loc, "'%" + Name + "' is not a basic block");
2342 else
2343 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002344 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002345 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002346 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002347
Chris Lattnerac161bf2009-01-02 07:01:27 +00002348 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002349 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002350 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002351 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002352 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002353
Chris Lattnerac161bf2009-01-02 07:01:27 +00002354 // Otherwise, create a new forward reference for this value and remember it.
2355 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002356 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002357 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002358 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002359 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002360 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002361
Chris Lattnerac161bf2009-01-02 07:01:27 +00002362 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2363 return FwdVal;
2364}
2365
David Majnemer8a1c45d2015-12-12 05:38:55 +00002366Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002367 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002368 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002369
Chris Lattnerac161bf2009-01-02 07:01:27 +00002370 // If this is a forward reference for the value, see if we already created a
2371 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002372 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002373 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002374 if (I != ForwardRefValIDs.end())
2375 Val = I->second.first;
2376 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002377
Chris Lattnerac161bf2009-01-02 07:01:27 +00002378 // If we have the value in the symbol table or fwd-ref table, return it.
2379 if (Val) {
2380 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002381 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002382 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002383 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002384 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002385 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002386 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002387 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002388
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002389 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002390 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002391 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002392 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002393
Chris Lattnerac161bf2009-01-02 07:01:27 +00002394 // Otherwise, create a new forward reference for this value and remember it.
2395 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002396 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002397 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002398 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002399 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002400 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002401
Chris Lattnerac161bf2009-01-02 07:01:27 +00002402 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2403 return FwdVal;
2404}
2405
2406/// SetInstName - After an instruction is parsed and inserted into its
2407/// basic block, this installs its name.
2408bool LLParser::PerFunctionState::SetInstName(int NameID,
2409 const std::string &NameStr,
2410 LocTy NameLoc, Instruction *Inst) {
2411 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002412 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002413 if (NameID != -1 || !NameStr.empty())
2414 return P.Error(NameLoc, "instructions returning void cannot have a name");
2415 return false;
2416 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002417
Chris Lattnerac161bf2009-01-02 07:01:27 +00002418 // If this was a numbered instruction, verify that the instruction is the
2419 // expected value and resolve any forward references.
2420 if (NameStr.empty()) {
2421 // If neither a name nor an ID was specified, just use the next ID.
2422 if (NameID == -1)
2423 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002424
Chris Lattnerac161bf2009-01-02 07:01:27 +00002425 if (unsigned(NameID) != NumberedVals.size())
2426 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002427 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002428
David Blaikie9ebdc692015-09-21 21:07:50 +00002429 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002430 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002431 Value *Sentinel = FI->second.first;
2432 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002433 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002434 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002435
2436 Sentinel->replaceAllUsesWith(Inst);
2437 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002438 ForwardRefValIDs.erase(FI);
2439 }
2440
2441 NumberedVals.push_back(Inst);
2442 return false;
2443 }
2444
2445 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002446 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002447 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002448 Value *Sentinel = FI->second.first;
2449 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002450 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002451 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002452
2453 Sentinel->replaceAllUsesWith(Inst);
2454 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002455 ForwardRefVals.erase(FI);
2456 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002457
Chris Lattnerac161bf2009-01-02 07:01:27 +00002458 // Set the name on the instruction.
2459 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002460
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002461 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002462 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002463 NameStr + "'");
2464 return false;
2465}
2466
2467/// GetBB - Get a basic block with the specified name or ID, creating a
2468/// forward reference record if needed.
2469BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2470 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002471 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2472 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002473}
2474
2475BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002476 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2477 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002478}
2479
2480/// DefineBB - Define the specified basic block, which is either named or
2481/// unnamed. If there is an error, this returns null otherwise it returns
2482/// the block being defined.
2483BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2484 LocTy Loc) {
2485 BasicBlock *BB;
2486 if (Name.empty())
2487 BB = GetBB(NumberedVals.size(), Loc);
2488 else
2489 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002490 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002491
Chris Lattnerac161bf2009-01-02 07:01:27 +00002492 // Move the block to the end of the function. Forward ref'd blocks are
2493 // inserted wherever they happen to be referenced.
2494 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002495
Chris Lattnerac161bf2009-01-02 07:01:27 +00002496 // Remove the block from forward ref sets.
2497 if (Name.empty()) {
2498 ForwardRefValIDs.erase(NumberedVals.size());
2499 NumberedVals.push_back(BB);
2500 } else {
2501 // BB forward references are already in the function symbol table.
2502 ForwardRefVals.erase(Name);
2503 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002504
Chris Lattnerac161bf2009-01-02 07:01:27 +00002505 return BB;
2506}
2507
2508//===----------------------------------------------------------------------===//
2509// Constants.
2510//===----------------------------------------------------------------------===//
2511
2512/// ParseValID - Parse an abstract value that doesn't necessarily have a
2513/// type implied. For example, if we parse "4" we don't know what integer type
2514/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002515/// sanity. PFS is used to convert function-local operands of metadata (since
2516/// metadata operands are not just parsed here but also converted to values).
2517/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002518bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002519 ID.Loc = Lex.getLoc();
2520 switch (Lex.getKind()) {
2521 default: return TokError("expected value token");
2522 case lltok::GlobalID: // @42
2523 ID.UIntVal = Lex.getUIntVal();
2524 ID.Kind = ValID::t_GlobalID;
2525 break;
2526 case lltok::GlobalVar: // @foo
2527 ID.StrVal = Lex.getStrVal();
2528 ID.Kind = ValID::t_GlobalName;
2529 break;
2530 case lltok::LocalVarID: // %42
2531 ID.UIntVal = Lex.getUIntVal();
2532 ID.Kind = ValID::t_LocalID;
2533 break;
2534 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002535 ID.StrVal = Lex.getStrVal();
2536 ID.Kind = ValID::t_LocalName;
2537 break;
2538 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002539 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002540 ID.Kind = ValID::t_APSInt;
2541 break;
2542 case lltok::APFloat:
2543 ID.APFloatVal = Lex.getAPFloatVal();
2544 ID.Kind = ValID::t_APFloat;
2545 break;
2546 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002547 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002548 ID.Kind = ValID::t_Constant;
2549 break;
2550 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002551 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002552 ID.Kind = ValID::t_Constant;
2553 break;
2554 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2555 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2556 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002557 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002558
Chris Lattnerac161bf2009-01-02 07:01:27 +00002559 case lltok::lbrace: {
2560 // ValID ::= '{' ConstVector '}'
2561 Lex.Lex();
2562 SmallVector<Constant*, 16> Elts;
2563 if (ParseGlobalValueVector(Elts) ||
2564 ParseToken(lltok::rbrace, "expected end of struct constant"))
2565 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002566
David Blaikieadbda4b2015-08-03 20:08:41 +00002567 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002568 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002569 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2570 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002571 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002572 return false;
2573 }
2574 case lltok::less: {
2575 // ValID ::= '<' ConstVector '>' --> Vector.
2576 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2577 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002578 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002579
Chris Lattnerac161bf2009-01-02 07:01:27 +00002580 SmallVector<Constant*, 16> Elts;
2581 LocTy FirstEltLoc = Lex.getLoc();
2582 if (ParseGlobalValueVector(Elts) ||
2583 (isPackedStruct &&
2584 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2585 ParseToken(lltok::greater, "expected end of constant"))
2586 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002587
Chris Lattnerac161bf2009-01-02 07:01:27 +00002588 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002589 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2590 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2591 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002592 ID.UIntVal = Elts.size();
2593 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002594 return false;
2595 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002596
Chris Lattnerac161bf2009-01-02 07:01:27 +00002597 if (Elts.empty())
2598 return Error(ID.Loc, "constant vector must not be empty");
2599
Duncan Sands9dff9be2010-02-15 16:12:20 +00002600 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002601 !Elts[0]->getType()->isFloatingPointTy() &&
2602 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002603 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002604 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002605
Chris Lattnerac161bf2009-01-02 07:01:27 +00002606 // Verify that all the vector elements have the same type.
2607 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2608 if (Elts[i]->getType() != Elts[0]->getType())
2609 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002610 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002611 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002612
Chris Lattner69229312011-02-15 00:14:00 +00002613 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002614 ID.Kind = ValID::t_Constant;
2615 return false;
2616 }
2617 case lltok::lsquare: { // Array Constant
2618 Lex.Lex();
2619 SmallVector<Constant*, 16> Elts;
2620 LocTy FirstEltLoc = Lex.getLoc();
2621 if (ParseGlobalValueVector(Elts) ||
2622 ParseToken(lltok::rsquare, "expected end of array constant"))
2623 return true;
2624
2625 // Handle empty element.
2626 if (Elts.empty()) {
2627 // Use undef instead of an array because it's inconvenient to determine
2628 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002629 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002630 return false;
2631 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002632
Chris Lattnerac161bf2009-01-02 07:01:27 +00002633 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002634 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002635 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002636
Owen Anderson4056ca92009-07-29 22:17:13 +00002637 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002638
Chris Lattnerac161bf2009-01-02 07:01:27 +00002639 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002640 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002641 if (Elts[i]->getType() != Elts[0]->getType())
2642 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002643 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002644 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002645 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002646
Jay Foad83be3612011-06-22 09:24:39 +00002647 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002648 ID.Kind = ValID::t_Constant;
2649 return false;
2650 }
2651 case lltok::kw_c: // c "foo"
2652 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002653 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2654 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002655 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2656 ID.Kind = ValID::t_Constant;
2657 return false;
2658
2659 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002660 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2661 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002662 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002663 Lex.Lex();
2664 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002665 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002666 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002667 ParseStringConstant(ID.StrVal) ||
2668 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002669 ParseToken(lltok::StringConstant, "expected constraint string"))
2670 return true;
2671 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002672 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002673 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002674 ID.Kind = ValID::t_InlineAsm;
2675 return false;
2676 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002677
Chris Lattner3432c622009-10-28 03:39:23 +00002678 case lltok::kw_blockaddress: {
2679 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2680 Lex.Lex();
2681
2682 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002683
Chris Lattner3432c622009-10-28 03:39:23 +00002684 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2685 ParseValID(Fn) ||
2686 ParseToken(lltok::comma, "expected comma in block address expression")||
2687 ParseValID(Label) ||
2688 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2689 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002690
Chris Lattner3432c622009-10-28 03:39:23 +00002691 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2692 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002693 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002694 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002695
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002696 // Try to find the function (but skip it if it's forward-referenced).
2697 GlobalValue *GV = nullptr;
2698 if (Fn.Kind == ValID::t_GlobalID) {
2699 if (Fn.UIntVal < NumberedVals.size())
2700 GV = NumberedVals[Fn.UIntVal];
2701 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2702 GV = M->getNamedValue(Fn.StrVal);
2703 }
2704 Function *F = nullptr;
2705 if (GV) {
2706 // Confirm that it's actually a function with a definition.
2707 if (!isa<Function>(GV))
2708 return Error(Fn.Loc, "expected function name in blockaddress");
2709 F = cast<Function>(GV);
2710 if (F->isDeclaration())
2711 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2712 }
2713
2714 if (!F) {
2715 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002716 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002717 ForwardRefBlockAddresses.insert(std::make_pair(
2718 std::move(Fn),
2719 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002720 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2721 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002722 if (!FwdRef)
2723 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2724 GlobalValue::InternalLinkage, nullptr, "");
2725 ID.ConstantVal = FwdRef;
2726 ID.Kind = ValID::t_Constant;
2727 return false;
2728 }
2729
2730 // We found the function; now find the basic block. Don't use PFS, since we
2731 // might be inside a constant expression.
2732 BasicBlock *BB;
2733 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2734 if (Label.Kind == ValID::t_LocalID)
2735 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2736 else
2737 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2738 if (!BB)
2739 return Error(Label.Loc, "referenced value is not a basic block");
2740 } else {
2741 if (Label.Kind == ValID::t_LocalID)
2742 return Error(Label.Loc, "cannot take address of numeric label after "
2743 "the function is defined");
2744 BB = dyn_cast_or_null<BasicBlock>(
2745 F->getValueSymbolTable().lookup(Label.StrVal));
2746 if (!BB)
2747 return Error(Label.Loc, "referenced value is not a basic block");
2748 }
2749
2750 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002751 ID.Kind = ValID::t_Constant;
2752 return false;
2753 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002754
Chris Lattnerac161bf2009-01-02 07:01:27 +00002755 case lltok::kw_trunc:
2756 case lltok::kw_zext:
2757 case lltok::kw_sext:
2758 case lltok::kw_fptrunc:
2759 case lltok::kw_fpext:
2760 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002761 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002762 case lltok::kw_uitofp:
2763 case lltok::kw_sitofp:
2764 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002765 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002766 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002767 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002768 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002769 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002770 Constant *SrcVal;
2771 Lex.Lex();
2772 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2773 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002774 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002775 ParseType(DestTy) ||
2776 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2777 return true;
2778 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2779 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002780 getTypeString(SrcVal->getType()) + "' to '" +
2781 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002782 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002783 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002784 ID.Kind = ValID::t_Constant;
2785 return false;
2786 }
2787 case lltok::kw_extractvalue: {
2788 Lex.Lex();
2789 Constant *Val;
2790 SmallVector<unsigned, 4> Indices;
2791 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2792 ParseGlobalTypeAndValue(Val) ||
2793 ParseIndexList(Indices) ||
2794 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2795 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002796
Chris Lattner392be582010-02-12 20:49:41 +00002797 if (!Val->getType()->isAggregateType())
2798 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002799 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002800 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002801 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002802 ID.Kind = ValID::t_Constant;
2803 return false;
2804 }
2805 case lltok::kw_insertvalue: {
2806 Lex.Lex();
2807 Constant *Val0, *Val1;
2808 SmallVector<unsigned, 4> Indices;
2809 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2810 ParseGlobalTypeAndValue(Val0) ||
2811 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2812 ParseGlobalTypeAndValue(Val1) ||
2813 ParseIndexList(Indices) ||
2814 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2815 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002816 if (!Val0->getType()->isAggregateType())
2817 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002818 Type *IndexedType =
2819 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2820 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002821 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002822 if (IndexedType != Val1->getType())
2823 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2824 getTypeString(Val1->getType()) +
2825 "' instead of '" + getTypeString(IndexedType) +
2826 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002827 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002828 ID.Kind = ValID::t_Constant;
2829 return false;
2830 }
2831 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002832 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002833 unsigned PredVal, Opc = Lex.getUIntVal();
2834 Constant *Val0, *Val1;
2835 Lex.Lex();
2836 if (ParseCmpPredicate(PredVal, Opc) ||
2837 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2838 ParseGlobalTypeAndValue(Val0) ||
2839 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2840 ParseGlobalTypeAndValue(Val1) ||
2841 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2842 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002843
Chris Lattnerac161bf2009-01-02 07:01:27 +00002844 if (Val0->getType() != Val1->getType())
2845 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002846
Chris Lattnerac161bf2009-01-02 07:01:27 +00002847 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002848
Chris Lattnerac161bf2009-01-02 07:01:27 +00002849 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002850 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002851 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002852 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002853 } else {
2854 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002855 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002856 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002857 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002858 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002859 }
2860 ID.Kind = ValID::t_Constant;
2861 return false;
2862 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002863
Chris Lattnerac161bf2009-01-02 07:01:27 +00002864 // Binary Operators.
2865 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002866 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002867 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002868 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002869 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002870 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002871 case lltok::kw_udiv:
2872 case lltok::kw_sdiv:
2873 case lltok::kw_fdiv:
2874 case lltok::kw_urem:
2875 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002876 case lltok::kw_frem:
2877 case lltok::kw_shl:
2878 case lltok::kw_lshr:
2879 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002880 bool NUW = false;
2881 bool NSW = false;
2882 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002883 unsigned Opc = Lex.getUIntVal();
2884 Constant *Val0, *Val1;
2885 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002886 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002887 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2888 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002889 if (EatIfPresent(lltok::kw_nuw))
2890 NUW = true;
2891 if (EatIfPresent(lltok::kw_nsw)) {
2892 NSW = true;
2893 if (EatIfPresent(lltok::kw_nuw))
2894 NUW = true;
2895 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002896 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2897 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002898 if (EatIfPresent(lltok::kw_exact))
2899 Exact = true;
2900 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002901 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2902 ParseGlobalTypeAndValue(Val0) ||
2903 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2904 ParseGlobalTypeAndValue(Val1) ||
2905 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2906 return true;
2907 if (Val0->getType() != Val1->getType())
2908 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002909 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002910 if (NUW)
2911 return Error(ModifierLoc, "nuw only applies to integer operations");
2912 if (NSW)
2913 return Error(ModifierLoc, "nsw only applies to integer operations");
2914 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002915 // Check that the type is valid for the operator.
2916 switch (Opc) {
2917 case Instruction::Add:
2918 case Instruction::Sub:
2919 case Instruction::Mul:
2920 case Instruction::UDiv:
2921 case Instruction::SDiv:
2922 case Instruction::URem:
2923 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002924 case Instruction::Shl:
2925 case Instruction::AShr:
2926 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002927 if (!Val0->getType()->isIntOrIntVectorTy())
2928 return Error(ID.Loc, "constexpr requires integer operands");
2929 break;
2930 case Instruction::FAdd:
2931 case Instruction::FSub:
2932 case Instruction::FMul:
2933 case Instruction::FDiv:
2934 case Instruction::FRem:
2935 if (!Val0->getType()->isFPOrFPVectorTy())
2936 return Error(ID.Loc, "constexpr requires fp operands");
2937 break;
2938 default: llvm_unreachable("Unknown binary operator!");
2939 }
Dan Gohman1b849082009-09-07 23:54:19 +00002940 unsigned Flags = 0;
2941 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2942 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002943 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002944 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002945 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002946 ID.Kind = ValID::t_Constant;
2947 return false;
2948 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002949
Chris Lattnerac161bf2009-01-02 07:01:27 +00002950 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002951 case lltok::kw_and:
2952 case lltok::kw_or:
2953 case lltok::kw_xor: {
2954 unsigned Opc = Lex.getUIntVal();
2955 Constant *Val0, *Val1;
2956 Lex.Lex();
2957 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2958 ParseGlobalTypeAndValue(Val0) ||
2959 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2960 ParseGlobalTypeAndValue(Val1) ||
2961 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2962 return true;
2963 if (Val0->getType() != Val1->getType())
2964 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002965 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002966 return Error(ID.Loc,
2967 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002968 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002969 ID.Kind = ValID::t_Constant;
2970 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002971 }
2972
Chris Lattnerac161bf2009-01-02 07:01:27 +00002973 case lltok::kw_getelementptr:
2974 case lltok::kw_shufflevector:
2975 case lltok::kw_insertelement:
2976 case lltok::kw_extractelement:
2977 case lltok::kw_select: {
2978 unsigned Opc = Lex.getUIntVal();
2979 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002980 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00002981 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002982 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00002983
Dan Gohman1639c392009-07-27 21:53:46 +00002984 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002985 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00002986
2987 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2988 return true;
2989
2990 LocTy ExplicitTypeLoc = Lex.getLoc();
2991 if (Opc == Instruction::GetElementPtr) {
2992 if (ParseType(Ty) ||
2993 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2994 return true;
2995 }
2996
2997 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002998 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2999 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003000
Chris Lattnerac161bf2009-01-02 07:01:27 +00003001 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003002 if (Elts.size() == 0 ||
3003 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003004 return Error(ID.Loc, "base of getelementptr must be a pointer");
3005
3006 Type *BaseType = Elts[0]->getType();
3007 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003008 if (Ty != BasePointerType->getElementType())
3009 return Error(
3010 ExplicitTypeLoc,
3011 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003012
Jay Foaded8db7d2011-07-21 14:31:17 +00003013 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003014 for (Constant *Val : Indices) {
3015 Type *ValTy = Val->getType();
3016 if (!ValTy->getScalarType()->isIntegerTy())
3017 return Error(ID.Loc, "getelementptr index must be an integer");
3018 if (ValTy->isVectorTy() != BaseType->isVectorTy())
3019 return Error(ID.Loc, "getelementptr index type missmatch");
3020 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003021 unsigned ValNumEl = ValTy->getVectorNumElements();
3022 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00003023 if (ValNumEl != PtrNumEl)
3024 return Error(
3025 ID.Loc,
3026 "getelementptr vector index has a wrong number of elements");
3027 }
3028 }
3029
Craig Toppere3dcce92015-08-01 22:20:21 +00003030 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003031 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003032 return Error(ID.Loc, "base element of getelementptr must be sized");
3033
David Blaikie4a2e73b2015-04-02 18:55:32 +00003034 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003035 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003036 ID.ConstantVal =
3037 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003038 } else if (Opc == Instruction::Select) {
3039 if (Elts.size() != 3)
3040 return Error(ID.Loc, "expected three operands to select");
3041 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3042 Elts[2]))
3043 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003044 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003045 } else if (Opc == Instruction::ShuffleVector) {
3046 if (Elts.size() != 3)
3047 return Error(ID.Loc, "expected three operands to shufflevector");
3048 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3049 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003050 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003051 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003052 } else if (Opc == Instruction::ExtractElement) {
3053 if (Elts.size() != 2)
3054 return Error(ID.Loc, "expected two operands to extractelement");
3055 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3056 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003057 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003058 } else {
3059 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3060 if (Elts.size() != 3)
3061 return Error(ID.Loc, "expected three operands to insertelement");
3062 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3063 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003064 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003065 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003066 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003067
Chris Lattnerac161bf2009-01-02 07:01:27 +00003068 ID.Kind = ValID::t_Constant;
3069 return false;
3070 }
3071 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003072
Chris Lattnerac161bf2009-01-02 07:01:27 +00003073 Lex.Lex();
3074 return false;
3075}
3076
3077/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003078bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003079 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003080 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003081 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003082 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003083 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003084 if (V && !(C = dyn_cast<Constant>(V)))
3085 return Error(ID.Loc, "global values must be constants");
3086 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003087}
3088
Victor Hernandez9d75c962010-01-11 22:31:58 +00003089bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003090 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003091 return ParseType(Ty) ||
3092 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003093}
3094
Rafael Espindola83a362c2015-01-06 22:55:16 +00003095bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003096 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003097
3098 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003099 if (!EatIfPresent(lltok::kw_comdat))
3100 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003101
3102 if (EatIfPresent(lltok::lparen)) {
3103 if (Lex.getKind() != lltok::ComdatVar)
3104 return TokError("expected comdat variable");
3105 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3106 Lex.Lex();
3107 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3108 return true;
3109 } else {
3110 if (GlobalName.empty())
3111 return TokError("comdat cannot be unnamed");
3112 C = getComdat(GlobalName, KwLoc);
3113 }
3114
David Majnemerdad0a642014-06-27 18:19:56 +00003115 return false;
3116}
3117
Victor Hernandez9d75c962010-01-11 22:31:58 +00003118/// ParseGlobalValueVector
3119/// ::= /*empty*/
3120/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003121bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003122 // Empty list.
3123 if (Lex.getKind() == lltok::rbrace ||
3124 Lex.getKind() == lltok::rsquare ||
3125 Lex.getKind() == lltok::greater ||
3126 Lex.getKind() == lltok::rparen)
3127 return false;
3128
3129 Constant *C;
3130 if (ParseGlobalTypeAndValue(C)) return true;
3131 Elts.push_back(C);
3132
3133 while (EatIfPresent(lltok::comma)) {
3134 if (ParseGlobalTypeAndValue(C)) return true;
3135 Elts.push_back(C);
3136 }
3137
3138 return false;
3139}
3140
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003141bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003142 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003143 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003144 return true;
3145
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003146 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003147 return false;
3148}
3149
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003150/// MDNode:
3151/// ::= !{ ... }
3152/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003153/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003154bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003155 if (Lex.getKind() == lltok::MetadataVar)
3156 return ParseSpecializedMDNode(N);
3157
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003158 return ParseToken(lltok::exclaim, "expected '!' here") ||
3159 ParseMDNodeTail(N);
3160}
3161
3162bool LLParser::ParseMDNodeTail(MDNode *&N) {
3163 // !{ ... }
3164 if (Lex.getKind() == lltok::lbrace)
3165 return ParseMDTuple(N);
3166
3167 // !42
3168 return ParseMDNodeID(N);
3169}
3170
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003171namespace {
3172
3173/// Structure to represent an optional metadata field.
3174template <class FieldTy> struct MDFieldImpl {
3175 typedef MDFieldImpl ImplTy;
3176 FieldTy Val;
3177 bool Seen;
3178
3179 void assign(FieldTy Val) {
3180 Seen = true;
3181 this->Val = std::move(Val);
3182 }
3183
3184 explicit MDFieldImpl(FieldTy Default)
3185 : Val(std::move(Default)), Seen(false) {}
3186};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003187
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003188struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3189 uint64_t Max;
3190
3191 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3192 : ImplTy(Default), Max(Max) {}
3193};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003194struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003195 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003196};
3197struct ColumnField : public MDUnsignedField {
3198 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3199};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003200struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003201 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003202 DwarfTagField(dwarf::Tag DefaultTag)
3203 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003204};
Amjad Abouda9bcf162015-12-10 12:56:35 +00003205struct DwarfMacinfoTypeField : public MDUnsignedField {
3206 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3207 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3208 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3209};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003210struct DwarfAttEncodingField : public MDUnsignedField {
3211 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3212};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003213struct DwarfVirtualityField : public MDUnsignedField {
3214 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3215};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003216struct DwarfLangField : public MDUnsignedField {
3217 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3218};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003219
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003220struct DIFlagField : public MDUnsignedField {
3221 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3222};
3223
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003224struct MDSignedField : public MDFieldImpl<int64_t> {
3225 int64_t Min;
3226 int64_t Max;
3227
3228 MDSignedField(int64_t Default = 0)
3229 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3230 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3231 : ImplTy(Default), Min(Min), Max(Max) {}
3232};
3233
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003234struct MDBoolField : public MDFieldImpl<bool> {
3235 MDBoolField(bool Default = false) : ImplTy(Default) {}
3236};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003237struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003238 bool AllowNull;
3239
3240 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003241};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003242struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3243 MDConstant() : ImplTy(nullptr) {}
3244};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003245struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003246 bool AllowEmpty;
3247 MDStringField(bool AllowEmpty = true)
3248 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003249};
3250struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3251 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3252};
3253
3254} // end namespace
3255
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003256namespace llvm {
3257
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003258template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003259bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003260 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003261 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3262 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003263
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003264 auto &U = Lex.getAPSIntVal();
3265 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003266 return TokError("value for '" + Name + "' too large, limit is " +
3267 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003268 Result.assign(U.getZExtValue());
3269 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003270 Lex.Lex();
3271 return false;
3272}
3273
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003274template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003275bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3276 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3277}
3278template <>
3279bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3280 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3281}
3282
3283template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003284bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3285 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003286 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003287
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003288 if (Lex.getKind() != lltok::DwarfTag)
3289 return TokError("expected DWARF tag");
3290
3291 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3292 if (Tag == dwarf::DW_TAG_invalid)
3293 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003294 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003295
3296 Result.assign(Tag);
3297 Lex.Lex();
3298 return false;
3299}
3300
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003301template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003302bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003303 DwarfMacinfoTypeField &Result) {
3304 if (Lex.getKind() == lltok::APSInt)
3305 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3306
3307 if (Lex.getKind() != lltok::DwarfMacinfo)
3308 return TokError("expected DWARF macinfo type");
3309
3310 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3311 if (Macinfo == dwarf::DW_MACINFO_invalid)
3312 return TokError(
3313 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3314 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3315
3316 Result.assign(Macinfo);
3317 Lex.Lex();
3318 return false;
3319}
3320
3321template <>
3322bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003323 DwarfVirtualityField &Result) {
3324 if (Lex.getKind() == lltok::APSInt)
3325 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3326
3327 if (Lex.getKind() != lltok::DwarfVirtuality)
3328 return TokError("expected DWARF virtuality code");
3329
3330 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3331 if (!Virtuality)
3332 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3333 Lex.getStrVal() + "'");
3334 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3335 Result.assign(Virtuality);
3336 Lex.Lex();
3337 return false;
3338}
3339
3340template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003341bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3342 if (Lex.getKind() == lltok::APSInt)
3343 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3344
3345 if (Lex.getKind() != lltok::DwarfLang)
3346 return TokError("expected DWARF language");
3347
3348 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3349 if (!Lang)
3350 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3351 "'");
3352 assert(Lang <= Result.Max && "Expected valid DWARF language");
3353 Result.assign(Lang);
3354 Lex.Lex();
3355 return false;
3356}
3357
3358template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003359bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003360 DwarfAttEncodingField &Result) {
3361 if (Lex.getKind() == lltok::APSInt)
3362 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3363
3364 if (Lex.getKind() != lltok::DwarfAttEncoding)
3365 return TokError("expected DWARF type attribute encoding");
3366
3367 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3368 if (!Encoding)
3369 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3370 Lex.getStrVal() + "'");
3371 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3372 Result.assign(Encoding);
3373 Lex.Lex();
3374 return false;
3375}
3376
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003377/// DIFlagField
3378/// ::= uint32
3379/// ::= DIFlagVector
3380/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3381template <>
3382bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3383 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3384
3385 // Parser for a single flag.
3386 auto parseFlag = [&](unsigned &Val) {
3387 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3388 return ParseUInt32(Val);
3389
3390 if (Lex.getKind() != lltok::DIFlag)
3391 return TokError("expected debug info flag");
3392
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003393 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003394 if (!Val)
3395 return TokError(Twine("invalid debug info flag flag '") +
3396 Lex.getStrVal() + "'");
3397 Lex.Lex();
3398 return false;
3399 };
3400
3401 // Parse the flags and combine them together.
3402 unsigned Combined = 0;
3403 do {
3404 unsigned Val;
3405 if (parseFlag(Val))
3406 return true;
3407 Combined |= Val;
3408 } while (EatIfPresent(lltok::bar));
3409
3410 Result.assign(Combined);
3411 return false;
3412}
3413
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003414template <>
3415bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003416 MDSignedField &Result) {
3417 if (Lex.getKind() != lltok::APSInt)
3418 return TokError("expected signed integer");
3419
3420 auto &S = Lex.getAPSIntVal();
3421 if (S < Result.Min)
3422 return TokError("value for '" + Name + "' too small, limit is " +
3423 Twine(Result.Min));
3424 if (S > Result.Max)
3425 return TokError("value for '" + Name + "' too large, limit is " +
3426 Twine(Result.Max));
3427 Result.assign(S.getExtValue());
3428 assert(Result.Val >= Result.Min && "Expected value in range");
3429 assert(Result.Val <= Result.Max && "Expected value in range");
3430 Lex.Lex();
3431 return false;
3432}
3433
3434template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003435bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3436 switch (Lex.getKind()) {
3437 default:
3438 return TokError("expected 'true' or 'false'");
3439 case lltok::kw_true:
3440 Result.assign(true);
3441 break;
3442 case lltok::kw_false:
3443 Result.assign(false);
3444 break;
3445 }
3446 Lex.Lex();
3447 return false;
3448}
3449
3450template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003451bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003452 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003453 if (!Result.AllowNull)
3454 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003455 Lex.Lex();
3456 Result.assign(nullptr);
3457 return false;
3458 }
3459
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003460 Metadata *MD;
3461 if (ParseMetadata(MD, nullptr))
3462 return true;
3463
3464 Result.assign(MD);
3465 return false;
3466}
3467
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003468template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003469bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3470 Metadata *MD;
3471 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3472 return true;
3473
3474 Result.assign(cast<ConstantAsMetadata>(MD));
3475 return false;
3476}
3477
3478template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003479bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003480 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003481 std::string S;
3482 if (ParseStringConstant(S))
3483 return true;
3484
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003485 if (!Result.AllowEmpty && S.empty())
3486 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3487
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003488 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003489 return false;
3490}
3491
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003492template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003493bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3494 SmallVector<Metadata *, 4> MDs;
3495 if (ParseMDNodeVector(MDs))
3496 return true;
3497
3498 Result.assign(std::move(MDs));
3499 return false;
3500}
3501
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003502} // end namespace llvm
3503
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003504template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003505bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003506 do {
3507 if (Lex.getKind() != lltok::LabelStr)
3508 return TokError("expected field label here");
3509
3510 if (parseField())
3511 return true;
3512 } while (EatIfPresent(lltok::comma));
3513
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003514 return false;
3515}
3516
3517template <class ParserTy>
3518bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3519 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3520 Lex.Lex();
3521
3522 if (ParseToken(lltok::lparen, "expected '(' here"))
3523 return true;
3524 if (Lex.getKind() != lltok::rparen)
3525 if (ParseMDFieldsImplBody(parseField))
3526 return true;
3527
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003528 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003529 return ParseToken(lltok::rparen, "expected ')' here");
3530}
3531
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003532template <class FieldTy>
3533bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3534 if (Result.Seen)
3535 return TokError("field '" + Name + "' cannot be specified more than once");
3536
3537 LocTy Loc = Lex.getLoc();
3538 Lex.Lex();
3539 return ParseMDField(Loc, Name, Result);
3540}
3541
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003542bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3543 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003544
3545#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003546 if (Lex.getStrVal() == #CLASS) \
3547 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003548#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003549
3550 return TokError("expected metadata type");
3551}
3552
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003553#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3554#define NOP_FIELD(NAME, TYPE, INIT)
3555#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3556 if (!NAME.Seen) \
3557 return Error(ClosingLoc, "missing required field '" #NAME "'");
3558#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003559 if (Lex.getStrVal() == #NAME) \
3560 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003561#define PARSE_MD_FIELDS() \
3562 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3563 do { \
3564 LocTy ClosingLoc; \
3565 if (ParseMDFieldsImpl([&]() -> bool { \
3566 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3567 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3568 }, ClosingLoc)) \
3569 return true; \
3570 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3571 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003572#define GET_OR_DISTINCT(CLASS, ARGS) \
3573 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003574
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003575/// ParseDILocationFields:
3576/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3577bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003578#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003579 OPTIONAL(line, LineField, ); \
3580 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003581 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003582 OPTIONAL(inlinedAt, MDField, );
3583 PARSE_MD_FIELDS();
3584#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003585
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003586 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003587 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003588 return false;
3589}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003590
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003591/// ParseGenericDINode:
3592/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3593bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003594#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003595 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003596 OPTIONAL(header, MDStringField, ); \
3597 OPTIONAL(operands, MDFieldList, );
3598 PARSE_MD_FIELDS();
3599#undef VISIT_MD_FIELDS
3600
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003601 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003602 (Context, tag.Val, header.Val, operands.Val));
3603 return false;
3604}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003605
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003606/// ParseDISubrange:
3607/// ::= !DISubrange(count: 30, lowerBound: 2)
3608bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003609#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003610 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003611 OPTIONAL(lowerBound, MDSignedField, );
3612 PARSE_MD_FIELDS();
3613#undef VISIT_MD_FIELDS
3614
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003615 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003616 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003617}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003618
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003619/// ParseDIEnumerator:
3620/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3621bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003622#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003623 REQUIRED(name, MDStringField, ); \
3624 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003625 PARSE_MD_FIELDS();
3626#undef VISIT_MD_FIELDS
3627
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003628 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003629 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003630}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003631
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003632/// ParseDIBasicType:
3633/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3634bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003635#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003636 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003637 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003638 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3639 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003640 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003641 PARSE_MD_FIELDS();
3642#undef VISIT_MD_FIELDS
3643
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003644 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003645 align.Val, encoding.Val));
3646 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003647}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003648
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003649/// ParseDIDerivedType:
3650/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003651/// line: 7, scope: !1, baseType: !2, size: 32,
3652/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003653bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003654#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3655 REQUIRED(tag, DwarfTagField, ); \
3656 OPTIONAL(name, MDStringField, ); \
3657 OPTIONAL(file, MDField, ); \
3658 OPTIONAL(line, LineField, ); \
3659 OPTIONAL(scope, MDField, ); \
3660 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003661 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3662 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3663 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003664 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003665 OPTIONAL(extraData, MDField, );
3666 PARSE_MD_FIELDS();
3667#undef VISIT_MD_FIELDS
3668
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003669 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003670 (Context, tag.Val, name.Val, file.Val, line.Val,
3671 scope.Val, baseType.Val, size.Val, align.Val,
3672 offset.Val, flags.Val, extraData.Val));
3673 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003674}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003675
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003676bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003677#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3678 REQUIRED(tag, DwarfTagField, ); \
3679 OPTIONAL(name, MDStringField, ); \
3680 OPTIONAL(file, MDField, ); \
3681 OPTIONAL(line, LineField, ); \
3682 OPTIONAL(scope, MDField, ); \
3683 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003684 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3685 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3686 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003687 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003688 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003689 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003690 OPTIONAL(vtableHolder, MDField, ); \
3691 OPTIONAL(templateParams, MDField, ); \
3692 OPTIONAL(identifier, MDStringField, );
3693 PARSE_MD_FIELDS();
3694#undef VISIT_MD_FIELDS
3695
3696 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003697 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003698 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3699 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3700 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3701 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003702}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003703
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003704bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003705#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003706 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003707 REQUIRED(types, MDField, );
3708 PARSE_MD_FIELDS();
3709#undef VISIT_MD_FIELDS
3710
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003711 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003712 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003713}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003714
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003715/// ParseDIFileType:
3716/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3717bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003718#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3719 REQUIRED(filename, MDStringField, ); \
3720 REQUIRED(directory, MDStringField, );
3721 PARSE_MD_FIELDS();
3722#undef VISIT_MD_FIELDS
3723
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003724 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003725 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003726}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003727
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003728/// ParseDICompileUnit:
3729/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003730/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3731/// splitDebugFilename: "abc.debug", emissionKind: 1,
3732/// enums: !1, retainedTypes: !2, subprograms: !3,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003733/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003734bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003735 if (!IsDistinct)
3736 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3737
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003738#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3739 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003740 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003741 OPTIONAL(producer, MDStringField, ); \
3742 OPTIONAL(isOptimized, MDBoolField, ); \
3743 OPTIONAL(flags, MDStringField, ); \
3744 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3745 OPTIONAL(splitDebugFilename, MDStringField, ); \
3746 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3747 OPTIONAL(enums, MDField, ); \
3748 OPTIONAL(retainedTypes, MDField, ); \
3749 OPTIONAL(subprograms, MDField, ); \
3750 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003751 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00003752 OPTIONAL(macros, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003753 OPTIONAL(dwoId, MDUnsignedField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003754 PARSE_MD_FIELDS();
3755#undef VISIT_MD_FIELDS
3756
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003757 Result = DICompileUnit::getDistinct(
3758 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3759 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003760 retainedTypes.Val, subprograms.Val, globals.Val, imports.Val, macros.Val,
3761 dwoId.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003762 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003763}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003764
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003765/// ParseDISubprogram:
3766/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003767/// file: !1, line: 7, type: !2, isLocal: false,
3768/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003769/// virtuality: DW_VIRTUALTIY_pure_virtual,
3770/// virtualIndex: 10, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00003771/// isOptimized: false, templateParams: !4, declaration: !5,
3772/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003773bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003774 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003775#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3776 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003777 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003778 OPTIONAL(linkageName, MDStringField, ); \
3779 OPTIONAL(file, MDField, ); \
3780 OPTIONAL(line, LineField, ); \
3781 OPTIONAL(type, MDField, ); \
3782 OPTIONAL(isLocal, MDBoolField, ); \
3783 OPTIONAL(isDefinition, MDBoolField, (true)); \
3784 OPTIONAL(scopeLine, LineField, ); \
3785 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003786 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003787 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003788 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003789 OPTIONAL(isOptimized, MDBoolField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003790 OPTIONAL(templateParams, MDField, ); \
3791 OPTIONAL(declaration, MDField, ); \
3792 OPTIONAL(variables, MDField, );
3793 PARSE_MD_FIELDS();
3794#undef VISIT_MD_FIELDS
3795
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003796 if (isDefinition.Val && !IsDistinct)
3797 return Lex.Error(
3798 Loc,
3799 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
3800
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003801 Result = GET_OR_DISTINCT(
Peter Collingbourned4bff302015-11-05 22:03:56 +00003802 DISubprogram,
3803 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
3804 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
3805 containingType.Val, virtuality.Val, virtualIndex.Val, flags.Val,
3806 isOptimized.Val, templateParams.Val, declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003807 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003808}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003809
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003810/// ParseDILexicalBlock:
3811/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3812bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003813#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003814 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003815 OPTIONAL(file, MDField, ); \
3816 OPTIONAL(line, LineField, ); \
3817 OPTIONAL(column, ColumnField, );
3818 PARSE_MD_FIELDS();
3819#undef VISIT_MD_FIELDS
3820
3821 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003822 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003823 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003824}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003825
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003826/// ParseDILexicalBlockFile:
3827/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3828bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003829#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003830 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003831 OPTIONAL(file, MDField, ); \
3832 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3833 PARSE_MD_FIELDS();
3834#undef VISIT_MD_FIELDS
3835
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003836 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003837 (Context, scope.Val, file.Val, discriminator.Val));
3838 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003839}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003840
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003841/// ParseDINamespace:
3842/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3843bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003844#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3845 REQUIRED(scope, MDField, ); \
3846 OPTIONAL(file, MDField, ); \
3847 OPTIONAL(name, MDStringField, ); \
3848 OPTIONAL(line, LineField, );
3849 PARSE_MD_FIELDS();
3850#undef VISIT_MD_FIELDS
3851
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003852 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003853 (Context, scope.Val, file.Val, name.Val, line.Val));
3854 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003855}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003856
Amjad Abouda9bcf162015-12-10 12:56:35 +00003857/// ParseDIMacro:
3858/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
3859bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
3860#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3861 REQUIRED(type, DwarfMacinfoTypeField, ); \
3862 REQUIRED(line, LineField, ); \
3863 REQUIRED(name, MDStringField, ); \
3864 OPTIONAL(value, MDStringField, );
3865 PARSE_MD_FIELDS();
3866#undef VISIT_MD_FIELDS
3867
3868 Result = GET_OR_DISTINCT(DIMacro,
3869 (Context, type.Val, line.Val, name.Val, value.Val));
3870 return false;
3871}
3872
3873/// ParseDIMacroFile:
3874/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
3875bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
3876#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3877 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
3878 REQUIRED(line, LineField, ); \
3879 REQUIRED(file, MDField, ); \
3880 OPTIONAL(nodes, MDField, );
3881 PARSE_MD_FIELDS();
3882#undef VISIT_MD_FIELDS
3883
3884 Result = GET_OR_DISTINCT(DIMacroFile,
3885 (Context, type.Val, line.Val, file.Val, nodes.Val));
3886 return false;
3887}
3888
3889
Adrian Prantlab1243f2015-06-29 23:03:47 +00003890/// ParseDIModule:
3891/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
3892/// includePath: "/usr/include", isysroot: "/")
3893bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
3894#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3895 REQUIRED(scope, MDField, ); \
3896 REQUIRED(name, MDStringField, ); \
3897 OPTIONAL(configMacros, MDStringField, ); \
3898 OPTIONAL(includePath, MDStringField, ); \
3899 OPTIONAL(isysroot, MDStringField, );
3900 PARSE_MD_FIELDS();
3901#undef VISIT_MD_FIELDS
3902
3903 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
3904 configMacros.Val, includePath.Val, isysroot.Val));
3905 return false;
3906}
3907
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003908/// ParseDITemplateTypeParameter:
3909/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3910bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003911#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003912 OPTIONAL(name, MDStringField, ); \
3913 REQUIRED(type, MDField, );
3914 PARSE_MD_FIELDS();
3915#undef VISIT_MD_FIELDS
3916
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003917 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003918 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003919 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003920}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003921
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003922/// ParseDITemplateValueParameter:
3923/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003924/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003925bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003926#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003927 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003928 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003929 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003930 REQUIRED(value, MDField, );
3931 PARSE_MD_FIELDS();
3932#undef VISIT_MD_FIELDS
3933
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003934 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003935 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003936 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003937}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003938
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003939/// ParseDIGlobalVariable:
3940/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003941/// file: !1, line: 7, type: !2, isLocal: false,
3942/// isDefinition: true, variable: i32* @foo,
3943/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003944bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003945#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003946 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003947 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003948 OPTIONAL(linkageName, MDStringField, ); \
3949 OPTIONAL(file, MDField, ); \
3950 OPTIONAL(line, LineField, ); \
3951 OPTIONAL(type, MDField, ); \
3952 OPTIONAL(isLocal, MDBoolField, ); \
3953 OPTIONAL(isDefinition, MDBoolField, (true)); \
3954 OPTIONAL(variable, MDConstant, ); \
3955 OPTIONAL(declaration, MDField, );
3956 PARSE_MD_FIELDS();
3957#undef VISIT_MD_FIELDS
3958
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003959 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003960 (Context, scope.Val, name.Val, linkageName.Val,
3961 file.Val, line.Val, type.Val, isLocal.Val,
3962 isDefinition.Val, variable.Val, declaration.Val));
3963 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003964}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003965
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003966/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00003967/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
3968/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3969/// ::= !DILocalVariable(scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003970/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003971bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003972#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003973 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003974 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00003975 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003976 OPTIONAL(file, MDField, ); \
3977 OPTIONAL(line, LineField, ); \
3978 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003979 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003980 PARSE_MD_FIELDS();
3981#undef VISIT_MD_FIELDS
3982
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003983 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00003984 (Context, scope.Val, name.Val, file.Val, line.Val,
3985 type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003986 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003987}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003988
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003989/// ParseDIExpression:
3990/// ::= !DIExpression(0, 7, -1)
3991bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003992 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3993 Lex.Lex();
3994
3995 if (ParseToken(lltok::lparen, "expected '(' here"))
3996 return true;
3997
3998 SmallVector<uint64_t, 8> Elements;
3999 if (Lex.getKind() != lltok::rparen)
4000 do {
4001 if (Lex.getKind() == lltok::DwarfOp) {
4002 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4003 Lex.Lex();
4004 Elements.push_back(Op);
4005 continue;
4006 }
4007 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4008 }
4009
4010 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4011 return TokError("expected unsigned integer");
4012
4013 auto &U = Lex.getAPSIntVal();
4014 if (U.ugt(UINT64_MAX))
4015 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4016 Elements.push_back(U.getZExtValue());
4017 Lex.Lex();
4018 } while (EatIfPresent(lltok::comma));
4019
4020 if (ParseToken(lltok::rparen, "expected ')' here"))
4021 return true;
4022
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004023 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004024 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004025}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004026
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004027/// ParseDIObjCProperty:
4028/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004029/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004030bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004031#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004032 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004033 OPTIONAL(file, MDField, ); \
4034 OPTIONAL(line, LineField, ); \
4035 OPTIONAL(setter, MDStringField, ); \
4036 OPTIONAL(getter, MDStringField, ); \
4037 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4038 OPTIONAL(type, MDField, );
4039 PARSE_MD_FIELDS();
4040#undef VISIT_MD_FIELDS
4041
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004042 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004043 (Context, name.Val, file.Val, line.Val, setter.Val,
4044 getter.Val, attributes.Val, type.Val));
4045 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004046}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004047
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004048/// ParseDIImportedEntity:
4049/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004050/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004051bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004052#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4053 REQUIRED(tag, DwarfTagField, ); \
4054 REQUIRED(scope, MDField, ); \
4055 OPTIONAL(entity, MDField, ); \
4056 OPTIONAL(line, LineField, ); \
4057 OPTIONAL(name, MDStringField, );
4058 PARSE_MD_FIELDS();
4059#undef VISIT_MD_FIELDS
4060
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004061 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004062 entity.Val, line.Val, name.Val));
4063 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004064}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004065
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004066#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004067#undef NOP_FIELD
4068#undef REQUIRE_FIELD
4069#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004070
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004071/// ParseMetadataAsValue
4072/// ::= metadata i32 %local
4073/// ::= metadata i32 @global
4074/// ::= metadata i32 7
4075/// ::= metadata !0
4076/// ::= metadata !{...}
4077/// ::= metadata !"string"
4078bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4079 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004080 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004081 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004082 return true;
4083
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004084 V = MetadataAsValue::get(Context, MD);
4085 return false;
4086}
4087
4088/// ParseValueAsMetadata
4089/// ::= i32 %local
4090/// ::= i32 @global
4091/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004092bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4093 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004094 Type *Ty;
4095 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004096 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004097 return true;
4098 if (Ty->isMetadataTy())
4099 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4100
4101 Value *V;
4102 if (ParseValue(Ty, V, PFS))
4103 return true;
4104
4105 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004106 return false;
4107}
4108
4109/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004110/// ::= i32 %local
4111/// ::= i32 @global
4112/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004113/// ::= !42
4114/// ::= !{...}
4115/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004116/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004117bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004118 if (Lex.getKind() == lltok::MetadataVar) {
4119 MDNode *N;
4120 if (ParseSpecializedMDNode(N))
4121 return true;
4122 MD = N;
4123 return false;
4124 }
4125
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004126 // ValueAsMetadata:
4127 // <type> <value>
4128 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004129 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004130
4131 // '!'.
4132 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4133 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004134
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004135 // MDString:
4136 // ::= '!' STRINGCONSTANT
4137 if (Lex.getKind() == lltok::StringConstant) {
4138 MDString *S;
4139 if (ParseMDString(S))
4140 return true;
4141 MD = S;
4142 return false;
4143 }
4144
Dan Gohman8939ba332010-07-14 18:26:50 +00004145 // MDNode:
4146 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004147 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004148 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004149 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004150 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004151 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004152 return false;
4153}
4154
Victor Hernandez9d75c962010-01-11 22:31:58 +00004155
4156//===----------------------------------------------------------------------===//
4157// Function Parsing.
4158//===----------------------------------------------------------------------===//
4159
Chris Lattner229907c2011-07-18 04:54:35 +00004160bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004161 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004162 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004163 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004164
Chris Lattnerac161bf2009-01-02 07:01:27 +00004165 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004166 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004167 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004168 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004169 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004170 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004171 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004172 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004173 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004174 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004175 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004176 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004177 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4178 (ID.UIntVal >> 1) & 1,
4179 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004180 return false;
4181 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004182 case ValID::t_GlobalName:
4183 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004184 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004185 case ValID::t_GlobalID:
4186 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004187 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004188 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004189 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004190 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004191 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004192 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004193 return false;
4194 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004195 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004196 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4197 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004198
Dan Gohman518cda42011-12-17 00:04:22 +00004199 // The lexer has no type info, so builds all half, float, and double FP
4200 // constants as double. Fix this here. Long double does not need this.
4201 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004202 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004203 if (Ty->isHalfTy())
4204 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4205 &Ignored);
4206 else if (Ty->isFloatTy())
4207 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4208 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004209 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004210 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004211
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004212 if (V->getType() != Ty)
4213 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004214 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004215
Chris Lattnerac161bf2009-01-02 07:01:27 +00004216 return false;
4217 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004218 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004219 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004220 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004221 return false;
4222 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004223 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004224 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004225 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004226 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004227 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004228 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004229 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004230 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004231 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004232 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004233 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004234 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004235 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004236 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004237 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004238 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004239 case ValID::t_None:
4240 if (!Ty->isTokenTy())
4241 return Error(ID.Loc, "invalid type for none constant");
4242 V = Constant::getNullValue(Ty);
4243 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004244 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004245 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004246 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004247
Chris Lattnerac161bf2009-01-02 07:01:27 +00004248 V = ID.ConstantVal;
4249 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004250 case ValID::t_ConstantStruct:
4251 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004252 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004253 if (ST->getNumElements() != ID.UIntVal)
4254 return Error(ID.Loc,
4255 "initializer with struct type has wrong # elements");
4256 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4257 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004258
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004259 // Verify that the elements are compatible with the structtype.
4260 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4261 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4262 return Error(ID.Loc, "element " + Twine(i) +
4263 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004264
David Blaikieadbda4b2015-08-03 20:08:41 +00004265 V = ConstantStruct::get(
4266 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004267 } else
4268 return Error(ID.Loc, "constant expression type mismatch");
4269 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004270 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004271 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004272}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004273
Alex Lorenzd2255952015-07-17 22:07:03 +00004274bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4275 C = nullptr;
4276 ValID ID;
4277 auto Loc = Lex.getLoc();
4278 if (ParseValID(ID, /*PFS=*/nullptr))
4279 return true;
4280 switch (ID.Kind) {
4281 case ValID::t_APSInt:
4282 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004283 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004284 case ValID::t_Constant:
4285 case ValID::t_ConstantStruct:
4286 case ValID::t_PackedConstantStruct: {
4287 Value *V;
4288 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4289 return true;
4290 assert(isa<Constant>(V) && "Expected a constant value");
4291 C = cast<Constant>(V);
4292 return false;
4293 }
4294 default:
4295 return Error(Loc, "expected a constant value");
4296 }
4297}
4298
David Majnemer8a1c45d2015-12-12 05:38:55 +00004299bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004300 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004301 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004302 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004303}
4304
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004305bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004306 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004307 return ParseType(Ty) ||
4308 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004309}
4310
Chris Lattner3ed871f2009-10-27 19:13:16 +00004311bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4312 PerFunctionState &PFS) {
4313 Value *V;
4314 Loc = Lex.getLoc();
4315 if (ParseTypeAndValue(V, PFS)) return true;
4316 if (!isa<BasicBlock>(V))
4317 return Error(Loc, "expected a basic block");
4318 BB = cast<BasicBlock>(V);
4319 return false;
4320}
4321
4322
Chris Lattnerac161bf2009-01-02 07:01:27 +00004323/// FunctionHeader
4324/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004325/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004326/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004327bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4328 // Parse the linkage.
4329 LocTy LinkageLoc = Lex.getLoc();
4330 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004331
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004332 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004333 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004334 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004335 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004336 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004337 LocTy RetTypeLoc = Lex.getLoc();
4338 if (ParseOptionalLinkage(Linkage) ||
4339 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00004340 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004341 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004342 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004343 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004344 return true;
4345
4346 // Verify that the linkage is ok.
4347 switch ((GlobalValue::LinkageTypes)Linkage) {
4348 case GlobalValue::ExternalLinkage:
4349 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004350 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004351 if (isDefine)
4352 return Error(LinkageLoc, "invalid linkage for function definition");
4353 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004354 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004355 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004356 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004357 case GlobalValue::LinkOnceAnyLinkage:
4358 case GlobalValue::LinkOnceODRLinkage:
4359 case GlobalValue::WeakAnyLinkage:
4360 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004361 if (!isDefine)
4362 return Error(LinkageLoc, "invalid linkage for function declaration");
4363 break;
4364 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004365 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004366 return Error(LinkageLoc, "invalid function linkage type");
4367 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004368
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004369 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4370 return Error(LinkageLoc,
4371 "symbol with local linkage must have default visibility");
4372
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004373 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004374 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004375
Chris Lattnerac161bf2009-01-02 07:01:27 +00004376 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004377
4378 std::string FunctionName;
4379 if (Lex.getKind() == lltok::GlobalVar) {
4380 FunctionName = Lex.getStrVal();
4381 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4382 unsigned NameID = Lex.getUIntVal();
4383
4384 if (NameID != NumberedVals.size())
4385 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004386 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004387 } else {
4388 return TokError("expected function name");
4389 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004390
Chris Lattner3822f632009-01-02 08:05:26 +00004391 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004392
Chris Lattner3822f632009-01-02 08:05:26 +00004393 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004394 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004395
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004396 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004397 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004398 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004399 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004400 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004401 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004402 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004403 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004404 bool UnnamedAddr;
4405 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004406 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004407 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004408 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004409 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004410
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004411 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004412 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4413 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004414 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004415 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004416 (EatIfPresent(lltok::kw_section) &&
4417 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004418 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004419 ParseOptionalAlignment(Alignment) ||
4420 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004421 ParseStringConstant(GC)) ||
4422 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004423 ParseGlobalTypeAndValue(Prefix)) ||
4424 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004425 ParseGlobalTypeAndValue(Prologue)) ||
4426 (EatIfPresent(lltok::kw_personality) &&
4427 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004428 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004429
Michael Gottesman41748d72013-06-27 00:25:01 +00004430 if (FuncAttrs.contains(Attribute::Builtin))
4431 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004432
Chris Lattnerac161bf2009-01-02 07:01:27 +00004433 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004434 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004435 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004436 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004437 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004438
Chris Lattnerac161bf2009-01-02 07:01:27 +00004439 // Okay, if we got here, the function is syntactically valid. Convert types
4440 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004441 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004442 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004443
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004444 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004445 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4446 AttributeSet::ReturnIndex,
4447 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004448
Chris Lattnerac161bf2009-01-02 07:01:27 +00004449 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004450 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004451 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4452 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004453 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4454 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004455 }
4456
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004457 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004458 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4459 AttributeSet::FunctionIndex,
4460 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004461
Bill Wendlinge94d8432012-12-07 23:16:57 +00004462 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004463
Bill Wendling749a43d2012-12-30 13:50:49 +00004464 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004465 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4466
Chris Lattner229907c2011-07-18 04:54:35 +00004467 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004468 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004469 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004470
Craig Topper2617dcc2014-04-15 06:32:26 +00004471 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004472 if (!FunctionName.empty()) {
4473 // If this was a definition of a forward reference, remove the definition
4474 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004475 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004476 if (FRVI != ForwardRefVals.end()) {
4477 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004478 if (!Fn)
4479 return Error(FRVI->second.second, "invalid forward reference to "
4480 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004481 if (Fn->getType() != PFT)
4482 return Error(FRVI->second.second, "invalid forward reference to "
4483 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004484
Chris Lattnerac161bf2009-01-02 07:01:27 +00004485 ForwardRefVals.erase(FRVI);
4486 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004487 // Reject redefinitions.
4488 return Error(NameLoc, "invalid redefinition of function '" +
4489 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004490 } else if (M->getNamedValue(FunctionName)) {
4491 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004492 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004493
Dan Gohman399d6ae2009-08-29 23:37:49 +00004494 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004495 // If this is a definition of a forward referenced function, make sure the
4496 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004497 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004498 if (I != ForwardRefValIDs.end()) {
4499 Fn = cast<Function>(I->second.first);
4500 if (Fn->getType() != PFT)
4501 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004502 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004503 ForwardRefValIDs.erase(I);
4504 }
4505 }
4506
Craig Topper2617dcc2014-04-15 06:32:26 +00004507 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004508 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4509 else // Move the forward-reference to the correct spot in the module.
4510 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4511
4512 if (FunctionName.empty())
4513 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004514
Chris Lattnerac161bf2009-01-02 07:01:27 +00004515 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4516 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004517 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004518 Fn->setCallingConv(CC);
4519 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004520 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004521 Fn->setAlignment(Alignment);
4522 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004523 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004524 Fn->setPersonalityFn(PersonalityFn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004525 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004526 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004527 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004528 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004529
Chris Lattnerac161bf2009-01-02 07:01:27 +00004530 // Add all of the arguments we parsed to the function.
4531 Function::arg_iterator ArgIt = Fn->arg_begin();
4532 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4533 // If the argument has a name, insert it into the argument symbol table.
4534 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004535
Chris Lattnerac161bf2009-01-02 07:01:27 +00004536 // Set the name, if it conflicted, it will be auto-renamed.
4537 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004538
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004539 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004540 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4541 ArgList[i].Name + "'");
4542 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004543
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004544 if (isDefine)
4545 return false;
4546
Robin Morisset039781e2014-08-29 21:53:01 +00004547 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004548 ValID ID;
4549 if (FunctionName.empty()) {
4550 ID.Kind = ValID::t_GlobalID;
4551 ID.UIntVal = NumberedVals.size() - 1;
4552 } else {
4553 ID.Kind = ValID::t_GlobalName;
4554 ID.StrVal = FunctionName;
4555 }
4556 auto Blocks = ForwardRefBlockAddresses.find(ID);
4557 if (Blocks != ForwardRefBlockAddresses.end())
4558 return Error(Blocks->first.Loc,
4559 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004560 return false;
4561}
4562
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004563bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4564 ValID ID;
4565 if (FunctionNumber == -1) {
4566 ID.Kind = ValID::t_GlobalName;
4567 ID.StrVal = F.getName();
4568 } else {
4569 ID.Kind = ValID::t_GlobalID;
4570 ID.UIntVal = FunctionNumber;
4571 }
4572
4573 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4574 if (Blocks == P.ForwardRefBlockAddresses.end())
4575 return false;
4576
4577 for (const auto &I : Blocks->second) {
4578 const ValID &BBID = I.first;
4579 GlobalValue *GV = I.second;
4580
4581 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4582 "Expected local id or name");
4583 BasicBlock *BB;
4584 if (BBID.Kind == ValID::t_LocalName)
4585 BB = GetBB(BBID.StrVal, BBID.Loc);
4586 else
4587 BB = GetBB(BBID.UIntVal, BBID.Loc);
4588 if (!BB)
4589 return P.Error(BBID.Loc, "referenced value is not a basic block");
4590
4591 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4592 GV->eraseFromParent();
4593 }
4594
4595 P.ForwardRefBlockAddresses.erase(Blocks);
4596 return false;
4597}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004598
4599/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004600/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004601bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004602 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004603 return TokError("expected '{' in function body");
4604 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004605
Chris Lattner3432c622009-10-28 03:39:23 +00004606 int FunctionNumber = -1;
4607 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004608
Chris Lattner3432c622009-10-28 03:39:23 +00004609 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004610
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004611 // Resolve block addresses and allow basic blocks to be forward-declared
4612 // within this function.
4613 if (PFS.resolveForwardRefBlockAddresses())
4614 return true;
4615 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4616
Chris Lattnerbbddd962010-01-09 19:20:07 +00004617 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004618 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004619 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004620
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004621 while (Lex.getKind() != lltok::rbrace &&
4622 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004623 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004624
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004625 while (Lex.getKind() != lltok::rbrace)
4626 if (ParseUseListOrder(&PFS))
4627 return true;
4628
Chris Lattnerac161bf2009-01-02 07:01:27 +00004629 // Eat the }.
4630 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004631
Chris Lattnerac161bf2009-01-02 07:01:27 +00004632 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004633 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004634}
4635
4636/// ParseBasicBlock
4637/// ::= LabelStr? Instruction*
4638bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4639 // If this basic block starts out with a name, remember it.
4640 std::string Name;
4641 LocTy NameLoc = Lex.getLoc();
4642 if (Lex.getKind() == lltok::LabelStr) {
4643 Name = Lex.getStrVal();
4644 Lex.Lex();
4645 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004646
Chris Lattnerac161bf2009-01-02 07:01:27 +00004647 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004648 if (!BB)
4649 return Error(NameLoc,
4650 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004651
Chris Lattnerac161bf2009-01-02 07:01:27 +00004652 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004653
Chris Lattnerac161bf2009-01-02 07:01:27 +00004654 // Parse the instructions in this block until we get a terminator.
4655 Instruction *Inst;
4656 do {
4657 // This instruction may have three possibilities for a name: a) none
4658 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4659 LocTy NameLoc = Lex.getLoc();
4660 int NameID = -1;
4661 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004662
Chris Lattnerac161bf2009-01-02 07:01:27 +00004663 if (Lex.getKind() == lltok::LocalVarID) {
4664 NameID = Lex.getUIntVal();
4665 Lex.Lex();
4666 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4667 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004668 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004669 NameStr = Lex.getStrVal();
4670 Lex.Lex();
4671 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4672 return true;
4673 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004674
Chris Lattner77b89dc2009-12-30 05:23:43 +00004675 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004676 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004677 case InstError: return true;
4678 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004679 BB->getInstList().push_back(Inst);
4680
Chris Lattner77b89dc2009-12-30 05:23:43 +00004681 // With a normal result, we check to see if the instruction is followed by
4682 // a comma and metadata.
4683 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004684 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004685 return true;
4686 break;
4687 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004688 BB->getInstList().push_back(Inst);
4689
Chris Lattner77b89dc2009-12-30 05:23:43 +00004690 // If the instruction parser ate an extra comma at the end of it, it
4691 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004692 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004693 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004694 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004695 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004696
Chris Lattnerac161bf2009-01-02 07:01:27 +00004697 // Set the name on the instruction.
4698 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4699 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004700
Chris Lattnerac161bf2009-01-02 07:01:27 +00004701 return false;
4702}
4703
4704//===----------------------------------------------------------------------===//
4705// Instruction Parsing.
4706//===----------------------------------------------------------------------===//
4707
4708/// ParseInstruction - Parse one of the many different instructions.
4709///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004710int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4711 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004712 lltok::Kind Token = Lex.getKind();
4713 if (Token == lltok::Eof)
4714 return TokError("found end of file when expecting more instructions");
4715 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004716 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004717 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004718
Chris Lattnerac161bf2009-01-02 07:01:27 +00004719 switch (Token) {
4720 default: return Error(Loc, "expected instruction opcode");
4721 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004722 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004723 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4724 case lltok::kw_br: return ParseBr(Inst, PFS);
4725 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004726 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004727 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004728 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00004729 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4730 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004731 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
4732 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004733 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004734 // Binary Operators.
4735 case lltok::kw_add:
4736 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004737 case lltok::kw_mul:
4738 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004739 bool NUW = EatIfPresent(lltok::kw_nuw);
4740 bool NSW = EatIfPresent(lltok::kw_nsw);
4741 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004742
Chris Lattnera676c0f2011-02-07 16:40:21 +00004743 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004744
Chris Lattnera676c0f2011-02-07 16:40:21 +00004745 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4746 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4747 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004748 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004749 case lltok::kw_fadd:
4750 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004751 case lltok::kw_fmul:
4752 case lltok::kw_fdiv:
4753 case lltok::kw_frem: {
4754 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4755 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4756 if (Res != 0)
4757 return Res;
4758 if (FMF.any())
4759 Inst->setFastMathFlags(FMF);
4760 return 0;
4761 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004762
Chris Lattner35315d02011-02-06 21:44:57 +00004763 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004764 case lltok::kw_udiv:
4765 case lltok::kw_lshr:
4766 case lltok::kw_ashr: {
4767 bool Exact = EatIfPresent(lltok::kw_exact);
4768
4769 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4770 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4771 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004772 }
4773
Chris Lattnerac161bf2009-01-02 07:01:27 +00004774 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004775 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004776 case lltok::kw_and:
4777 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004778 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00004779 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4780 case lltok::kw_fcmp: {
4781 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4782 int Res = ParseCompare(Inst, PFS, KeywordVal);
4783 if (Res != 0)
4784 return Res;
4785 if (FMF.any())
4786 Inst->setFastMathFlags(FMF);
4787 return 0;
4788 }
4789
Chris Lattnerac161bf2009-01-02 07:01:27 +00004790 // Casts.
4791 case lltok::kw_trunc:
4792 case lltok::kw_zext:
4793 case lltok::kw_sext:
4794 case lltok::kw_fptrunc:
4795 case lltok::kw_fpext:
4796 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004797 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004798 case lltok::kw_uitofp:
4799 case lltok::kw_sitofp:
4800 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004801 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004802 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004803 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004804 // Other.
4805 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004806 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004807 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4808 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4809 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4810 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004811 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004812 // Call.
4813 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4814 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4815 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00004816 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004817 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004818 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004819 case lltok::kw_load: return ParseLoad(Inst, PFS);
4820 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004821 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4822 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004823 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004824 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4825 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4826 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4827 }
4828}
4829
4830/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4831bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004832 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004833 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004834 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004835 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4836 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4837 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4838 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4839 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4840 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4841 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4842 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4843 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4844 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4845 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4846 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4847 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4848 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4849 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4850 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4851 }
4852 } else {
4853 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004854 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004855 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4856 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4857 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4858 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4859 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4860 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4861 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4862 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4863 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4864 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4865 }
4866 }
4867 Lex.Lex();
4868 return false;
4869}
4870
4871//===----------------------------------------------------------------------===//
4872// Terminator Instructions.
4873//===----------------------------------------------------------------------===//
4874
4875/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00004876/// ::= 'ret' void (',' !dbg, !1)*
4877/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00004878bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004879 PerFunctionState &PFS) {
4880 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00004881 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00004882 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004883
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004884 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004885
Chris Lattnerfdd87902009-10-05 05:54:46 +00004886 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004887 if (!ResType->isVoidTy())
4888 return Error(TypeLoc, "value doesn't match function result type '" +
4889 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004890
Owen Anderson55f1c092009-08-13 21:58:54 +00004891 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004892 return false;
4893 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004894
Chris Lattnerac161bf2009-01-02 07:01:27 +00004895 Value *RV;
4896 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004897
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004898 if (ResType != RV->getType())
4899 return Error(TypeLoc, "value doesn't match function result type '" +
4900 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004901
Owen Anderson55f1c092009-08-13 21:58:54 +00004902 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00004903 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004904}
4905
4906
4907/// ParseBr
4908/// ::= 'br' TypeAndValue
4909/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4910bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4911 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004912 Value *Op0;
4913 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004914 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004915
Chris Lattnerac161bf2009-01-02 07:01:27 +00004916 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4917 Inst = BranchInst::Create(BB);
4918 return false;
4919 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004920
Owen Anderson55f1c092009-08-13 21:58:54 +00004921 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004922 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004923
Chris Lattnerac161bf2009-01-02 07:01:27 +00004924 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004925 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004926 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004927 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004928 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004929
Chris Lattner3ed871f2009-10-27 19:13:16 +00004930 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004931 return false;
4932}
4933
4934/// ParseSwitch
4935/// Instruction
4936/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4937/// JumpTable
4938/// ::= (TypeAndValue ',' TypeAndValue)*
4939bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4940 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004941 Value *Cond;
4942 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004943 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4944 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004945 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004946 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4947 return true;
4948
Duncan Sands19d0b472010-02-16 11:11:14 +00004949 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004950 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004951
Chris Lattnerac161bf2009-01-02 07:01:27 +00004952 // Parse the jump table pairs.
4953 SmallPtrSet<Value*, 32> SeenCases;
4954 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4955 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004956 Value *Constant;
4957 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004958
Chris Lattnerac161bf2009-01-02 07:01:27 +00004959 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4960 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004961 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004962 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004963
David Blaikie70573dc2014-11-19 07:49:26 +00004964 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004965 return Error(CondLoc, "duplicate case value in switch");
4966 if (!isa<ConstantInt>(Constant))
4967 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004968
Chris Lattner3ed871f2009-10-27 19:13:16 +00004969 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004970 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004971
Chris Lattnerac161bf2009-01-02 07:01:27 +00004972 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004973
Chris Lattner3ed871f2009-10-27 19:13:16 +00004974 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004975 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4976 SI->addCase(Table[i].first, Table[i].second);
4977 Inst = SI;
4978 return false;
4979}
4980
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004981/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00004982/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004983/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4984bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004985 LocTy AddrLoc;
4986 Value *Address;
4987 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004988 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4989 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00004990 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004991
Duncan Sands19d0b472010-02-16 11:11:14 +00004992 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004993 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004994
Chris Lattner3ed871f2009-10-27 19:13:16 +00004995 // Parse the destination list.
4996 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004997
Chris Lattner3ed871f2009-10-27 19:13:16 +00004998 if (Lex.getKind() != lltok::rsquare) {
4999 BasicBlock *DestBB;
5000 if (ParseTypeAndBasicBlock(DestBB, PFS))
5001 return true;
5002 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005003
Chris Lattner3ed871f2009-10-27 19:13:16 +00005004 while (EatIfPresent(lltok::comma)) {
5005 if (ParseTypeAndBasicBlock(DestBB, PFS))
5006 return true;
5007 DestList.push_back(DestBB);
5008 }
5009 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005010
Chris Lattner3ed871f2009-10-27 19:13:16 +00005011 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5012 return true;
5013
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005014 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005015 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5016 IBI->addDestination(DestList[i]);
5017 Inst = IBI;
5018 return false;
5019}
5020
5021
Chris Lattnerac161bf2009-01-02 07:01:27 +00005022/// ParseInvoke
5023/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5024/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5025bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5026 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005027 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005028 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005029 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005030 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005031 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005032 LocTy RetTypeLoc;
5033 ValID CalleeID;
5034 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005035 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005036
Chris Lattner3ed871f2009-10-27 19:13:16 +00005037 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005038 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005039 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005040 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005041 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5042 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005043 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005044 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005045 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005046 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005047 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005048 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005049
Chris Lattnerac161bf2009-01-02 07:01:27 +00005050 // If RetType is a non-function pointer type, then this is the short syntax
5051 // for the call, which means that RetType is just the return type. Infer the
5052 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005053 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5054 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005055 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005056 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005057 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5058 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005059
Chris Lattnerac161bf2009-01-02 07:01:27 +00005060 if (!FunctionType::isValidReturnType(RetType))
5061 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005062
Owen Anderson4056ca92009-07-29 22:17:13 +00005063 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005064 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005065
David Blaikie41ba2b42015-07-27 23:32:19 +00005066 CalleeID.FTy = Ty;
5067
Chris Lattnerac161bf2009-01-02 07:01:27 +00005068 // Look up the callee.
5069 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005070 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5071 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005072
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005073 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005074 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005075 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005076 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5077 AttributeSet::ReturnIndex,
5078 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005079
Chris Lattnerac161bf2009-01-02 07:01:27 +00005080 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005081
Chris Lattnerac161bf2009-01-02 07:01:27 +00005082 // Loop through FunctionType's arguments and ensure they are specified
5083 // correctly. Also, gather any parameter attributes.
5084 FunctionType::param_iterator I = Ty->param_begin();
5085 FunctionType::param_iterator E = Ty->param_end();
5086 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005087 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005088 if (I != E) {
5089 ExpectedTy = *I++;
5090 } else if (!Ty->isVarArg()) {
5091 return Error(ArgList[i].Loc, "too many arguments specified");
5092 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005093
Chris Lattnerac161bf2009-01-02 07:01:27 +00005094 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5095 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005096 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005097 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005098 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5099 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005100 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5101 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005102 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005103
Chris Lattnerac161bf2009-01-02 07:01:27 +00005104 if (I != E)
5105 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005106
David Majnemer8d22abd2015-02-23 00:01:32 +00005107 if (FnAttrs.hasAttributes()) {
5108 if (FnAttrs.hasAlignmentAttr())
5109 return Error(CallLoc, "invoke instructions may not have an alignment");
5110
Bill Wendlingf5075a42013-01-27 02:24:02 +00005111 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5112 AttributeSet::FunctionIndex,
5113 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005114 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005115
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005116 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005117 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005118
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005119 InvokeInst *II =
5120 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005121 II->setCallingConv(CC);
5122 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005123 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005124 Inst = II;
5125 return false;
5126}
5127
Bill Wendlingf891bf82011-07-31 06:30:59 +00005128/// ParseResume
5129/// ::= 'resume' TypeAndValue
5130bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5131 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005132 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5133 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005134
Bill Wendlingf891bf82011-07-31 06:30:59 +00005135 ResumeInst *RI = ResumeInst::Create(Exn);
5136 Inst = RI;
5137 return false;
5138}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005139
David Majnemer654e1302015-07-31 17:58:14 +00005140bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5141 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005142 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005143 return true;
5144
5145 while (Lex.getKind() != lltok::rsquare) {
5146 // If this isn't the first argument, we need a comma.
5147 if (!Args.empty() &&
5148 ParseToken(lltok::comma, "expected ',' in argument list"))
5149 return true;
5150
5151 // Parse the argument.
5152 LocTy ArgLoc;
5153 Type *ArgTy = nullptr;
5154 if (ParseType(ArgTy, ArgLoc))
5155 return true;
5156
5157 Value *V;
5158 if (ArgTy->isMetadataTy()) {
5159 if (ParseMetadataAsValue(V, PFS))
5160 return true;
5161 } else {
5162 if (ParseValue(ArgTy, V, PFS))
5163 return true;
5164 }
5165 Args.push_back(V);
5166 }
5167
5168 Lex.Lex(); // Lex the ']'.
5169 return false;
5170}
5171
5172/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005173/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005174bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005175 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005176
David Majnemer8a1c45d2015-12-12 05:38:55 +00005177 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5178 return true;
5179
5180 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005181 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005182
5183 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5184 return true;
5185
5186 BasicBlock *UnwindBB = nullptr;
5187 if (Lex.getKind() == lltok::kw_to) {
5188 Lex.Lex();
5189 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5190 return true;
5191 } else {
5192 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5193 return true;
5194 }
5195 }
5196
David Majnemer8a1c45d2015-12-12 05:38:55 +00005197 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005198 return false;
5199}
5200
5201/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005202/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005203bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005204 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005205
David Majnemer8a1c45d2015-12-12 05:38:55 +00005206 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5207 return true;
5208
5209 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005210 return true;
5211
David Majnemer0bc0eef2015-08-15 02:46:08 +00005212 BasicBlock *BB;
5213 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5214 ParseTypeAndBasicBlock(BB, PFS))
5215 return true;
5216
David Majnemer8a1c45d2015-12-12 05:38:55 +00005217 Inst = CatchReturnInst::Create(CatchPad, BB);
5218 return false;
5219}
5220
5221/// ParseCatchSwitch
5222/// ::= 'catchswitch' within Parent
5223bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5224 Value *ParentPad;
5225 LocTy BBLoc;
5226
5227 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5228 return true;
5229
5230 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5231 Lex.getKind() != lltok::LocalVarID)
5232 return TokError("expected scope value for catchswitch");
5233
5234 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5235 return true;
5236
5237 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5238 return true;
5239
5240 SmallVector<BasicBlock *, 32> Table;
5241 do {
5242 BasicBlock *DestBB;
5243 if (ParseTypeAndBasicBlock(DestBB, PFS))
5244 return true;
5245 Table.push_back(DestBB);
5246 } while (EatIfPresent(lltok::comma));
5247
5248 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5249 return true;
5250
5251 if (ParseToken(lltok::kw_unwind,
5252 "expected 'unwind' after catchswitch scope"))
5253 return true;
5254
5255 BasicBlock *UnwindBB = nullptr;
5256 if (EatIfPresent(lltok::kw_to)) {
5257 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5258 return true;
5259 } else {
5260 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5261 return true;
5262 }
5263
5264 auto *CatchSwitch =
5265 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5266 for (BasicBlock *DestBB : Table)
5267 CatchSwitch->addHandler(DestBB);
5268 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005269 return false;
5270}
5271
5272/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005273/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005274bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005275 Value *CatchSwitch = nullptr;
5276
5277 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5278 return true;
5279
5280 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5281 return TokError("expected scope value for catchpad");
5282
5283 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5284 return true;
5285
David Majnemer654e1302015-07-31 17:58:14 +00005286 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005287 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005288 return true;
5289
David Majnemer8a1c45d2015-12-12 05:38:55 +00005290 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005291 return false;
5292}
5293
David Majnemer654e1302015-07-31 17:58:14 +00005294/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005295/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005296bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005297 Value *ParentPad = nullptr;
5298
5299 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5300 return true;
5301
5302 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5303 Lex.getKind() != lltok::LocalVarID)
5304 return TokError("expected scope value for cleanuppad");
5305
5306 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5307 return true;
5308
David Majnemer654e1302015-07-31 17:58:14 +00005309 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005310 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005311 return true;
5312
David Majnemer8a1c45d2015-12-12 05:38:55 +00005313 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005314 return false;
5315}
5316
Chris Lattnerac161bf2009-01-02 07:01:27 +00005317//===----------------------------------------------------------------------===//
5318// Binary Operators.
5319//===----------------------------------------------------------------------===//
5320
5321/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005322/// ::= ArithmeticOps TypeAndValue ',' Value
5323///
5324/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5325/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005326bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005327 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005328 LocTy Loc; Value *LHS, *RHS;
5329 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5330 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5331 ParseValue(LHS->getType(), RHS, PFS))
5332 return true;
5333
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005334 bool Valid;
5335 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005336 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005337 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005338 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5339 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005340 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005341 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5342 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005343 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005344
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005345 if (!Valid)
5346 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005347
Chris Lattnerac161bf2009-01-02 07:01:27 +00005348 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5349 return false;
5350}
5351
5352/// ParseLogical
5353/// ::= ArithmeticOps TypeAndValue ',' Value {
5354bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5355 unsigned Opc) {
5356 LocTy Loc; Value *LHS, *RHS;
5357 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5358 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5359 ParseValue(LHS->getType(), RHS, PFS))
5360 return true;
5361
Duncan Sands9dff9be2010-02-15 16:12:20 +00005362 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005363 return Error(Loc,"instruction requires integer or integer vector operands");
5364
5365 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5366 return false;
5367}
5368
5369
5370/// ParseCompare
5371/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5372/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005373bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5374 unsigned Opc) {
5375 // Parse the integer/fp comparison predicate.
5376 LocTy Loc;
5377 unsigned Pred;
5378 Value *LHS, *RHS;
5379 if (ParseCmpPredicate(Pred, Opc) ||
5380 ParseTypeAndValue(LHS, Loc, PFS) ||
5381 ParseToken(lltok::comma, "expected ',' after compare value") ||
5382 ParseValue(LHS->getType(), RHS, PFS))
5383 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005384
Chris Lattnerac161bf2009-01-02 07:01:27 +00005385 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005386 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005387 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005388 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005389 } else {
5390 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005391 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005392 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005393 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005394 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005395 }
5396 return false;
5397}
5398
5399//===----------------------------------------------------------------------===//
5400// Other Instructions.
5401//===----------------------------------------------------------------------===//
5402
5403
5404/// ParseCast
5405/// ::= CastOpc TypeAndValue 'to' Type
5406bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5407 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005408 LocTy Loc;
5409 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005410 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005411 if (ParseTypeAndValue(Op, Loc, PFS) ||
5412 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5413 ParseType(DestTy))
5414 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005415
Chris Lattner89d856e2009-03-01 00:53:13 +00005416 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5417 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005418 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005419 getTypeString(Op->getType()) + "' to '" +
5420 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005421 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005422 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5423 return false;
5424}
5425
5426/// ParseSelect
5427/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5428bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5429 LocTy Loc;
5430 Value *Op0, *Op1, *Op2;
5431 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5432 ParseToken(lltok::comma, "expected ',' after select condition") ||
5433 ParseTypeAndValue(Op1, PFS) ||
5434 ParseToken(lltok::comma, "expected ',' after select value") ||
5435 ParseTypeAndValue(Op2, PFS))
5436 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005437
Chris Lattnerac161bf2009-01-02 07:01:27 +00005438 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5439 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005440
Chris Lattnerac161bf2009-01-02 07:01:27 +00005441 Inst = SelectInst::Create(Op0, Op1, Op2);
5442 return false;
5443}
5444
Chris Lattnerb55ab542009-01-05 08:18:44 +00005445/// ParseVA_Arg
5446/// ::= 'va_arg' TypeAndValue ',' Type
5447bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005448 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005449 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005450 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005451 if (ParseTypeAndValue(Op, PFS) ||
5452 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005453 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005454 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005455
Chris Lattnerb55ab542009-01-05 08:18:44 +00005456 if (!EltTy->isFirstClassType())
5457 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005458
5459 Inst = new VAArgInst(Op, EltTy);
5460 return false;
5461}
5462
5463/// ParseExtractElement
5464/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5465bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5466 LocTy Loc;
5467 Value *Op0, *Op1;
5468 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5469 ParseToken(lltok::comma, "expected ',' after extract value") ||
5470 ParseTypeAndValue(Op1, PFS))
5471 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005472
Chris Lattnerac161bf2009-01-02 07:01:27 +00005473 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5474 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005475
Eric Christopherc9742252009-07-25 02:28:41 +00005476 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005477 return false;
5478}
5479
5480/// ParseInsertElement
5481/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5482bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5483 LocTy Loc;
5484 Value *Op0, *Op1, *Op2;
5485 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5486 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5487 ParseTypeAndValue(Op1, PFS) ||
5488 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5489 ParseTypeAndValue(Op2, PFS))
5490 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005491
Chris Lattnerac161bf2009-01-02 07:01:27 +00005492 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005493 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005494
Chris Lattnerac161bf2009-01-02 07:01:27 +00005495 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5496 return false;
5497}
5498
5499/// ParseShuffleVector
5500/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5501bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5502 LocTy Loc;
5503 Value *Op0, *Op1, *Op2;
5504 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5505 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5506 ParseTypeAndValue(Op1, PFS) ||
5507 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5508 ParseTypeAndValue(Op2, PFS))
5509 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005510
Chris Lattnerac161bf2009-01-02 07:01:27 +00005511 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005512 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005513
Chris Lattnerac161bf2009-01-02 07:01:27 +00005514 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5515 return false;
5516}
5517
5518/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005519/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005520int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005521 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005522 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005523
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005524 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005525 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5526 ParseValue(Ty, Op0, PFS) ||
5527 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005528 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005529 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5530 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005531
Chris Lattnerf4f03422009-12-30 05:27:33 +00005532 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005533 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5534 while (1) {
5535 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005536
Chris Lattner3822f632009-01-02 08:05:26 +00005537 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005538 break;
5539
Chris Lattnerf4f03422009-12-30 05:27:33 +00005540 if (Lex.getKind() == lltok::MetadataVar) {
5541 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005542 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005543 }
Devang Patel8f842d32009-10-16 18:45:49 +00005544
Chris Lattner3822f632009-01-02 08:05:26 +00005545 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005546 ParseValue(Ty, Op0, PFS) ||
5547 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005548 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005549 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5550 return true;
5551 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005552
Chris Lattnerac161bf2009-01-02 07:01:27 +00005553 if (!Ty->isFirstClassType())
5554 return Error(TypeLoc, "phi node must have first class type");
5555
Jay Foad52131342011-03-30 11:28:46 +00005556 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005557 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5558 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5559 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005560 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005561}
5562
Bill Wendlingfae14752011-08-12 20:24:12 +00005563/// ParseLandingPad
5564/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5565/// Clause
5566/// ::= 'catch' TypeAndValue
5567/// ::= 'filter'
5568/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5569bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005570 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005571
David Majnemer7fddecc2015-06-17 20:52:32 +00005572 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005573 return true;
5574
David Majnemer7fddecc2015-06-17 20:52:32 +00005575 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005576 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5577
5578 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5579 LandingPadInst::ClauseType CT;
5580 if (EatIfPresent(lltok::kw_catch))
5581 CT = LandingPadInst::Catch;
5582 else if (EatIfPresent(lltok::kw_filter))
5583 CT = LandingPadInst::Filter;
5584 else
5585 return TokError("expected 'catch' or 'filter' clause type");
5586
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005587 Value *V;
5588 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005589 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005590 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005591
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005592 // A 'catch' type expects a non-array constant. A filter clause expects an
5593 // array constant.
5594 if (CT == LandingPadInst::Catch) {
5595 if (isa<ArrayType>(V->getType()))
5596 Error(VLoc, "'catch' clause has an invalid type");
5597 } else {
5598 if (!isa<ArrayType>(V->getType()))
5599 Error(VLoc, "'filter' clause has an invalid type");
5600 }
5601
Owen Andersonf8f259d2015-03-09 07:13:42 +00005602 Constant *CV = dyn_cast<Constant>(V);
5603 if (!CV)
5604 return Error(VLoc, "clause argument must be a constant");
5605 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005606 }
5607
Owen Andersonf8f259d2015-03-09 07:13:42 +00005608 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005609 return false;
5610}
5611
Chris Lattnerac161bf2009-01-02 07:01:27 +00005612/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005613/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5614/// OptionalAttrs Type Value ParameterList OptionalAttrs
5615/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5616/// OptionalAttrs Type Value ParameterList OptionalAttrs
5617/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5618/// OptionalAttrs Type Value ParameterList OptionalAttrs
5619/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5620/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005621bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005622 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005623 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005624 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005625 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005626 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005627 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005628 LocTy RetTypeLoc;
5629 ValID CalleeID;
5630 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005631 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005632 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005633
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005634 if (TCK != CallInst::TCK_None &&
5635 ParseToken(lltok::kw_call,
5636 "expected 'tail call', 'musttail call', or 'notail call'"))
5637 return true;
5638
5639 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5640
5641 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005642 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005643 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005644 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5645 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005646 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5647 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005648 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005649
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005650 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5651 return Error(CallLoc, "fast-math-flags specified for call without "
5652 "floating-point scalar or vector return type");
5653
Chris Lattnerac161bf2009-01-02 07:01:27 +00005654 // If RetType is a non-function pointer type, then this is the short syntax
5655 // for the call, which means that RetType is just the return type. Infer the
5656 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005657 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5658 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005659 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005660 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005661 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5662 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005663
Chris Lattnerac161bf2009-01-02 07:01:27 +00005664 if (!FunctionType::isValidReturnType(RetType))
5665 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005666
Owen Anderson4056ca92009-07-29 22:17:13 +00005667 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005668 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005669
David Blaikie41ba2b42015-07-27 23:32:19 +00005670 CalleeID.FTy = Ty;
5671
Chris Lattnerac161bf2009-01-02 07:01:27 +00005672 // Look up the callee.
5673 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005674 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5675 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005676
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005677 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005678 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005679 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005680 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5681 AttributeSet::ReturnIndex,
5682 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005683
Chris Lattnerac161bf2009-01-02 07:01:27 +00005684 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005685
Chris Lattnerac161bf2009-01-02 07:01:27 +00005686 // Loop through FunctionType's arguments and ensure they are specified
5687 // correctly. Also, gather any parameter attributes.
5688 FunctionType::param_iterator I = Ty->param_begin();
5689 FunctionType::param_iterator E = Ty->param_end();
5690 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005691 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005692 if (I != E) {
5693 ExpectedTy = *I++;
5694 } else if (!Ty->isVarArg()) {
5695 return Error(ArgList[i].Loc, "too many arguments specified");
5696 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005697
Chris Lattnerac161bf2009-01-02 07:01:27 +00005698 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5699 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005700 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005701 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005702 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5703 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005704 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5705 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005706 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005707
Chris Lattnerac161bf2009-01-02 07:01:27 +00005708 if (I != E)
5709 return Error(CallLoc, "not enough parameters specified for call");
5710
David Majnemer8d22abd2015-02-23 00:01:32 +00005711 if (FnAttrs.hasAttributes()) {
5712 if (FnAttrs.hasAlignmentAttr())
5713 return Error(CallLoc, "call instructions may not have an alignment");
5714
Bill Wendlingf5075a42013-01-27 02:24:02 +00005715 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5716 AttributeSet::FunctionIndex,
5717 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005718 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005719
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005720 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005721 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005722
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005723 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00005724 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005725 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005726 if (FMF.any())
5727 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005728 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005729 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005730 Inst = CI;
5731 return false;
5732}
5733
5734//===----------------------------------------------------------------------===//
5735// Memory Instructions.
5736//===----------------------------------------------------------------------===//
5737
5738/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00005739/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005740int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005741 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005742 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005743 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005744 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005745
5746 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5747
David Majnemera3b0eb22015-02-16 08:38:03 +00005748 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005749
David Majnemera3b0eb22015-02-16 08:38:03 +00005750 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5751 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005752
Chris Lattnerb2f39502009-12-30 05:44:30 +00005753 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005754 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005755 if (Lex.getKind() == lltok::kw_align) {
5756 if (ParseOptionalAlignment(Alignment)) return true;
5757 } else if (Lex.getKind() == lltok::MetadataVar) {
5758 AteExtraComma = true;
5759 } else {
5760 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5761 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5762 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005763 }
5764 }
5765
Dan Gohman2140a742010-05-28 01:14:11 +00005766 if (Size && !Size->getType()->isIntegerTy())
5767 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005768
Reid Kleckner436c42e2014-01-17 23:58:17 +00005769 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5770 AI->setUsedWithInAlloca(IsInAlloca);
5771 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005772 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005773}
5774
5775/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005776/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005777/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005778/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005779int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005780 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005781 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005782 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005783 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005784 AtomicOrdering Ordering = NotAtomic;
5785 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005786
5787 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005788 isAtomic = true;
5789 Lex.Lex();
5790 }
5791
Chris Lattnerbc639292011-11-27 06:56:53 +00005792 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005793 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005794 isVolatile = true;
5795 Lex.Lex();
5796 }
5797
David Blaikie15d9a4c2015-04-06 20:59:48 +00005798 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005799 LocTy ExplicitTypeLoc = Lex.getLoc();
5800 if (ParseType(Ty) ||
5801 ParseToken(lltok::comma, "expected comma after load's type") ||
5802 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005803 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005804 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5805 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005806
David Blaikie15d9a4c2015-04-06 20:59:48 +00005807 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005808 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005809 if (isAtomic && !Alignment)
5810 return Error(Loc, "atomic load must have explicit non-zero alignment");
5811 if (Ordering == Release || Ordering == AcquireRelease)
5812 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005813
David Blaikiea79ac142015-02-27 21:17:42 +00005814 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5815 return Error(ExplicitTypeLoc,
5816 "explicit pointee type doesn't match operand's pointee type");
5817
David Blaikie15d9a4c2015-04-06 20:59:48 +00005818 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005819 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005820}
5821
5822/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005823
5824/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5825/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005826/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005827int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005828 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005829 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005830 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005831 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005832 AtomicOrdering Ordering = NotAtomic;
5833 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005834
5835 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005836 isAtomic = true;
5837 Lex.Lex();
5838 }
5839
Chris Lattnerbc639292011-11-27 06:56:53 +00005840 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005841 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005842 isVolatile = true;
5843 Lex.Lex();
5844 }
5845
Chris Lattnerac161bf2009-01-02 07:01:27 +00005846 if (ParseTypeAndValue(Val, Loc, PFS) ||
5847 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005848 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005849 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005850 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005851 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00005852
Duncan Sands19d0b472010-02-16 11:11:14 +00005853 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005854 return Error(PtrLoc, "store operand must be a pointer");
5855 if (!Val->getType()->isFirstClassType())
5856 return Error(Loc, "store operand must be a first class value");
5857 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5858 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00005859 if (isAtomic && !Alignment)
5860 return Error(Loc, "atomic store must have explicit non-zero alignment");
5861 if (Ordering == Acquire || Ordering == AcquireRelease)
5862 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005863
Eli Friedman59b66882011-08-09 23:02:53 +00005864 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005865 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005866}
5867
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005868/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00005869/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5870/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00005871int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005872 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5873 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00005874 AtomicOrdering SuccessOrdering = NotAtomic;
5875 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005876 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005877 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00005878 bool isWeak = false;
5879
5880 if (EatIfPresent(lltok::kw_weak))
5881 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00005882
5883 if (EatIfPresent(lltok::kw_volatile))
5884 isVolatile = true;
5885
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005886 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5887 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5888 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5889 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5890 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00005891 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5892 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005893 return true;
5894
Tim Northovere94a5182014-03-11 10:48:52 +00005895 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005896 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00005897 if (SuccessOrdering < FailureOrdering)
5898 return TokError("cmpxchg must be at least as ordered on success as failure");
5899 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5900 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005901 if (!Ptr->getType()->isPointerTy())
5902 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5903 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5904 return Error(CmpLoc, "compare value and pointer type do not match");
5905 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5906 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00005907 if (!New->getType()->isFirstClassType())
5908 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00005909 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5910 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005911 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00005912 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005913 Inst = CXI;
5914 return AteExtraComma ? InstExtraComma : InstNormal;
5915}
5916
5917/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00005918/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5919/// 'singlethread'? AtomicOrdering
5920int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005921 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5922 bool AteExtraComma = false;
5923 AtomicOrdering Ordering = NotAtomic;
5924 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005925 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005926 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00005927
5928 if (EatIfPresent(lltok::kw_volatile))
5929 isVolatile = true;
5930
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005931 switch (Lex.getKind()) {
5932 default: return TokError("expected binary operation in atomicrmw");
5933 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5934 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5935 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5936 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5937 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5938 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5939 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5940 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5941 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5942 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5943 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5944 }
5945 Lex.Lex(); // Eat the operation.
5946
5947 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5948 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5949 ParseTypeAndValue(Val, ValLoc, PFS) ||
5950 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5951 return true;
5952
5953 if (Ordering == Unordered)
5954 return TokError("atomicrmw cannot be unordered");
5955 if (!Ptr->getType()->isPointerTy())
5956 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5957 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5958 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5959 if (!Val->getType()->isIntegerTy())
5960 return Error(ValLoc, "atomicrmw operand must be an integer");
5961 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5962 if (Size < 8 || (Size & (Size - 1)))
5963 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5964 " integer");
5965
5966 AtomicRMWInst *RMWI =
5967 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5968 RMWI->setVolatile(isVolatile);
5969 Inst = RMWI;
5970 return AteExtraComma ? InstExtraComma : InstNormal;
5971}
5972
Eli Friedmanfee02c62011-07-25 23:16:38 +00005973/// ParseFence
5974/// ::= 'fence' 'singlethread'? AtomicOrdering
5975int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5976 AtomicOrdering Ordering = NotAtomic;
5977 SynchronizationScope Scope = CrossThread;
5978 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5979 return true;
5980
5981 if (Ordering == Unordered)
5982 return TokError("fence cannot be unordered");
5983 if (Ordering == Monotonic)
5984 return TokError("fence cannot be monotonic");
5985
5986 Inst = new FenceInst(Context, Ordering, Scope);
5987 return InstNormal;
5988}
5989
Chris Lattnerac161bf2009-01-02 07:01:27 +00005990/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00005991/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005992int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005993 Value *Ptr = nullptr;
5994 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005995 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00005996
Dan Gohman16cbbe42009-07-29 15:58:36 +00005997 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00005998
David Blaikie79e6c742015-02-27 19:29:02 +00005999 Type *Ty = nullptr;
6000 LocTy ExplicitTypeLoc = Lex.getLoc();
6001 if (ParseType(Ty) ||
6002 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6003 ParseTypeAndValue(Ptr, Loc, PFS))
6004 return true;
6005
Eli Benderskyd9806682013-04-22 17:03:42 +00006006 Type *BaseType = Ptr->getType();
6007 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6008 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006009 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006010
David Blaikie8d757942015-03-09 23:08:44 +00006011 if (Ty != BasePointerType->getElementType())
6012 return Error(ExplicitTypeLoc,
6013 "explicit pointee type doesn't match operand's pointee type");
6014
Chris Lattnerac161bf2009-01-02 07:01:27 +00006015 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006016 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006017 // GEP returns a vector of pointers if at least one of parameters is a vector.
6018 // All vector parameters should have the same vector width.
6019 unsigned GEPWidth = BaseType->isVectorTy() ?
6020 BaseType->getVectorNumElements() : 0;
6021
Chris Lattner3822f632009-01-02 08:05:26 +00006022 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006023 if (Lex.getKind() == lltok::MetadataVar) {
6024 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006025 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006026 }
Chris Lattner3822f632009-01-02 08:05:26 +00006027 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006028 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006029 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006030
Nadav Rotem3924cb02011-12-05 06:29:09 +00006031 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006032 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6033 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006034 return Error(EltLoc,
6035 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006036 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006037 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006038 Indices.push_back(Val);
6039 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006040
Craig Toppere3dcce92015-08-01 22:20:21 +00006041 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006042 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006043 return Error(Loc, "base element of getelementptr must be sized");
6044
David Blaikied33bad32015-04-17 22:32:13 +00006045 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006046 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006047 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006048 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006049 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006050 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006051}
6052
6053/// ParseExtractValue
6054/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006055int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006056 Value *Val; LocTy Loc;
6057 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006058 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006059 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006060 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006061 return true;
6062
Chris Lattner392be582010-02-12 20:49:41 +00006063 if (!Val->getType()->isAggregateType())
6064 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006065
Jay Foad57aa6362011-07-13 10:26:04 +00006066 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006067 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006068 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006069 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006070}
6071
6072/// ParseInsertValue
6073/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006074int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006075 Value *Val0, *Val1; LocTy Loc0, Loc1;
6076 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006077 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006078 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6079 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6080 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006081 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006082 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006083
Chris Lattner392be582010-02-12 20:49:41 +00006084 if (!Val0->getType()->isAggregateType())
6085 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006086
David Majnemer30074532015-02-11 07:43:58 +00006087 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6088 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006089 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006090 if (IndexedType != Val1->getType())
6091 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6092 getTypeString(Val1->getType()) + "' instead of '" +
6093 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006094 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006095 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006096}
Nick Lewycky49f89192009-04-04 07:22:01 +00006097
6098//===----------------------------------------------------------------------===//
6099// Embedded metadata.
6100//===----------------------------------------------------------------------===//
6101
6102/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006103/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006104/// Element
6105/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006106bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006107 if (ParseToken(lltok::lbrace, "expected '{' here"))
6108 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006109
Dan Gohman1e0213a2010-07-13 19:33:27 +00006110 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006111 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006112 return false;
6113
Nick Lewycky49f89192009-04-04 07:22:01 +00006114 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006115 // Null is a special case since it is typeless.
6116 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006117 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006118 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006119 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006120
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006121 Metadata *MD;
6122 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006123 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006124 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006125 } while (EatIfPresent(lltok::comma));
6126
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006127 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006128}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006129
6130//===----------------------------------------------------------------------===//
6131// Use-list order directives.
6132//===----------------------------------------------------------------------===//
6133bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6134 SMLoc Loc) {
6135 if (V->use_empty())
6136 return Error(Loc, "value has no uses");
6137
6138 unsigned NumUses = 0;
6139 SmallDenseMap<const Use *, unsigned, 16> Order;
6140 for (const Use &U : V->uses()) {
6141 if (++NumUses > Indexes.size())
6142 break;
6143 Order[&U] = Indexes[NumUses - 1];
6144 }
6145 if (NumUses < 2)
6146 return Error(Loc, "value only has one use");
6147 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6148 return Error(Loc, "wrong number of indexes, expected " +
6149 Twine(std::distance(V->use_begin(), V->use_end())));
6150
6151 V->sortUseList([&](const Use &L, const Use &R) {
6152 return Order.lookup(&L) < Order.lookup(&R);
6153 });
6154 return false;
6155}
6156
6157/// ParseUseListOrderIndexes
6158/// ::= '{' uint32 (',' uint32)+ '}'
6159bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6160 SMLoc Loc = Lex.getLoc();
6161 if (ParseToken(lltok::lbrace, "expected '{' here"))
6162 return true;
6163 if (Lex.getKind() == lltok::rbrace)
6164 return Lex.Error("expected non-empty list of uselistorder indexes");
6165
6166 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6167 // indexes should be distinct numbers in the range [0, size-1], and should
6168 // not be in order.
6169 unsigned Offset = 0;
6170 unsigned Max = 0;
6171 bool IsOrdered = true;
6172 assert(Indexes.empty() && "Expected empty order vector");
6173 do {
6174 unsigned Index;
6175 if (ParseUInt32(Index))
6176 return true;
6177
6178 // Update consistency checks.
6179 Offset += Index - Indexes.size();
6180 Max = std::max(Max, Index);
6181 IsOrdered &= Index == Indexes.size();
6182
6183 Indexes.push_back(Index);
6184 } while (EatIfPresent(lltok::comma));
6185
6186 if (ParseToken(lltok::rbrace, "expected '}' here"))
6187 return true;
6188
6189 if (Indexes.size() < 2)
6190 return Error(Loc, "expected >= 2 uselistorder indexes");
6191 if (Offset != 0 || Max >= Indexes.size())
6192 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6193 if (IsOrdered)
6194 return Error(Loc, "expected uselistorder indexes to change the order");
6195
6196 return false;
6197}
6198
6199/// ParseUseListOrder
6200/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6201bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6202 SMLoc Loc = Lex.getLoc();
6203 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6204 return true;
6205
6206 Value *V;
6207 SmallVector<unsigned, 16> Indexes;
6208 if (ParseTypeAndValue(V, PFS) ||
6209 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6210 ParseUseListOrderIndexes(Indexes))
6211 return true;
6212
6213 return sortUseListOrder(V, Indexes, Loc);
6214}
6215
6216/// ParseUseListOrderBB
6217/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6218bool LLParser::ParseUseListOrderBB() {
6219 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6220 SMLoc Loc = Lex.getLoc();
6221 Lex.Lex();
6222
6223 ValID Fn, Label;
6224 SmallVector<unsigned, 16> Indexes;
6225 if (ParseValID(Fn) ||
6226 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6227 ParseValID(Label) ||
6228 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6229 ParseUseListOrderIndexes(Indexes))
6230 return true;
6231
6232 // Check the function.
6233 GlobalValue *GV;
6234 if (Fn.Kind == ValID::t_GlobalName)
6235 GV = M->getNamedValue(Fn.StrVal);
6236 else if (Fn.Kind == ValID::t_GlobalID)
6237 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6238 else
6239 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6240 if (!GV)
6241 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6242 auto *F = dyn_cast<Function>(GV);
6243 if (!F)
6244 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6245 if (F->isDeclaration())
6246 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6247
6248 // Check the basic block.
6249 if (Label.Kind == ValID::t_LocalID)
6250 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6251 if (Label.Kind != ValID::t_LocalName)
6252 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6253 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6254 if (!V)
6255 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6256 if (!isa<BasicBlock>(V))
6257 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6258
6259 return sortUseListOrder(V, Indexes, Loc);
6260}