blob: b1586b1864e93a1c4101053ef10b42e0aebb9cef [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"
Eugene Zelenko1804a772016-08-25 00:45:04 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/Optional.h"
David Blaikieadbda4b2015-08-03 20:08:41 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000019#include "llvm/ADT/SmallPtrSet.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000020#include "llvm/AsmParser/SlotMapping.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000021#include "llvm/IR/Argument.h"
Chandler Carruth91065212014-03-05 10:34:14 +000022#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000023#include "llvm/IR/BasicBlock.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000025#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000027#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000029#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalIFunc.h"
31#include "llvm/IR/GlobalObject.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/InlineAsm.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000033#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Instructions.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000035#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000036#include "llvm/IR/LLVMContext.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000037#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Module.h"
39#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000040#include "llvm/IR/Type.h"
41#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/ValueSymbolTable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000043#include "llvm/Support/Casting.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000044#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000045#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000046#include "llvm/Support/MathExtras.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000047#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000048#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000049#include <algorithm>
50#include <cassert>
51#include <cstring>
52#include <iterator>
53#include <vector>
54
Chris Lattnerac161bf2009-01-02 07:01:27 +000055using namespace llvm;
56
Chris Lattner229907c2011-07-18 04:54:35 +000057static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000058 std::string Result;
59 raw_string_ostream Tmp(Result);
60 Tmp << *T;
61 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000062}
63
Chris Lattner3822f632009-01-02 08:05:26 +000064/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000065bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000066 // Prime the lexer.
67 Lex.Lex();
68
Mehdi Amini50af49f2016-04-02 03:46:17 +000069 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000070 return Error(
71 Lex.getLoc(),
72 "Can't read textual IR with a Context that discards named Values");
73
Chris Lattnerad6f3352009-01-04 20:44:11 +000074 return ParseTopLevelEntities() ||
75 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000076}
77
Alex Lorenz1de2acd2015-08-21 21:32:39 +000078bool LLParser::parseStandaloneConstantValue(Constant *&C,
79 const SlotMapping *Slots) {
80 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000081 Lex.Lex();
82
83 Type *Ty = nullptr;
84 if (ParseType(Ty) || parseConstantValue(Ty, C))
85 return true;
86 if (Lex.getKind() != lltok::Eof)
87 return Error(Lex.getLoc(), "expected end of string");
88 return false;
89}
90
Quentin Colombetdafed5d2016-03-08 00:37:07 +000091bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000093 restoreParsingState(Slots);
94 Lex.Lex();
95
Quentin Colombetdafed5d2016-03-08 00:37:07 +000096 Read = 0;
97 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000098 Ty = nullptr;
99 if (ParseType(Ty))
100 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +0000101 SMLoc End = Lex.getLoc();
102 Read = End.getPointer() - Start.getPointer();
103
Quentin Colombet81e72b42016-03-07 22:09:05 +0000104 return false;
105}
106
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000107void LLParser::restoreParsingState(const SlotMapping *Slots) {
108 if (!Slots)
109 return;
110 NumberedVals = Slots->GlobalValues;
111 NumberedMetadata = Slots->MetadataNodes;
112 for (const auto &I : Slots->NamedTypes)
113 NamedTypes.insert(
114 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
115 for (const auto &I : Slots->Types)
116 NumberedTypes.insert(
117 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
118}
119
Chris Lattnerac161bf2009-01-02 07:01:27 +0000120/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
121/// module.
122bool LLParser::ValidateEndOfModule() {
Bill Wendlingb32b0412013-02-08 06:32:06 +0000123 // Handle any function attribute group forward references.
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000124 for (const auto &RAG : ForwardRefAttrGroups) {
125 Value *V = RAG.first;
126 const std::vector<unsigned> &Attrs = RAG.second;
Bill Wendlingb32b0412013-02-08 06:32:06 +0000127 AttrBuilder B;
128
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000129 for (const auto &Attr : Attrs)
130 B.merge(NumberedAttrBuilders[Attr]);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000131
132 if (Function *Fn = dyn_cast<Function>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000133 AttributeList AS = Fn->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000134 AttrBuilder FnAttrs(AS.getFnAttributes());
135 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000136
137 FnAttrs.merge(B);
138
139 // If the alignment was parsed as an attribute, move to the alignment
140 // field.
141 if (FnAttrs.hasAlignmentAttr()) {
142 Fn->setAlignment(FnAttrs.getAlignment());
143 FnAttrs.removeAttribute(Attribute::Alignment);
144 }
145
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000146 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
147 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000148 Fn->setAttributes(AS);
149 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000150 AttributeList AS = CI->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000151 AttrBuilder FnAttrs(AS.getFnAttributes());
152 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000153 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000154 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
155 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000156 CI->setAttributes(AS);
157 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000158 AttributeList AS = II->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000159 AttrBuilder FnAttrs(AS.getFnAttributes());
160 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000161 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000162 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
163 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000164 II->setAttributes(AS);
Javed Absarf3d79042017-05-11 12:28:08 +0000165 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
166 AttrBuilder Attrs(GV->getAttributes());
167 Attrs.merge(B);
168 GV->setAttributes(AttributeSet::get(Context,Attrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000169 } else {
170 llvm_unreachable("invalid object with forward attribute group reference");
171 }
172 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000173
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000174 // If there are entries in ForwardRefBlockAddresses at this point, the
175 // function was never defined.
176 if (!ForwardRefBlockAddresses.empty())
177 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
178 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000179
David Majnemer19b51052015-02-11 07:43:56 +0000180 for (const auto &NT : NumberedTypes)
181 if (NT.second.second.isValid())
182 return Error(NT.second.second,
183 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000184
185 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
186 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
187 if (I->second.second.isValid())
188 return Error(I->second.second,
189 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000190
David Majnemerdad0a642014-06-27 18:19:56 +0000191 if (!ForwardRefComdats.empty())
192 return Error(ForwardRefComdats.begin()->second,
193 "use of undefined comdat '$" +
194 ForwardRefComdats.begin()->first + "'");
195
Chris Lattnerac161bf2009-01-02 07:01:27 +0000196 if (!ForwardRefVals.empty())
197 return Error(ForwardRefVals.begin()->second.second,
198 "use of undefined value '@" + ForwardRefVals.begin()->first +
199 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000200
Chris Lattnerac161bf2009-01-02 07:01:27 +0000201 if (!ForwardRefValIDs.empty())
202 return Error(ForwardRefValIDs.begin()->second.second,
203 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000204 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000205
Devang Pateld2541152009-07-08 19:23:54 +0000206 if (!ForwardRefMDNodes.empty())
207 return Error(ForwardRefMDNodes.begin()->second.second,
208 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000209 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000210
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000211 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000212 for (auto &N : NumberedMetadata) {
213 if (N.second && !N.second->isResolved())
214 N.second->resolveCycles();
215 }
Devang Pateld2541152009-07-08 19:23:54 +0000216
Mehdi Aminie4709272016-09-14 22:29:59 +0000217 for (auto *Inst : InstsWithTBAATag) {
218 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
219 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
220 auto *UpgradedMD = UpgradeTBAANode(*MD);
221 if (MD != UpgradedMD)
222 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
223 }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000224
Chris Lattnerac161bf2009-01-02 07:01:27 +0000225 // Look for intrinsic functions and CallInst that need to be upgraded
226 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000227 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000228
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000229 // Some types could be renamed during loading if several modules are
230 // loaded in the same LLVMContext (LTO scenario). In this case we should
231 // remangle intrinsics names as well.
232 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
233 Function *F = &*FI++;
234 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
235 F->replaceAllUsesWith(Remangled.getValue());
236 F->eraseFromParent();
237 }
238 }
239
Manman Ren8b4306c2013-12-02 21:29:56 +0000240 UpgradeDebugInfo(*M);
241
Manman Renb5d7ff42016-05-25 23:14:48 +0000242 UpgradeModuleFlags(*M);
243
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000244 if (!Slots)
245 return false;
246 // Initialize the slot mapping.
247 // Because by this point we've parsed and validated everything, we can "steal"
248 // the mapping from LLParser as it doesn't need it anymore.
249 Slots->GlobalValues = std::move(NumberedVals);
250 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000251 for (const auto &I : NamedTypes)
252 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
253 for (const auto &I : NumberedTypes)
254 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000255
Chris Lattnerac161bf2009-01-02 07:01:27 +0000256 return false;
257}
258
259//===----------------------------------------------------------------------===//
260// Top-Level Entities
261//===----------------------------------------------------------------------===//
262
263bool LLParser::ParseTopLevelEntities() {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000264 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000265 switch (Lex.getKind()) {
266 default: return TokError("expected top-level entity");
267 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000268 case lltok::kw_declare: if (ParseDeclare()) return true; break;
269 case lltok::kw_define: if (ParseDefine()) return true; break;
270 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
271 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000272 case lltok::kw_source_filename:
273 if (ParseSourceFileName())
274 return true;
275 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000276 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000277 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000278 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000279 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000280 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000281 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000282 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000283 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000284 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000285 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
286 case lltok::kw_uselistorder_bb:
Davide Italianof4e16612016-08-26 18:05:03 +0000287 if (ParseUseListOrderBB())
288 return true;
289 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000290 }
291 }
292}
293
Chris Lattnerac161bf2009-01-02 07:01:27 +0000294/// toplevelentity
295/// ::= 'module' 'asm' STRINGCONSTANT
296bool LLParser::ParseModuleAsm() {
297 assert(Lex.getKind() == lltok::kw_module);
298 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000299
300 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000301 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
302 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000303
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000304 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000305 return false;
306}
307
308/// toplevelentity
309/// ::= 'target' 'triple' '=' STRINGCONSTANT
310/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
311bool LLParser::ParseTargetDefinition() {
312 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000313 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000314 switch (Lex.Lex()) {
315 default: return TokError("unknown target property");
316 case lltok::kw_triple:
317 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000318 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
319 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000320 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000321 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000322 return false;
323 case lltok::kw_datalayout:
324 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000325 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
326 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000327 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000328 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000329 return false;
330 }
331}
332
Bill Wendling706d3d62012-11-28 08:41:48 +0000333/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000334/// ::= 'source_filename' '=' STRINGCONSTANT
335bool LLParser::ParseSourceFileName() {
336 assert(Lex.getKind() == lltok::kw_source_filename);
337 std::string Str;
338 Lex.Lex();
339 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
340 ParseStringConstant(Str))
341 return true;
342 M->setSourceFileName(Str);
343 return false;
344}
345
346/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000347/// ::= 'deplibs' '=' '[' ']'
348/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
349/// FIXME: Remove in 4.0. Currently parse, but ignore.
350bool LLParser::ParseDepLibs() {
351 assert(Lex.getKind() == lltok::kw_deplibs);
352 Lex.Lex();
353 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
354 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
355 return true;
356
357 if (EatIfPresent(lltok::rsquare))
358 return false;
359
360 do {
361 std::string Str;
362 if (ParseStringConstant(Str)) return true;
363 } while (EatIfPresent(lltok::comma));
364
365 return ParseToken(lltok::rsquare, "expected ']' at end of list");
366}
367
Dan Gohman466876b2009-08-12 23:32:33 +0000368/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000369/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000370bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000371 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000372 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000373 Lex.Lex(); // eat LocalVarID;
374
375 if (ParseToken(lltok::equal, "expected '=' after name") ||
376 ParseToken(lltok::kw_type, "expected 'type' after '='"))
377 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000378
Craig Topper2617dcc2014-04-15 06:32:26 +0000379 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000380 if (ParseStructDefinition(TypeLoc, "",
381 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000382
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000383 if (!isa<StructType>(Result)) {
384 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
385 if (Entry.first)
386 return Error(TypeLoc, "non-struct types may not be recursive");
387 Entry.first = Result;
388 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000389 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000390
Chris Lattnerac161bf2009-01-02 07:01:27 +0000391 return false;
392}
393
394/// toplevelentity
395/// ::= LocalVar '=' 'type' type
396bool LLParser::ParseNamedType() {
397 std::string Name = Lex.getStrVal();
398 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000399 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000400
Chris Lattner3822f632009-01-02 08:05:26 +0000401 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000402 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000403 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000404
Craig Topper2617dcc2014-04-15 06:32:26 +0000405 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000406 if (ParseStructDefinition(NameLoc, Name,
407 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000408
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000409 if (!isa<StructType>(Result)) {
410 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
411 if (Entry.first)
412 return Error(NameLoc, "non-struct types may not be recursive");
413 Entry.first = Result;
414 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000415 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000416
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000417 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000418}
419
Chris Lattnerac161bf2009-01-02 07:01:27 +0000420/// toplevelentity
421/// ::= 'declare' FunctionHeader
422bool LLParser::ParseDeclare() {
423 assert(Lex.getKind() == lltok::kw_declare);
424 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000425
Peter Collingbourne21521892016-06-21 23:42:48 +0000426 std::vector<std::pair<unsigned, MDNode *>> MDs;
427 while (Lex.getKind() == lltok::MetadataVar) {
428 unsigned MDK;
429 MDNode *N;
430 if (ParseMetadataAttachment(MDK, N))
431 return true;
432 MDs.push_back({MDK, N});
433 }
434
Chris Lattnerac161bf2009-01-02 07:01:27 +0000435 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000436 if (ParseFunctionHeader(F, false))
437 return true;
438 for (auto &MD : MDs)
439 F->addMetadata(MD.first, *MD.second);
440 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000441}
442
443/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000444/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000445bool LLParser::ParseDefine() {
446 assert(Lex.getKind() == lltok::kw_define);
447 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000448
Chris Lattnerac161bf2009-01-02 07:01:27 +0000449 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000450 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000451 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000452 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000453}
454
Chris Lattner3822f632009-01-02 08:05:26 +0000455/// ParseGlobalType
456/// ::= 'constant'
457/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000458bool LLParser::ParseGlobalType(bool &IsConstant) {
459 if (Lex.getKind() == lltok::kw_constant)
460 IsConstant = true;
461 else if (Lex.getKind() == lltok::kw_global)
462 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000463 else {
464 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000465 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000466 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000467 Lex.Lex();
468 return false;
469}
470
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000471bool LLParser::ParseOptionalUnnamedAddr(
472 GlobalVariable::UnnamedAddr &UnnamedAddr) {
473 if (EatIfPresent(lltok::kw_unnamed_addr))
474 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
475 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
476 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
477 else
478 UnnamedAddr = GlobalValue::UnnamedAddr::None;
479 return false;
480}
481
Dan Gohman466876b2009-08-12 23:32:33 +0000482/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000483/// OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000484/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
485/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000486/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000487/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
488/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000489bool LLParser::ParseUnnamedGlobal() {
490 unsigned VarID = NumberedVals.size();
491 std::string Name;
492 LocTy NameLoc = Lex.getLoc();
493
494 // Handle the GlobalID form.
495 if (Lex.getKind() == lltok::GlobalID) {
496 if (Lex.getUIntVal() != VarID)
497 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000498 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000499 Lex.Lex(); // eat GlobalID;
500
501 if (ParseToken(lltok::equal, "expected '=' after name"))
502 return true;
503 }
504
505 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000506 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000507 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000508 GlobalVariable::UnnamedAddr UnnamedAddr;
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000509 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000510 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000511 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000512
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000513 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000514 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000515 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000516
517 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
518 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000519}
520
Chris Lattnerac161bf2009-01-02 07:01:27 +0000521/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000522/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000523/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
524/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000525bool LLParser::ParseNamedGlobal() {
526 assert(Lex.getKind() == lltok::GlobalVar);
527 LocTy NameLoc = Lex.getLoc();
528 std::string Name = Lex.getStrVal();
529 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000530
Chris Lattnerac161bf2009-01-02 07:01:27 +0000531 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000532 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000533 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000534 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000535 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000536 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000537 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000538 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000539
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000540 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000541 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000542 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000543
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000544 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
545 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000546}
547
David Majnemerdad0a642014-06-27 18:19:56 +0000548bool LLParser::parseComdat() {
549 assert(Lex.getKind() == lltok::ComdatVar);
550 std::string Name = Lex.getStrVal();
551 LocTy NameLoc = Lex.getLoc();
552 Lex.Lex();
553
554 if (ParseToken(lltok::equal, "expected '=' here"))
555 return true;
556
557 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
558 return TokError("expected comdat type");
559
560 Comdat::SelectionKind SK;
561 switch (Lex.getKind()) {
562 default:
563 return TokError("unknown selection kind");
564 case lltok::kw_any:
565 SK = Comdat::Any;
566 break;
567 case lltok::kw_exactmatch:
568 SK = Comdat::ExactMatch;
569 break;
570 case lltok::kw_largest:
571 SK = Comdat::Largest;
572 break;
573 case lltok::kw_noduplicates:
574 SK = Comdat::NoDuplicates;
575 break;
576 case lltok::kw_samesize:
577 SK = Comdat::SameSize;
578 break;
579 }
580 Lex.Lex();
581
582 // See if the comdat was forward referenced, if so, use the comdat.
583 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
584 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
585 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
586 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
587
588 Comdat *C;
589 if (I != ComdatSymTab.end())
590 C = &I->second;
591 else
592 C = M->getOrInsertComdat(Name);
593 C->setSelectionKind(SK);
594
595 return false;
596}
597
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000598// MDString:
599// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000600bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000601 std::string Str;
602 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000603 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000604 return false;
605}
606
607// MDNode:
608// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000609bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000610 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000611 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000612 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000613 if (ParseUInt32(MID))
614 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000615
Chris Lattner8eff0152010-04-01 05:14:45 +0000616 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000617 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000618 Result = NumberedMetadata[MID];
619 return false;
620 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000621
Chris Lattner8eff0152010-04-01 05:14:45 +0000622 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000623 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000624 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000625
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000626 Result = FwdRef.first.get();
627 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000628 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000629}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000630
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000631/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000632/// !foo = !{ !1, !2 }
633bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000634 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000635 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000636 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000637
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000638 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000639 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000640 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000641 return true;
642
Dan Gohman2637cc12010-07-21 23:38:33 +0000643 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000644 if (Lex.getKind() != lltok::rbrace)
645 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000646 if (ParseToken(lltok::exclaim, "Expected '!' here"))
647 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000648
Craig Topper2617dcc2014-04-15 06:32:26 +0000649 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000650 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000651 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000652 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000653
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000654 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000655}
656
Devang Patel39e64d42009-07-01 19:21:12 +0000657/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000658/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000659bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000660 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000661 Lex.Lex();
662 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000663
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000664 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000665 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000666 ParseToken(lltok::equal, "expected '=' here"))
667 return true;
668
669 // Detect common error, from old metadata syntax.
670 if (Lex.getKind() == lltok::Type)
671 return TokError("unexpected type in metadata definition");
672
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000673 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000674 if (Lex.getKind() == lltok::MetadataVar) {
675 if (ParseSpecializedMDNode(Init, IsDistinct))
676 return true;
677 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
678 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000679 return true;
680
Chris Lattnerfc58af22009-12-30 04:51:58 +0000681 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000682 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000683 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000684 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000685 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000686
Chris Lattnerfc58af22009-12-30 04:51:58 +0000687 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
688 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000689 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000690 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000691 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000692 }
693
Devang Patel39e64d42009-07-01 19:21:12 +0000694 return false;
695}
696
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000697static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
698 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
699 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
700}
701
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000702/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000703/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
704/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000705/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000706///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000707/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000708/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000709///
Eric Christopher536f0a92015-05-28 23:07:39 +0000710/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000711///
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000712bool LLParser::parseIndirectSymbol(
713 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
714 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
715 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000716 bool IsAlias;
717 if (Lex.getKind() == lltok::kw_alias)
718 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000719 else if (Lex.getKind() == lltok::kw_ifunc)
720 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000721 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000722 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000723 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000724
Rafael Espindola78527052013-10-06 15:10:43 +0000725 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
726
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000727 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000728 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000729
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000730 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000731 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000732 "symbol with local linkage must have default visibility");
733
David Blaikie2f408302015-09-11 03:22:04 +0000734 Type *Ty;
735 LocTy ExplicitTypeLoc = Lex.getLoc();
736 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000737 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000738 return true;
739
Rafael Espindola64c1e182014-06-03 02:41:57 +0000740 Constant *Aliasee;
741 LocTy AliaseeLoc = Lex.getLoc();
742 if (Lex.getKind() != lltok::kw_bitcast &&
743 Lex.getKind() != lltok::kw_getelementptr &&
744 Lex.getKind() != lltok::kw_addrspacecast &&
745 Lex.getKind() != lltok::kw_inttoptr) {
746 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000747 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000748 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000749 // The bitcast dest type is not present, it is implied by the dest type.
750 ValID ID;
751 if (ParseValID(ID))
752 return true;
753 if (ID.Kind != ValID::t_Constant)
754 return Error(AliaseeLoc, "invalid aliasee");
755 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000756 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000757
Rafael Espindola64c1e182014-06-03 02:41:57 +0000758 Type *AliaseeType = Aliasee->getType();
759 auto *PTy = dyn_cast<PointerType>(AliaseeType);
760 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000761 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000762 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000763
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000764 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000765 return Error(
766 ExplicitTypeLoc,
767 "explicit pointee type doesn't match operand's pointee type");
768
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000769 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
770 return Error(
771 ExplicitTypeLoc,
772 "explicit pointee type should be a function type");
773
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000774 GlobalValue *GVal = nullptr;
775
776 // See if the alias was forward referenced, if so, prepare to replace the
777 // forward reference.
778 if (!Name.empty()) {
779 GVal = M->getNamedValue(Name);
780 if (GVal) {
781 if (!ForwardRefVals.erase(Name))
782 return Error(NameLoc, "redefinition of global '@" + Name + "'");
783 }
784 } else {
785 auto I = ForwardRefValIDs.find(NumberedVals.size());
786 if (I != ForwardRefValIDs.end()) {
787 GVal = I->second.first;
788 ForwardRefValIDs.erase(I);
789 }
790 }
791
Chris Lattnerac161bf2009-01-02 07:01:27 +0000792 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000793 std::unique_ptr<GlobalIndirectSymbol> GA;
794 if (IsAlias)
795 GA.reset(GlobalAlias::create(Ty, AddrSpace,
796 (GlobalValue::LinkageTypes)Linkage, Name,
797 Aliasee, /*Parent*/ nullptr));
798 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000799 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
800 (GlobalValue::LinkageTypes)Linkage, Name,
801 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000802 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000803 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000804 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000805 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000806
Rafael Espindola54fc2982015-06-17 17:53:31 +0000807 if (Name.empty())
808 NumberedVals.push_back(GA.get());
809
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000810 if (GVal) {
811 // Verify that types agree.
812 if (GVal->getType() != GA->getType())
813 return Error(
814 ExplicitTypeLoc,
815 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000816
Chris Lattnerac161bf2009-01-02 07:01:27 +0000817 // If they agree, just RAUW the old value with the alias and remove the
818 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000819 GVal->replaceAllUsesWith(GA.get());
820 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000821 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000822
Chris Lattnerac161bf2009-01-02 07:01:27 +0000823 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000824 if (IsAlias)
825 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
826 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000827 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000828 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000829
Rafael Espindolaaa273822014-05-09 21:49:17 +0000830 // The module owns this now
831 GA.release();
832
Chris Lattnerac161bf2009-01-02 07:01:27 +0000833 return false;
834}
835
836/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000837/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000838/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +0000839/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Nico Rieck7157bb72014-01-14 15:22:47 +0000840/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000841/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +0000842/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +0000843///
Eric Christopher536f0a92015-05-28 23:07:39 +0000844/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000845/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000846///
847bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
848 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000849 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000850 GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000851 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000852 if (!isValidVisibilityForLinkage(Visibility, Linkage))
853 return Error(NameLoc,
854 "symbol with local linkage must have default visibility");
855
Chris Lattnerac161bf2009-01-02 07:01:27 +0000856 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000857 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000858 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000859 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000860
Craig Topper2617dcc2014-04-15 06:32:26 +0000861 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000862 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000863 ParseOptionalToken(lltok::kw_externally_initialized,
864 IsExternallyInitialized,
865 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000866 ParseGlobalType(IsConstant) ||
867 ParseType(Ty, TyLoc))
868 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000869
Chris Lattnerac161bf2009-01-02 07:01:27 +0000870 // If the linkage is specified and is external, then no initializer is
871 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000872 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000873 if (!HasLinkage ||
874 !GlobalValue::isValidDeclarationLinkage(
875 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000876 if (ParseGlobalValue(Ty, Init))
877 return true;
878 }
879
David Majnemer49b3d9b2015-02-16 08:41:08 +0000880 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000881 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000882
David Majnemer598bd052014-12-09 05:56:09 +0000883 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000884
885 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000886 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000887 GVal = M->getNamedValue(Name);
888 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000889 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000890 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000891 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000892 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000893 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000894 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000895 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000896 ForwardRefValIDs.erase(I);
897 }
898 }
899
David Majnemer598bd052014-12-09 05:56:09 +0000900 GlobalVariable *GV;
901 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000902 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
903 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000904 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000905 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000906 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000907 return Error(TyLoc,
908 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000909
David Majnemer598bd052014-12-09 05:56:09 +0000910 GV = cast<GlobalVariable>(GVal);
911
Chris Lattnerac161bf2009-01-02 07:01:27 +0000912 // Move the forward-reference to the correct spot in the module.
913 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
914 }
915
916 if (Name.empty())
917 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000918
Chris Lattnerac161bf2009-01-02 07:01:27 +0000919 // Set the parsed properties on the global.
920 if (Init)
921 GV->setInitializer(Init);
922 GV->setConstant(IsConstant);
923 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
924 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000925 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000926 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000927 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000928 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000929
Chris Lattnerac161bf2009-01-02 07:01:27 +0000930 // Parse attributes on the global.
931 while (Lex.getKind() == lltok::comma) {
932 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000933
Chris Lattnerac161bf2009-01-02 07:01:27 +0000934 if (Lex.getKind() == lltok::kw_section) {
935 Lex.Lex();
936 GV->setSection(Lex.getStrVal());
937 if (ParseToken(lltok::StringConstant, "expected global section string"))
938 return true;
939 } else if (Lex.getKind() == lltok::kw_align) {
940 unsigned Alignment;
941 if (ParseOptionalAlignment(Alignment)) return true;
942 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000943 } else if (Lex.getKind() == lltok::MetadataVar) {
944 if (ParseGlobalObjectMetadataAttachment(*GV))
945 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000946 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000947 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000948 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000949 return true;
950 if (C)
951 GV->setComdat(C);
952 else
953 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000954 }
955 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000956
Javed Absarf3d79042017-05-11 12:28:08 +0000957 AttrBuilder Attrs;
958 LocTy BuiltinLoc;
959 std::vector<unsigned> FwdRefAttrGrps;
960 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
961 return true;
962 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
963 GV->setAttributes(AttributeSet::get(Context, Attrs));
964 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
965 }
966
Chris Lattnerac161bf2009-01-02 07:01:27 +0000967 return false;
968}
969
Bill Wendling63b88192013-02-06 06:52:58 +0000970/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000971/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000972bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000973 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000974 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000975 Lex.Lex();
976
David Majnemerb39e22b2014-12-09 18:33:57 +0000977 if (Lex.getKind() != lltok::AttrGrpID)
978 return TokError("expected attribute group id");
979
Bill Wendling63b88192013-02-06 06:52:58 +0000980 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000981 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000982 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000983 Lex.Lex();
984
985 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000986 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000987 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000988 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000989 ParseToken(lltok::rbrace, "expected end of attribute group"))
990 return true;
991
Bill Wendlingb32b0412013-02-08 06:32:06 +0000992 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000993 return Error(AttrGrpLoc, "attribute group has no attributes");
994
995 return false;
996}
997
Bill Wendling8b0321d2013-02-08 00:52:31 +0000998/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000999/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +00001000bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1001 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +00001002 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +00001003 bool HaveError = false;
1004
1005 B.clear();
1006
Bill Wendling63b88192013-02-06 06:52:58 +00001007 while (true) {
1008 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001009 if (Token == lltok::kw_builtin)
1010 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001011 switch (Token) {
1012 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001013 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001014 return Error(Lex.getLoc(), "unterminated attribute group");
1015 case lltok::rbrace:
1016 // Finished.
1017 return false;
1018
Bill Wendlingb32b0412013-02-08 06:32:06 +00001019 case lltok::AttrGrpID: {
1020 // Allow a function to reference an attribute group:
1021 //
1022 // define void @foo() #1 { ... }
1023 if (inAttrGrp)
1024 HaveError |=
1025 Error(Lex.getLoc(),
1026 "cannot have an attribute group reference in an attribute group");
1027
1028 unsigned AttrGrpNum = Lex.getUIntVal();
1029 if (inAttrGrp) break;
1030
1031 // Save the reference to the attribute group. We'll fill it in later.
1032 FwdRefAttrGrps.push_back(AttrGrpNum);
1033 break;
1034 }
Bill Wendling63b88192013-02-06 06:52:58 +00001035 // Target-dependent attributes:
1036 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001037 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001038 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001039 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001040 }
1041
1042 // Target-independent attributes:
1043 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001044 // As a hack, we allow function alignment to be initially parsed as an
1045 // attribute on a function declaration/definition or added to an attribute
1046 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001047 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001048 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001049 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001050 if (ParseToken(lltok::equal, "expected '=' here") ||
1051 ParseUInt32(Alignment))
1052 return true;
1053 } else {
1054 if (ParseOptionalAlignment(Alignment))
1055 return true;
1056 }
Bill Wendling63b88192013-02-06 06:52:58 +00001057 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001058 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001059 }
1060 case lltok::kw_alignstack: {
1061 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001062 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001063 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001064 if (ParseToken(lltok::equal, "expected '=' here") ||
1065 ParseUInt32(Alignment))
1066 return true;
1067 } else {
1068 if (ParseOptionalStackAlignment(Alignment))
1069 return true;
1070 }
Bill Wendling63b88192013-02-06 06:52:58 +00001071 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001072 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001073 }
George Burgess IV278199f2016-04-12 01:05:35 +00001074 case lltok::kw_allocsize: {
1075 unsigned ElemSizeArg;
1076 Optional<unsigned> NumElemsArg;
1077 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1078 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1079 return true;
1080 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1081 continue;
1082 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001083 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1084 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1085 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1086 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1087 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001088 case lltok::kw_inaccessiblememonly:
1089 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1090 case lltok::kw_inaccessiblemem_or_argmemonly:
1091 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001092 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1093 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1094 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1095 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1096 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1097 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1098 case lltok::kw_noimplicitfloat:
1099 B.addAttribute(Attribute::NoImplicitFloat); break;
1100 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1101 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1102 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1103 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001104 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001105 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1106 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1107 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1108 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1109 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1110 case lltok::kw_returns_twice:
1111 B.addAttribute(Attribute::ReturnsTwice); break;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001112 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001113 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1114 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1115 case lltok::kw_sspstrong:
1116 B.addAttribute(Attribute::StackProtectStrong); break;
1117 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1118 case lltok::kw_sanitize_address:
1119 B.addAttribute(Attribute::SanitizeAddress); break;
1120 case lltok::kw_sanitize_thread:
1121 B.addAttribute(Attribute::SanitizeThread); break;
1122 case lltok::kw_sanitize_memory:
1123 B.addAttribute(Attribute::SanitizeMemory); break;
1124 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001125 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001126
1127 // Error handling.
1128 case lltok::kw_inreg:
1129 case lltok::kw_signext:
1130 case lltok::kw_zeroext:
1131 HaveError |=
1132 Error(Lex.getLoc(),
1133 "invalid use of attribute on a function");
1134 break;
1135 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001136 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001137 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001138 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001139 case lltok::kw_nest:
1140 case lltok::kw_noalias:
1141 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001142 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001143 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001144 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001145 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001146 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001147 HaveError |=
1148 Error(Lex.getLoc(),
1149 "invalid use of parameter-only attribute on a function");
1150 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001151 }
1152
1153 Lex.Lex();
1154 }
1155}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001156
1157//===----------------------------------------------------------------------===//
1158// GlobalValue Reference/Resolution Routines.
1159//===----------------------------------------------------------------------===//
1160
Karl Schimpf77729782015-09-03 18:06:44 +00001161static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1162 const std::string &Name) {
1163 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1164 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1165 else
1166 return new GlobalVariable(*M, PTy->getElementType(), false,
1167 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1168 nullptr, GlobalVariable::NotThreadLocal,
1169 PTy->getAddressSpace());
1170}
1171
Chris Lattnerac161bf2009-01-02 07:01:27 +00001172/// GetGlobalVal - Get a value with the specified name or ID, creating a
1173/// forward reference record if needed. This can return null if the value
1174/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001175GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001176 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001177 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001178 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001179 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001180 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001181 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001182
Chris Lattnerac161bf2009-01-02 07:01:27 +00001183 // Look this name up in the normal function symbol table.
1184 GlobalValue *Val =
1185 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001186
Chris Lattnerac161bf2009-01-02 07:01:27 +00001187 // If this is a forward reference for the value, see if we already created a
1188 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001189 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001190 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001191 if (I != ForwardRefVals.end())
1192 Val = I->second.first;
1193 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001194
Chris Lattnerac161bf2009-01-02 07:01:27 +00001195 // If we have the value in the symbol table or fwd-ref table, return it.
1196 if (Val) {
1197 if (Val->getType() == Ty) return Val;
1198 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001199 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001200 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001201 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001202
Chris Lattnerac161bf2009-01-02 07:01:27 +00001203 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001204 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001205 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1206 return FwdVal;
1207}
1208
Chris Lattner229907c2011-07-18 04:54:35 +00001209GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1210 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001211 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001212 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001213 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001214 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001215
Craig Topper2617dcc2014-04-15 06:32:26 +00001216 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001217
Chris Lattnerac161bf2009-01-02 07:01:27 +00001218 // If this is a forward reference for the value, see if we already created a
1219 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001220 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001221 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001222 if (I != ForwardRefValIDs.end())
1223 Val = I->second.first;
1224 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001225
Chris Lattnerac161bf2009-01-02 07:01:27 +00001226 // If we have the value in the symbol table or fwd-ref table, return it.
1227 if (Val) {
1228 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001229 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001230 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001231 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001232 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001233
Chris Lattnerac161bf2009-01-02 07:01:27 +00001234 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001235 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001236 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1237 return FwdVal;
1238}
1239
Chris Lattnerac161bf2009-01-02 07:01:27 +00001240//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001241// Comdat Reference/Resolution Routines.
1242//===----------------------------------------------------------------------===//
1243
1244Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1245 // Look this name up in the comdat symbol table.
1246 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1247 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1248 if (I != ComdatSymTab.end())
1249 return &I->second;
1250
1251 // Otherwise, create a new forward reference for this value and remember it.
1252 Comdat *C = M->getOrInsertComdat(Name);
1253 ForwardRefComdats[Name] = Loc;
1254 return C;
1255}
1256
David Majnemerdad0a642014-06-27 18:19:56 +00001257//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001258// Helper Routines.
1259//===----------------------------------------------------------------------===//
1260
1261/// ParseToken - If the current token has the specified kind, eat it and return
1262/// success. Otherwise, emit the specified error and return failure.
1263bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1264 if (Lex.getKind() != T)
1265 return TokError(ErrMsg);
1266 Lex.Lex();
1267 return false;
1268}
1269
Chris Lattner3822f632009-01-02 08:05:26 +00001270/// ParseStringConstant
1271/// ::= StringConstant
1272bool LLParser::ParseStringConstant(std::string &Result) {
1273 if (Lex.getKind() != lltok::StringConstant)
1274 return TokError("expected string constant");
1275 Result = Lex.getStrVal();
1276 Lex.Lex();
1277 return false;
1278}
1279
1280/// ParseUInt32
1281/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001282bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001283 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1284 return TokError("expected integer");
1285 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1286 if (Val64 != unsigned(Val64))
1287 return TokError("expected 32-bit integer (too large)");
1288 Val = Val64;
1289 Lex.Lex();
1290 return false;
1291}
1292
Hal Finkelb0407ba2014-07-18 15:51:28 +00001293/// ParseUInt64
1294/// ::= uint64
1295bool LLParser::ParseUInt64(uint64_t &Val) {
1296 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1297 return TokError("expected integer");
1298 Val = Lex.getAPSIntVal().getLimitedValue();
1299 Lex.Lex();
1300 return false;
1301}
1302
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001303/// ParseTLSModel
1304/// := 'localdynamic'
1305/// := 'initialexec'
1306/// := 'localexec'
1307bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1308 switch (Lex.getKind()) {
1309 default:
1310 return TokError("expected localdynamic, initialexec or localexec");
1311 case lltok::kw_localdynamic:
1312 TLM = GlobalVariable::LocalDynamicTLSModel;
1313 break;
1314 case lltok::kw_initialexec:
1315 TLM = GlobalVariable::InitialExecTLSModel;
1316 break;
1317 case lltok::kw_localexec:
1318 TLM = GlobalVariable::LocalExecTLSModel;
1319 break;
1320 }
1321
1322 Lex.Lex();
1323 return false;
1324}
1325
1326/// ParseOptionalThreadLocal
1327/// := /*empty*/
1328/// := 'thread_local'
1329/// := 'thread_local' '(' tlsmodel ')'
1330bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1331 TLM = GlobalVariable::NotThreadLocal;
1332 if (!EatIfPresent(lltok::kw_thread_local))
1333 return false;
1334
1335 TLM = GlobalVariable::GeneralDynamicTLSModel;
1336 if (Lex.getKind() == lltok::lparen) {
1337 Lex.Lex();
1338 return ParseTLSModel(TLM) ||
1339 ParseToken(lltok::rparen, "expected ')' after thread local model");
1340 }
1341 return false;
1342}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001343
1344/// ParseOptionalAddrSpace
1345/// := /*empty*/
1346/// := 'addrspace' '(' uint32 ')'
1347bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1348 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001349 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001350 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001351 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001352 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001353 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001354}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001355
Artur Pilipenko17376c42015-08-03 14:31:49 +00001356/// ParseStringAttribute
1357/// := StringConstant
1358/// := StringConstant '=' StringConstant
1359bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1360 std::string Attr = Lex.getStrVal();
1361 Lex.Lex();
1362 std::string Val;
1363 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1364 return true;
1365 B.addAttribute(Attr, Val);
1366 return false;
1367}
1368
Bill Wendling34c2eb22012-12-04 23:40:58 +00001369/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1370bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1371 bool HaveError = false;
1372
1373 B.clear();
1374
Eugene Zelenko1804a772016-08-25 00:45:04 +00001375 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001376 lltok::Kind Token = Lex.getKind();
1377 switch (Token) {
1378 default: // End of attributes.
1379 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001380 case lltok::StringConstant: {
1381 if (ParseStringAttribute(B))
1382 return true;
1383 continue;
1384 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001385 case lltok::kw_align: {
1386 unsigned Alignment;
1387 if (ParseOptionalAlignment(Alignment))
1388 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001389 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001390 continue;
1391 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001392 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001393 case lltok::kw_dereferenceable: {
1394 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001395 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001396 return true;
1397 B.addDereferenceableAttr(Bytes);
1398 continue;
1399 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001400 case lltok::kw_dereferenceable_or_null: {
1401 uint64_t Bytes;
1402 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1403 return true;
1404 B.addDereferenceableOrNullAttr(Bytes);
1405 continue;
1406 }
Reid Klecknera534a382013-12-19 02:14:12 +00001407 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001408 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1409 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1410 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1411 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001412 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001413 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1414 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001415 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001416 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1417 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001418 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001419 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001420 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001421 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001422
Stephen Lin7577ed52013-04-20 13:16:13 +00001423 case lltok::kw_alignstack:
1424 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001425 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001426 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001427 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001428 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001429 case lltok::kw_minsize:
1430 case lltok::kw_naked:
1431 case lltok::kw_nobuiltin:
1432 case lltok::kw_noduplicate:
1433 case lltok::kw_noimplicitfloat:
1434 case lltok::kw_noinline:
1435 case lltok::kw_nonlazybind:
1436 case lltok::kw_noredzone:
1437 case lltok::kw_noreturn:
1438 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001439 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001440 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001441 case lltok::kw_returns_twice:
1442 case lltok::kw_sanitize_address:
1443 case lltok::kw_sanitize_memory:
1444 case lltok::kw_sanitize_thread:
1445 case lltok::kw_ssp:
1446 case lltok::kw_sspreq:
1447 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001448 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001449 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001450 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1451 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001452 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001453
Bill Wendling34c2eb22012-12-04 23:40:58 +00001454 Lex.Lex();
1455 }
1456}
1457
1458/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1459bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1460 bool HaveError = false;
1461
1462 B.clear();
1463
Eugene Zelenko1804a772016-08-25 00:45:04 +00001464 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001465 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001466 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001467 default: // End of attributes.
1468 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001469 case lltok::StringConstant: {
1470 if (ParseStringAttribute(B))
1471 return true;
1472 continue;
1473 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001474 case lltok::kw_dereferenceable: {
1475 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001476 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001477 return true;
1478 B.addDereferenceableAttr(Bytes);
1479 continue;
1480 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001481 case lltok::kw_dereferenceable_or_null: {
1482 uint64_t Bytes;
1483 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1484 return true;
1485 B.addDereferenceableOrNullAttr(Bytes);
1486 continue;
1487 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001488 case lltok::kw_align: {
1489 unsigned Alignment;
1490 if (ParseOptionalAlignment(Alignment))
1491 return true;
1492 B.addAlignmentAttr(Alignment);
1493 continue;
1494 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001495 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1496 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001497 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001498 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1499 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001500
Bill Wendling34c2eb22012-12-04 23:40:58 +00001501 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001502 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001503 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001504 case lltok::kw_nest:
1505 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001506 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001507 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001508 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001509 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001510 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001511 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001512
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001513 case lltok::kw_alignstack:
1514 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001515 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001516 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001517 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001518 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001519 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001520 case lltok::kw_minsize:
1521 case lltok::kw_naked:
1522 case lltok::kw_nobuiltin:
1523 case lltok::kw_noduplicate:
1524 case lltok::kw_noimplicitfloat:
1525 case lltok::kw_noinline:
1526 case lltok::kw_nonlazybind:
1527 case lltok::kw_noredzone:
1528 case lltok::kw_noreturn:
1529 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001530 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001531 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001532 case lltok::kw_returns_twice:
1533 case lltok::kw_sanitize_address:
1534 case lltok::kw_sanitize_memory:
1535 case lltok::kw_sanitize_thread:
1536 case lltok::kw_ssp:
1537 case lltok::kw_sspreq:
1538 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001539 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001540 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001541 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001542 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001543
1544 case lltok::kw_readnone:
1545 case lltok::kw_readonly:
1546 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001547 }
1548
Chris Lattnerac161bf2009-01-02 07:01:27 +00001549 Lex.Lex();
1550 }
1551}
1552
Rafael Espindolac6269912016-05-10 17:16:45 +00001553static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1554 HasLinkage = true;
1555 switch (Kind) {
1556 default:
1557 HasLinkage = false;
1558 return GlobalValue::ExternalLinkage;
1559 case lltok::kw_private:
1560 return GlobalValue::PrivateLinkage;
1561 case lltok::kw_internal:
1562 return GlobalValue::InternalLinkage;
1563 case lltok::kw_weak:
1564 return GlobalValue::WeakAnyLinkage;
1565 case lltok::kw_weak_odr:
1566 return GlobalValue::WeakODRLinkage;
1567 case lltok::kw_linkonce:
1568 return GlobalValue::LinkOnceAnyLinkage;
1569 case lltok::kw_linkonce_odr:
1570 return GlobalValue::LinkOnceODRLinkage;
1571 case lltok::kw_available_externally:
1572 return GlobalValue::AvailableExternallyLinkage;
1573 case lltok::kw_appending:
1574 return GlobalValue::AppendingLinkage;
1575 case lltok::kw_common:
1576 return GlobalValue::CommonLinkage;
1577 case lltok::kw_extern_weak:
1578 return GlobalValue::ExternalWeakLinkage;
1579 case lltok::kw_external:
1580 return GlobalValue::ExternalLinkage;
1581 }
1582}
1583
Chris Lattnerac161bf2009-01-02 07:01:27 +00001584/// ParseOptionalLinkage
1585/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001586/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001587/// ::= 'internal'
1588/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001589/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001590/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001591/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001592/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001593/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001594/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001595/// ::= 'extern_weak'
1596/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001597bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1598 unsigned &Visibility,
1599 unsigned &DLLStorageClass) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001600 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1601 if (HasLinkage)
1602 Lex.Lex();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001603 ParseOptionalVisibility(Visibility);
1604 ParseOptionalDLLStorageClass(DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001605 return false;
1606}
1607
1608/// ParseOptionalVisibility
1609/// ::= /*empty*/
1610/// ::= 'default'
1611/// ::= 'hidden'
1612/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001613///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001614void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001615 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001616 default:
1617 Res = GlobalValue::DefaultVisibility;
1618 return;
1619 case lltok::kw_default:
1620 Res = GlobalValue::DefaultVisibility;
1621 break;
1622 case lltok::kw_hidden:
1623 Res = GlobalValue::HiddenVisibility;
1624 break;
1625 case lltok::kw_protected:
1626 Res = GlobalValue::ProtectedVisibility;
1627 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001628 }
1629 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001630}
1631
Nico Rieck7157bb72014-01-14 15:22:47 +00001632/// ParseOptionalDLLStorageClass
1633/// ::= /*empty*/
1634/// ::= 'dllimport'
1635/// ::= 'dllexport'
1636///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001637void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001638 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001639 default:
1640 Res = GlobalValue::DefaultStorageClass;
1641 return;
1642 case lltok::kw_dllimport:
1643 Res = GlobalValue::DLLImportStorageClass;
1644 break;
1645 case lltok::kw_dllexport:
1646 Res = GlobalValue::DLLExportStorageClass;
1647 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001648 }
1649 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001650}
1651
Chris Lattnerac161bf2009-01-02 07:01:27 +00001652/// ParseOptionalCallingConv
1653/// ::= /*empty*/
1654/// ::= 'ccc'
1655/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001656/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001657/// ::= 'coldcc'
1658/// ::= 'x86_stdcallcc'
1659/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001660/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001661/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001662/// ::= 'arm_apcscc'
1663/// ::= 'arm_aapcscc'
1664/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001665/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001666/// ::= 'avr_intrcc'
1667/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001668/// ::= 'ptx_kernel'
1669/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001670/// ::= 'spir_func'
1671/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001672/// ::= 'x86_64_sysvcc'
1673/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001674/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001675/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001676/// ::= 'preserve_mostcc'
1677/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001678/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001679/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001680/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001681/// ::= 'hhvmcc'
1682/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001683/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001684/// ::= 'amdgpu_vs'
Marek Olsaka302a7362017-05-02 15:41:10 +00001685/// ::= 'amdgpu_hs'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001686/// ::= 'amdgpu_gs'
1687/// ::= 'amdgpu_ps'
1688/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001689/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001690/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001691///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001692bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001693 switch (Lex.getKind()) {
1694 default: CC = CallingConv::C; return false;
1695 case lltok::kw_ccc: CC = CallingConv::C; break;
1696 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1697 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1698 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1699 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001700 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001701 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001702 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001703 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1704 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1705 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001706 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001707 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1708 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001709 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1710 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001711 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1712 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001713 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001714 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1715 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001716 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001717 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001718 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1719 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001720 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001721 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001722 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001723 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1724 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001725 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001726 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
Marek Olsaka302a7362017-05-02 15:41:10 +00001727 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001728 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1729 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1730 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001731 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001732 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001733 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001734 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001735 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001736 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001737
Chris Lattnerac161bf2009-01-02 07:01:27 +00001738 Lex.Lex();
1739 return false;
1740}
1741
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001742/// ParseMetadataAttachment
1743/// ::= !dbg !42
1744bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1745 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1746
1747 std::string Name = Lex.getStrVal();
1748 Kind = M->getMDKindID(Name);
1749 Lex.Lex();
1750
1751 return ParseMDNode(MD);
1752}
1753
Chris Lattner5c427632009-12-30 05:31:19 +00001754/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001755/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001756bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001757 do {
1758 if (Lex.getKind() != lltok::MetadataVar)
1759 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001760
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001761 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001762 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001763 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001764 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001765
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001766 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001767 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001768 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001769
Chris Lattner596760d2009-12-29 21:25:40 +00001770 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001771 } while (EatIfPresent(lltok::comma));
1772 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001773}
1774
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001775/// ParseGlobalObjectMetadataAttachment
1776/// ::= !dbg !57
1777bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1778 unsigned MDK;
1779 MDNode *N;
1780 if (ParseMetadataAttachment(MDK, N))
1781 return true;
1782
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001783 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001784 return false;
1785}
1786
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001787/// ParseOptionalFunctionMetadata
1788/// ::= (!dbg !57)*
1789bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001790 while (Lex.getKind() == lltok::MetadataVar)
1791 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001792 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001793 return false;
1794}
1795
Chris Lattnerac161bf2009-01-02 07:01:27 +00001796/// ParseOptionalAlignment
1797/// ::= /* empty */
1798/// ::= 'align' 4
1799bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1800 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001801 if (!EatIfPresent(lltok::kw_align))
1802 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001803 LocTy AlignLoc = Lex.getLoc();
1804 if (ParseUInt32(Alignment)) return true;
1805 if (!isPowerOf2_32(Alignment))
1806 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001807 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001808 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001809 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001810}
1811
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001812/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001813/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001814/// ::= AttrKind '(' 4 ')'
1815///
1816/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1817bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1818 uint64_t &Bytes) {
1819 assert((AttrKind == lltok::kw_dereferenceable ||
1820 AttrKind == lltok::kw_dereferenceable_or_null) &&
1821 "contract!");
1822
Hal Finkelb0407ba2014-07-18 15:51:28 +00001823 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001824 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001825 return false;
1826 LocTy ParenLoc = Lex.getLoc();
1827 if (!EatIfPresent(lltok::lparen))
1828 return Error(ParenLoc, "expected '('");
1829 LocTy DerefLoc = Lex.getLoc();
1830 if (ParseUInt64(Bytes)) return true;
1831 ParenLoc = Lex.getLoc();
1832 if (!EatIfPresent(lltok::rparen))
1833 return Error(ParenLoc, "expected ')'");
1834 if (!Bytes)
1835 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1836 return false;
1837}
1838
Chris Lattnerb2f39502009-12-30 05:44:30 +00001839/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001840/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001841/// ::= ',' align 4
1842///
1843/// This returns with AteExtraComma set to true if it ate an excess comma at the
1844/// end.
1845bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1846 bool &AteExtraComma) {
1847 AteExtraComma = false;
1848 while (EatIfPresent(lltok::comma)) {
1849 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001850 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001851 AteExtraComma = true;
1852 return false;
1853 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001854
Chris Lattner95b0ff42010-04-23 00:50:50 +00001855 if (Lex.getKind() != lltok::kw_align)
1856 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001857
Chris Lattner95b0ff42010-04-23 00:50:50 +00001858 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001859 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001860
Devang Patelea8a4b92009-09-17 23:04:48 +00001861 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001862}
1863
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001864/// ParseOptionalCommaAddrSpace
1865/// ::=
1866/// ::= ',' addrspace(1)
1867///
1868/// This returns with AteExtraComma set to true if it ate an excess comma at the
1869/// end.
1870bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
1871 LocTy &Loc,
1872 bool &AteExtraComma) {
1873 AteExtraComma = false;
1874 while (EatIfPresent(lltok::comma)) {
1875 // Metadata at the end is an early exit.
1876 if (Lex.getKind() == lltok::MetadataVar) {
1877 AteExtraComma = true;
1878 return false;
1879 }
1880
1881 Loc = Lex.getLoc();
1882 if (Lex.getKind() != lltok::kw_addrspace)
1883 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
1884
1885 if (ParseOptionalAddrSpace(AddrSpace))
1886 return true;
1887 }
1888
1889 return false;
1890}
1891
George Burgess IV278199f2016-04-12 01:05:35 +00001892bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1893 Optional<unsigned> &HowManyArg) {
1894 Lex.Lex();
1895
1896 auto StartParen = Lex.getLoc();
1897 if (!EatIfPresent(lltok::lparen))
1898 return Error(StartParen, "expected '('");
1899
1900 if (ParseUInt32(BaseSizeArg))
1901 return true;
1902
1903 if (EatIfPresent(lltok::comma)) {
1904 auto HowManyAt = Lex.getLoc();
1905 unsigned HowMany;
1906 if (ParseUInt32(HowMany))
1907 return true;
1908 if (HowMany == BaseSizeArg)
1909 return Error(HowManyAt,
1910 "'allocsize' indices can't refer to the same parameter");
1911 HowManyArg = HowMany;
1912 } else
1913 HowManyArg = None;
1914
1915 auto EndParen = Lex.getLoc();
1916 if (!EatIfPresent(lltok::rparen))
1917 return Error(EndParen, "expected ')'");
1918 return false;
1919}
1920
Eli Friedmanfee02c62011-07-25 23:16:38 +00001921/// ParseScopeAndOrdering
1922/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1923/// else: ::=
1924///
1925/// This sets Scope and Ordering to the parsed values.
1926bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1927 AtomicOrdering &Ordering) {
1928 if (!isAtomic)
1929 return false;
1930
1931 Scope = CrossThread;
1932 if (EatIfPresent(lltok::kw_singlethread))
1933 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001934
1935 return ParseOrdering(Ordering);
1936}
1937
1938/// ParseOrdering
1939/// ::= AtomicOrdering
1940///
1941/// This sets Ordering to the parsed value.
1942bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001943 switch (Lex.getKind()) {
1944 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001945 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1946 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1947 // Not specified yet:
1948 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1949 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1950 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1951 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1952 case lltok::kw_seq_cst:
1953 Ordering = AtomicOrdering::SequentiallyConsistent;
1954 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001955 }
1956 Lex.Lex();
1957 return false;
1958}
1959
Charles Davisbe5557e2010-02-12 00:31:15 +00001960/// ParseOptionalStackAlignment
1961/// ::= /* empty */
1962/// ::= 'alignstack' '(' 4 ')'
1963bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1964 Alignment = 0;
1965 if (!EatIfPresent(lltok::kw_alignstack))
1966 return false;
1967 LocTy ParenLoc = Lex.getLoc();
1968 if (!EatIfPresent(lltok::lparen))
1969 return Error(ParenLoc, "expected '('");
1970 LocTy AlignLoc = Lex.getLoc();
1971 if (ParseUInt32(Alignment)) return true;
1972 ParenLoc = Lex.getLoc();
1973 if (!EatIfPresent(lltok::rparen))
1974 return Error(ParenLoc, "expected ')'");
1975 if (!isPowerOf2_32(Alignment))
1976 return Error(AlignLoc, "stack alignment is not a power of two");
1977 return false;
1978}
Devang Patelea8a4b92009-09-17 23:04:48 +00001979
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001980/// ParseIndexList - This parses the index list for an insert/extractvalue
1981/// instruction. This sets AteExtraComma in the case where we eat an extra
1982/// comma at the end of the line and find that it is followed by metadata.
1983/// Clients that don't allow metadata can call the version of this function that
1984/// only takes one argument.
1985///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001986/// ParseIndexList
1987/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001988///
1989bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1990 bool &AteExtraComma) {
1991 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001992
Chris Lattnerac161bf2009-01-02 07:01:27 +00001993 if (Lex.getKind() != lltok::comma)
1994 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001995
Chris Lattner3822f632009-01-02 08:05:26 +00001996 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001997 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001998 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001999 AteExtraComma = true;
2000 return false;
2001 }
Nick Lewycky83e47112010-09-29 23:32:20 +00002002 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002003 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002004 Indices.push_back(Idx);
2005 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002006
Chris Lattnerac161bf2009-01-02 07:01:27 +00002007 return false;
2008}
2009
2010//===----------------------------------------------------------------------===//
2011// Type Parsing.
2012//===----------------------------------------------------------------------===//
2013
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002014/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002015bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002016 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002017 switch (Lex.getKind()) {
2018 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002019 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002020 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002021 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002022 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002023 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002024 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002025 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002026 // Type ::= StructType
2027 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002028 return true;
2029 break;
2030 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002031 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002032 Lex.Lex(); // eat the lsquare.
2033 if (ParseArrayVectorType(Result, false))
2034 return true;
2035 break;
2036 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002037 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002038 Lex.Lex();
2039 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002040 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002041 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002042 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002043 } else if (ParseArrayVectorType(Result, true))
2044 return true;
2045 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002046 case lltok::LocalVar: {
2047 // Type ::= %foo
2048 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002049
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002050 // If the type hasn't been defined yet, create a forward definition and
2051 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002052 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002053 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002054 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002055 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002056 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002057 Lex.Lex();
2058 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002059 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002060
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002061 case lltok::LocalVarID: {
2062 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002063 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002064
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002065 // If the type hasn't been defined yet, create a forward definition and
2066 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002067 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002068 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002069 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002070 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002071 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002072 Lex.Lex();
2073 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002074 }
2075 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002076
2077 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002078 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002079 switch (Lex.getKind()) {
2080 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002081 default:
2082 if (!AllowVoid && Result->isVoidTy())
2083 return Error(TypeLoc, "void type only allowed for function results");
2084 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002085
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002086 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002087 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002088 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002089 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002090 if (Result->isVoidTy())
2091 return TokError("pointers to void are invalid - use i8* instead");
2092 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002093 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002094 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002095 Lex.Lex();
2096 break;
2097
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002098 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002099 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002100 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002101 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002102 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002103 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002104 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002105 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002106 unsigned AddrSpace;
2107 if (ParseOptionalAddrSpace(AddrSpace) ||
2108 ParseToken(lltok::star, "expected '*' in address space"))
2109 return true;
2110
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002111 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002112 break;
2113 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002114
Chris Lattnerac161bf2009-01-02 07:01:27 +00002115 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2116 case lltok::lparen:
2117 if (ParseFunctionType(Result))
2118 return true;
2119 break;
2120 }
2121 }
2122}
2123
2124/// ParseParameterList
2125/// ::= '(' ')'
2126/// ::= '(' Arg (',' Arg)* ')'
2127/// Arg
2128/// ::= Type OptionalAttributes Value OptionalAttributes
2129bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002130 PerFunctionState &PFS, bool IsMustTailCall,
2131 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002132 if (ParseToken(lltok::lparen, "expected '(' in call"))
2133 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002134
Chris Lattnerac161bf2009-01-02 07:01:27 +00002135 while (Lex.getKind() != lltok::rparen) {
2136 // If this isn't the first argument, we need a comma.
2137 if (!ArgList.empty() &&
2138 ParseToken(lltok::comma, "expected ',' in argument list"))
2139 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002140
Reid Kleckner83498642014-08-26 00:33:28 +00002141 // Parse an ellipsis if this is a musttail call in a variadic function.
2142 if (Lex.getKind() == lltok::dotdotdot) {
2143 const char *Msg = "unexpected ellipsis in argument list for ";
2144 if (!IsMustTailCall)
2145 return TokError(Twine(Msg) + "non-musttail call");
2146 if (!InVarArgsFunc)
2147 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2148 Lex.Lex(); // Lex the '...', it is purely for readability.
2149 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2150 }
2151
Chris Lattnerac161bf2009-01-02 07:01:27 +00002152 // Parse the argument.
2153 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002154 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002155 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002156 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002157 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002158 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002159
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002160 if (ArgTy->isMetadataTy()) {
2161 if (ParseMetadataAsValue(V, PFS))
2162 return true;
2163 } else {
2164 // Otherwise, handle normal operands.
2165 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2166 return true;
2167 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002168 ArgList.push_back(ParamInfo(
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002169 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002170 }
2171
Reid Kleckner83498642014-08-26 00:33:28 +00002172 if (IsMustTailCall && InVarArgsFunc)
2173 return TokError("expected '...' at end of argument list for musttail call "
2174 "in varargs function");
2175
Chris Lattnerac161bf2009-01-02 07:01:27 +00002176 Lex.Lex(); // Lex the ')'.
2177 return false;
2178}
2179
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002180/// ParseOptionalOperandBundles
2181/// ::= /*empty*/
2182/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2183///
2184/// OperandBundle
2185/// ::= bundle-tag '(' ')'
2186/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2187///
2188/// bundle-tag ::= String Constant
2189bool LLParser::ParseOptionalOperandBundles(
2190 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2191 LocTy BeginLoc = Lex.getLoc();
2192 if (!EatIfPresent(lltok::lsquare))
2193 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002194
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002195 while (Lex.getKind() != lltok::rsquare) {
2196 // If this isn't the first operand bundle, we need a comma.
2197 if (!BundleList.empty() &&
2198 ParseToken(lltok::comma, "expected ',' in input list"))
2199 return true;
2200
2201 std::string Tag;
2202 if (ParseStringConstant(Tag))
2203 return true;
2204
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002205 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2206 return true;
2207
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002208 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002209 while (Lex.getKind() != lltok::rparen) {
2210 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002211 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002212 ParseToken(lltok::comma, "expected ',' in input list"))
2213 return true;
2214
2215 Type *Ty = nullptr;
2216 Value *Input = nullptr;
2217 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2218 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002219 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002220 }
2221
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002222 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2223
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002224 Lex.Lex(); // Lex the ')'.
2225 }
2226
2227 if (BundleList.empty())
2228 return Error(BeginLoc, "operand bundle set must not be empty");
2229
2230 Lex.Lex(); // Lex the ']'.
2231 return false;
2232}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002233
Chris Lattner2ed06b42009-01-05 18:34:07 +00002234/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002235/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002236/// ::= '(' ArgTypeListI ')'
2237/// ArgTypeListI
2238/// ::= /*empty*/
2239/// ::= '...'
2240/// ::= ArgTypeList ',' '...'
2241/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002242///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002243bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2244 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002245 isVarArg = false;
2246 assert(Lex.getKind() == lltok::lparen);
2247 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002248
Chris Lattnerac161bf2009-01-02 07:01:27 +00002249 if (Lex.getKind() == lltok::rparen) {
2250 // empty
2251 } else if (Lex.getKind() == lltok::dotdotdot) {
2252 isVarArg = true;
2253 Lex.Lex();
2254 } else {
2255 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002256 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002257 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002258 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002259
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002260 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002261 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002262
Chris Lattnerfdd87902009-10-05 05:54:46 +00002263 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002264 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002265
Chris Lattnerdef19492011-06-17 06:36:20 +00002266 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002267 Name = Lex.getStrVal();
2268 Lex.Lex();
2269 }
Chris Lattner3822f632009-01-02 08:05:26 +00002270
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002271 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002272 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002273
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002274 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002275 AttributeSet::get(ArgTy->getContext(), Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002276 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002277
Chris Lattner3822f632009-01-02 08:05:26 +00002278 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002279 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002280 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002281 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002282 break;
2283 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002284
Chris Lattnerac161bf2009-01-02 07:01:27 +00002285 // Otherwise must be an argument type.
2286 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002287 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002288
Chris Lattnerfdd87902009-10-05 05:54:46 +00002289 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002290 return Error(TypeLoc, "argument can not have void type");
2291
Chris Lattnerdef19492011-06-17 06:36:20 +00002292 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002293 Name = Lex.getStrVal();
2294 Lex.Lex();
2295 } else {
2296 Name = "";
2297 }
Chris Lattner3822f632009-01-02 08:05:26 +00002298
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002299 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002300 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002301
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002302 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002303 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002304 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002305 }
2306 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002307
Chris Lattner3822f632009-01-02 08:05:26 +00002308 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002309}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002310
Chris Lattnerac161bf2009-01-02 07:01:27 +00002311/// ParseFunctionType
2312/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002313bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002314 assert(Lex.getKind() == lltok::lparen);
2315
Chris Lattnerce473c72009-01-05 08:04:33 +00002316 if (!FunctionType::isValidReturnType(Result))
2317 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002318
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002319 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002320 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002321 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002322 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002323
Chris Lattnerac161bf2009-01-02 07:01:27 +00002324 // Reject names on the arguments lists.
2325 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2326 if (!ArgList[i].Name.empty())
2327 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002328 if (ArgList[i].Attrs.hasAttributes())
Chris Lattner6bc5c892011-06-17 17:37:13 +00002329 return Error(ArgList[i].Loc,
2330 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002331 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002332
Jay Foadb804a2b2011-07-12 14:06:48 +00002333 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002334 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002335 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002336
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002337 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002338 return false;
2339}
2340
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002341/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2342/// other structs.
2343bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2344 SmallVector<Type*, 8> Elts;
2345 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002346
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002347 Result = StructType::get(Context, Elts, Packed);
2348 return false;
2349}
2350
2351/// ParseStructDefinition - Parse a struct in a 'type' definition.
2352bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2353 std::pair<Type*, LocTy> &Entry,
2354 Type *&ResultTy) {
2355 // If the type was already defined, diagnose the redefinition.
2356 if (Entry.first && !Entry.second.isValid())
2357 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002358
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002359 // If we have opaque, just return without filling in the definition for the
2360 // struct. This counts as a definition as far as the .ll file goes.
2361 if (EatIfPresent(lltok::kw_opaque)) {
2362 // This type is being defined, so clear the location to indicate this.
2363 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002364
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002365 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002366 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002367 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002368 ResultTy = Entry.first;
2369 return false;
2370 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002371
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002372 // If the type starts with '<', then it is either a packed struct or a vector.
2373 bool isPacked = EatIfPresent(lltok::less);
2374
2375 // If we don't have a struct, then we have a random type alias, which we
2376 // accept for compatibility with old files. These types are not allowed to be
2377 // forward referenced and not allowed to be recursive.
2378 if (Lex.getKind() != lltok::lbrace) {
2379 if (Entry.first)
2380 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002381
Craig Topper2617dcc2014-04-15 06:32:26 +00002382 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002383 if (isPacked)
2384 return ParseArrayVectorType(ResultTy, true);
2385 return ParseType(ResultTy);
2386 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002387
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002388 // This type is being defined, so clear the location to indicate this.
2389 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002390
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002391 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002392 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002393 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002394
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002395 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002396
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002397 SmallVector<Type*, 8> Body;
2398 if (ParseStructBody(Body) ||
2399 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2400 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002401
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002402 STy->setBody(Body, isPacked);
2403 ResultTy = STy;
2404 return false;
2405}
2406
Chris Lattnerac161bf2009-01-02 07:01:27 +00002407/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002408/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002409/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002410/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002411/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002412/// ::= '<' '{' Type (',' Type)* '}' '>'
2413bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002414 assert(Lex.getKind() == lltok::lbrace);
2415 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002416
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002417 // Handle the empty struct.
2418 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002419 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002420
Chris Lattnerf880ca22009-03-09 04:49:14 +00002421 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002422 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002423 if (ParseType(Ty)) return true;
2424 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002425
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002426 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002427 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002428
Chris Lattner3822f632009-01-02 08:05:26 +00002429 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002430 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002431 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002432
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002433 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002434 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002435
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002436 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002437 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002438
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002439 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002440}
2441
2442/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2443/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002444/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002445/// ::= '[' APSINTVAL 'x' Types ']'
2446/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002447bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002448 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2449 Lex.getAPSIntVal().getBitWidth() > 64)
2450 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002451
Chris Lattnerac161bf2009-01-02 07:01:27 +00002452 LocTy SizeLoc = Lex.getLoc();
2453 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002454 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002455
Chris Lattner3822f632009-01-02 08:05:26 +00002456 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2457 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002458
2459 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002460 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002461 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002462
Chris Lattner3822f632009-01-02 08:05:26 +00002463 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2464 "expected end of sequential type"))
2465 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002466
Chris Lattnerac161bf2009-01-02 07:01:27 +00002467 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002468 if (Size == 0)
2469 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002470 if ((unsigned)Size != Size)
2471 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002472 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002473 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002474 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002475 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002476 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002477 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002478 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002479 }
2480 return false;
2481}
2482
2483//===----------------------------------------------------------------------===//
2484// Function Semantic Analysis.
2485//===----------------------------------------------------------------------===//
2486
Chris Lattner3432c622009-10-28 03:39:23 +00002487LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2488 int functionNumber)
2489 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002490
2491 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002492 for (Argument &A : F.args())
2493 if (!A.hasName())
2494 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002495}
2496
2497LLParser::PerFunctionState::~PerFunctionState() {
2498 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002499
David Blaikie9ebdc692015-09-21 21:07:50 +00002500 for (const auto &P : ForwardRefVals) {
2501 if (isa<BasicBlock>(P.second.first))
2502 continue;
2503 P.second.first->replaceAllUsesWith(
2504 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002505 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002506 }
2507
2508 for (const auto &P : ForwardRefValIDs) {
2509 if (isa<BasicBlock>(P.second.first))
2510 continue;
2511 P.second.first->replaceAllUsesWith(
2512 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002513 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002514 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002515}
2516
Chris Lattner3432c622009-10-28 03:39:23 +00002517bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002518 if (!ForwardRefVals.empty())
2519 return P.Error(ForwardRefVals.begin()->second.second,
2520 "use of undefined value '%" + ForwardRefVals.begin()->first +
2521 "'");
2522 if (!ForwardRefValIDs.empty())
2523 return P.Error(ForwardRefValIDs.begin()->second.second,
2524 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002525 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002526 return false;
2527}
2528
Chris Lattnerac161bf2009-01-02 07:01:27 +00002529/// GetVal - Get a value with the specified name or ID, creating a
2530/// forward reference record if needed. This can return null if the value
2531/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002532Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002533 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002534 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002535 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002536
Chris Lattnerac161bf2009-01-02 07:01:27 +00002537 // If this is a forward reference for the value, see if we already created a
2538 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002539 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002540 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002541 if (I != ForwardRefVals.end())
2542 Val = I->second.first;
2543 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002544
Chris Lattnerac161bf2009-01-02 07:01:27 +00002545 // If we have the value in the symbol table or fwd-ref table, return it.
2546 if (Val) {
2547 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002548 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002549 P.Error(Loc, "'%" + Name + "' is not a basic block");
2550 else
2551 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002552 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002553 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002554 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002555
Chris Lattnerac161bf2009-01-02 07:01:27 +00002556 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002557 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002558 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002559 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002560 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002561
Chris Lattnerac161bf2009-01-02 07:01:27 +00002562 // Otherwise, create a new forward reference for this value and remember it.
2563 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002564 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002565 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002566 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002567 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002568 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002569
Chris Lattnerac161bf2009-01-02 07:01:27 +00002570 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2571 return FwdVal;
2572}
2573
David Majnemer8a1c45d2015-12-12 05:38:55 +00002574Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002575 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002576 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002577
Chris Lattnerac161bf2009-01-02 07:01:27 +00002578 // If this is a forward reference for the value, see if we already created a
2579 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002580 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002581 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002582 if (I != ForwardRefValIDs.end())
2583 Val = I->second.first;
2584 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002585
Chris Lattnerac161bf2009-01-02 07:01:27 +00002586 // If we have the value in the symbol table or fwd-ref table, return it.
2587 if (Val) {
2588 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002589 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002590 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002591 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002592 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002593 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002594 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002595 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002596
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002597 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002598 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002599 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002600 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002601
Chris Lattnerac161bf2009-01-02 07:01:27 +00002602 // Otherwise, create a new forward reference for this value and remember it.
2603 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002604 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002605 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002606 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002607 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002608 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002609
Chris Lattnerac161bf2009-01-02 07:01:27 +00002610 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2611 return FwdVal;
2612}
2613
2614/// SetInstName - After an instruction is parsed and inserted into its
2615/// basic block, this installs its name.
2616bool LLParser::PerFunctionState::SetInstName(int NameID,
2617 const std::string &NameStr,
2618 LocTy NameLoc, Instruction *Inst) {
2619 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002620 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002621 if (NameID != -1 || !NameStr.empty())
2622 return P.Error(NameLoc, "instructions returning void cannot have a name");
2623 return false;
2624 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002625
Chris Lattnerac161bf2009-01-02 07:01:27 +00002626 // If this was a numbered instruction, verify that the instruction is the
2627 // expected value and resolve any forward references.
2628 if (NameStr.empty()) {
2629 // If neither a name nor an ID was specified, just use the next ID.
2630 if (NameID == -1)
2631 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002632
Chris Lattnerac161bf2009-01-02 07:01:27 +00002633 if (unsigned(NameID) != NumberedVals.size())
2634 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002635 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002636
David Blaikie9ebdc692015-09-21 21:07:50 +00002637 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002638 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002639 Value *Sentinel = FI->second.first;
2640 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002641 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002642 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002643
2644 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002645 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002646 ForwardRefValIDs.erase(FI);
2647 }
2648
2649 NumberedVals.push_back(Inst);
2650 return false;
2651 }
2652
2653 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002654 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002655 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002656 Value *Sentinel = FI->second.first;
2657 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002658 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002659 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002660
2661 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002662 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002663 ForwardRefVals.erase(FI);
2664 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002665
Chris Lattnerac161bf2009-01-02 07:01:27 +00002666 // Set the name on the instruction.
2667 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002668
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002669 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002670 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002671 NameStr + "'");
2672 return false;
2673}
2674
2675/// GetBB - Get a basic block with the specified name or ID, creating a
2676/// forward reference record if needed.
2677BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2678 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002679 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2680 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002681}
2682
2683BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002684 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2685 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002686}
2687
2688/// DefineBB - Define the specified basic block, which is either named or
2689/// unnamed. If there is an error, this returns null otherwise it returns
2690/// the block being defined.
2691BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2692 LocTy Loc) {
2693 BasicBlock *BB;
2694 if (Name.empty())
2695 BB = GetBB(NumberedVals.size(), Loc);
2696 else
2697 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002698 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002699
Chris Lattnerac161bf2009-01-02 07:01:27 +00002700 // Move the block to the end of the function. Forward ref'd blocks are
2701 // inserted wherever they happen to be referenced.
2702 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002703
Chris Lattnerac161bf2009-01-02 07:01:27 +00002704 // Remove the block from forward ref sets.
2705 if (Name.empty()) {
2706 ForwardRefValIDs.erase(NumberedVals.size());
2707 NumberedVals.push_back(BB);
2708 } else {
2709 // BB forward references are already in the function symbol table.
2710 ForwardRefVals.erase(Name);
2711 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002712
Chris Lattnerac161bf2009-01-02 07:01:27 +00002713 return BB;
2714}
2715
2716//===----------------------------------------------------------------------===//
2717// Constants.
2718//===----------------------------------------------------------------------===//
2719
2720/// ParseValID - Parse an abstract value that doesn't necessarily have a
2721/// type implied. For example, if we parse "4" we don't know what integer type
2722/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002723/// sanity. PFS is used to convert function-local operands of metadata (since
2724/// metadata operands are not just parsed here but also converted to values).
2725/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002726bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002727 ID.Loc = Lex.getLoc();
2728 switch (Lex.getKind()) {
2729 default: return TokError("expected value token");
2730 case lltok::GlobalID: // @42
2731 ID.UIntVal = Lex.getUIntVal();
2732 ID.Kind = ValID::t_GlobalID;
2733 break;
2734 case lltok::GlobalVar: // @foo
2735 ID.StrVal = Lex.getStrVal();
2736 ID.Kind = ValID::t_GlobalName;
2737 break;
2738 case lltok::LocalVarID: // %42
2739 ID.UIntVal = Lex.getUIntVal();
2740 ID.Kind = ValID::t_LocalID;
2741 break;
2742 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002743 ID.StrVal = Lex.getStrVal();
2744 ID.Kind = ValID::t_LocalName;
2745 break;
2746 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002747 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002748 ID.Kind = ValID::t_APSInt;
2749 break;
2750 case lltok::APFloat:
2751 ID.APFloatVal = Lex.getAPFloatVal();
2752 ID.Kind = ValID::t_APFloat;
2753 break;
2754 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002755 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002756 ID.Kind = ValID::t_Constant;
2757 break;
2758 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002759 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002760 ID.Kind = ValID::t_Constant;
2761 break;
2762 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2763 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2764 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002765 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002766
Chris Lattnerac161bf2009-01-02 07:01:27 +00002767 case lltok::lbrace: {
2768 // ValID ::= '{' ConstVector '}'
2769 Lex.Lex();
2770 SmallVector<Constant*, 16> Elts;
2771 if (ParseGlobalValueVector(Elts) ||
2772 ParseToken(lltok::rbrace, "expected end of struct constant"))
2773 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002774
David Blaikieadbda4b2015-08-03 20:08:41 +00002775 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002776 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002777 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2778 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002779 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002780 return false;
2781 }
2782 case lltok::less: {
2783 // ValID ::= '<' ConstVector '>' --> Vector.
2784 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2785 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002786 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002787
Chris Lattnerac161bf2009-01-02 07:01:27 +00002788 SmallVector<Constant*, 16> Elts;
2789 LocTy FirstEltLoc = Lex.getLoc();
2790 if (ParseGlobalValueVector(Elts) ||
2791 (isPackedStruct &&
2792 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2793 ParseToken(lltok::greater, "expected end of constant"))
2794 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002795
Chris Lattnerac161bf2009-01-02 07:01:27 +00002796 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002797 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2798 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2799 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002800 ID.UIntVal = Elts.size();
2801 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002802 return false;
2803 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002804
Chris Lattnerac161bf2009-01-02 07:01:27 +00002805 if (Elts.empty())
2806 return Error(ID.Loc, "constant vector must not be empty");
2807
Duncan Sands9dff9be2010-02-15 16:12:20 +00002808 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002809 !Elts[0]->getType()->isFloatingPointTy() &&
2810 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002811 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002812 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002813
Chris Lattnerac161bf2009-01-02 07:01:27 +00002814 // Verify that all the vector elements have the same type.
2815 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2816 if (Elts[i]->getType() != Elts[0]->getType())
2817 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002818 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002819 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002820
Chris Lattner69229312011-02-15 00:14:00 +00002821 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002822 ID.Kind = ValID::t_Constant;
2823 return false;
2824 }
2825 case lltok::lsquare: { // Array Constant
2826 Lex.Lex();
2827 SmallVector<Constant*, 16> Elts;
2828 LocTy FirstEltLoc = Lex.getLoc();
2829 if (ParseGlobalValueVector(Elts) ||
2830 ParseToken(lltok::rsquare, "expected end of array constant"))
2831 return true;
2832
2833 // Handle empty element.
2834 if (Elts.empty()) {
2835 // Use undef instead of an array because it's inconvenient to determine
2836 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002837 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002838 return false;
2839 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002840
Chris Lattnerac161bf2009-01-02 07:01:27 +00002841 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002842 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002843 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002844
Owen Anderson4056ca92009-07-29 22:17:13 +00002845 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002846
Chris Lattnerac161bf2009-01-02 07:01:27 +00002847 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002848 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002849 if (Elts[i]->getType() != Elts[0]->getType())
2850 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002851 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002852 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002853 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002854
Jay Foad83be3612011-06-22 09:24:39 +00002855 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002856 ID.Kind = ValID::t_Constant;
2857 return false;
2858 }
2859 case lltok::kw_c: // c "foo"
2860 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002861 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2862 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002863 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2864 ID.Kind = ValID::t_Constant;
2865 return false;
2866
2867 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002868 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2869 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002870 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002871 Lex.Lex();
2872 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002873 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002874 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002875 ParseStringConstant(ID.StrVal) ||
2876 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002877 ParseToken(lltok::StringConstant, "expected constraint string"))
2878 return true;
2879 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002880 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002881 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002882 ID.Kind = ValID::t_InlineAsm;
2883 return false;
2884 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002885
Chris Lattner3432c622009-10-28 03:39:23 +00002886 case lltok::kw_blockaddress: {
2887 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2888 Lex.Lex();
2889
2890 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002891
Chris Lattner3432c622009-10-28 03:39:23 +00002892 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2893 ParseValID(Fn) ||
2894 ParseToken(lltok::comma, "expected comma in block address expression")||
2895 ParseValID(Label) ||
2896 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2897 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002898
Chris Lattner3432c622009-10-28 03:39:23 +00002899 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2900 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002901 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002902 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002903
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002904 // Try to find the function (but skip it if it's forward-referenced).
2905 GlobalValue *GV = nullptr;
2906 if (Fn.Kind == ValID::t_GlobalID) {
2907 if (Fn.UIntVal < NumberedVals.size())
2908 GV = NumberedVals[Fn.UIntVal];
2909 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2910 GV = M->getNamedValue(Fn.StrVal);
2911 }
2912 Function *F = nullptr;
2913 if (GV) {
2914 // Confirm that it's actually a function with a definition.
2915 if (!isa<Function>(GV))
2916 return Error(Fn.Loc, "expected function name in blockaddress");
2917 F = cast<Function>(GV);
2918 if (F->isDeclaration())
2919 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2920 }
2921
2922 if (!F) {
2923 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002924 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002925 ForwardRefBlockAddresses.insert(std::make_pair(
2926 std::move(Fn),
2927 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002928 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2929 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002930 if (!FwdRef)
2931 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2932 GlobalValue::InternalLinkage, nullptr, "");
2933 ID.ConstantVal = FwdRef;
2934 ID.Kind = ValID::t_Constant;
2935 return false;
2936 }
2937
2938 // We found the function; now find the basic block. Don't use PFS, since we
2939 // might be inside a constant expression.
2940 BasicBlock *BB;
2941 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2942 if (Label.Kind == ValID::t_LocalID)
2943 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2944 else
2945 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2946 if (!BB)
2947 return Error(Label.Loc, "referenced value is not a basic block");
2948 } else {
2949 if (Label.Kind == ValID::t_LocalID)
2950 return Error(Label.Loc, "cannot take address of numeric label after "
2951 "the function is defined");
2952 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002953 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002954 if (!BB)
2955 return Error(Label.Loc, "referenced value is not a basic block");
2956 }
2957
2958 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002959 ID.Kind = ValID::t_Constant;
2960 return false;
2961 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002962
Chris Lattnerac161bf2009-01-02 07:01:27 +00002963 case lltok::kw_trunc:
2964 case lltok::kw_zext:
2965 case lltok::kw_sext:
2966 case lltok::kw_fptrunc:
2967 case lltok::kw_fpext:
2968 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002969 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002970 case lltok::kw_uitofp:
2971 case lltok::kw_sitofp:
2972 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002973 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002974 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002975 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002976 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002977 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002978 Constant *SrcVal;
2979 Lex.Lex();
2980 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2981 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002982 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002983 ParseType(DestTy) ||
2984 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2985 return true;
2986 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2987 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002988 getTypeString(SrcVal->getType()) + "' to '" +
2989 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002990 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002991 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002992 ID.Kind = ValID::t_Constant;
2993 return false;
2994 }
2995 case lltok::kw_extractvalue: {
2996 Lex.Lex();
2997 Constant *Val;
2998 SmallVector<unsigned, 4> Indices;
2999 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3000 ParseGlobalTypeAndValue(Val) ||
3001 ParseIndexList(Indices) ||
3002 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3003 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00003004
Chris Lattner392be582010-02-12 20:49:41 +00003005 if (!Val->getType()->isAggregateType())
3006 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00003007 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003008 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00003009 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003010 ID.Kind = ValID::t_Constant;
3011 return false;
3012 }
3013 case lltok::kw_insertvalue: {
3014 Lex.Lex();
3015 Constant *Val0, *Val1;
3016 SmallVector<unsigned, 4> Indices;
3017 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3018 ParseGlobalTypeAndValue(Val0) ||
3019 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3020 ParseGlobalTypeAndValue(Val1) ||
3021 ParseIndexList(Indices) ||
3022 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3023 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003024 if (!Val0->getType()->isAggregateType())
3025 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003026 Type *IndexedType =
3027 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3028 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003029 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003030 if (IndexedType != Val1->getType())
3031 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3032 getTypeString(Val1->getType()) +
3033 "' instead of '" + getTypeString(IndexedType) +
3034 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003035 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003036 ID.Kind = ValID::t_Constant;
3037 return false;
3038 }
3039 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003040 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003041 unsigned PredVal, Opc = Lex.getUIntVal();
3042 Constant *Val0, *Val1;
3043 Lex.Lex();
3044 if (ParseCmpPredicate(PredVal, Opc) ||
3045 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3046 ParseGlobalTypeAndValue(Val0) ||
3047 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3048 ParseGlobalTypeAndValue(Val1) ||
3049 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3050 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003051
Chris Lattnerac161bf2009-01-02 07:01:27 +00003052 if (Val0->getType() != Val1->getType())
3053 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003054
Chris Lattnerac161bf2009-01-02 07:01:27 +00003055 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003056
Chris Lattnerac161bf2009-01-02 07:01:27 +00003057 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003058 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003059 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003060 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003061 } else {
3062 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003063 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003064 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003065 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003066 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003067 }
3068 ID.Kind = ValID::t_Constant;
3069 return false;
3070 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003071
Chris Lattnerac161bf2009-01-02 07:01:27 +00003072 // Binary Operators.
3073 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003074 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003075 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003076 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003077 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003078 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003079 case lltok::kw_udiv:
3080 case lltok::kw_sdiv:
3081 case lltok::kw_fdiv:
3082 case lltok::kw_urem:
3083 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003084 case lltok::kw_frem:
3085 case lltok::kw_shl:
3086 case lltok::kw_lshr:
3087 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003088 bool NUW = false;
3089 bool NSW = false;
3090 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003091 unsigned Opc = Lex.getUIntVal();
3092 Constant *Val0, *Val1;
3093 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003094 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003095 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3096 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003097 if (EatIfPresent(lltok::kw_nuw))
3098 NUW = true;
3099 if (EatIfPresent(lltok::kw_nsw)) {
3100 NSW = true;
3101 if (EatIfPresent(lltok::kw_nuw))
3102 NUW = true;
3103 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003104 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3105 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003106 if (EatIfPresent(lltok::kw_exact))
3107 Exact = true;
3108 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003109 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3110 ParseGlobalTypeAndValue(Val0) ||
3111 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3112 ParseGlobalTypeAndValue(Val1) ||
3113 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3114 return true;
3115 if (Val0->getType() != Val1->getType())
3116 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003117 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003118 if (NUW)
3119 return Error(ModifierLoc, "nuw only applies to integer operations");
3120 if (NSW)
3121 return Error(ModifierLoc, "nsw only applies to integer operations");
3122 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003123 // Check that the type is valid for the operator.
3124 switch (Opc) {
3125 case Instruction::Add:
3126 case Instruction::Sub:
3127 case Instruction::Mul:
3128 case Instruction::UDiv:
3129 case Instruction::SDiv:
3130 case Instruction::URem:
3131 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003132 case Instruction::Shl:
3133 case Instruction::AShr:
3134 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003135 if (!Val0->getType()->isIntOrIntVectorTy())
3136 return Error(ID.Loc, "constexpr requires integer operands");
3137 break;
3138 case Instruction::FAdd:
3139 case Instruction::FSub:
3140 case Instruction::FMul:
3141 case Instruction::FDiv:
3142 case Instruction::FRem:
3143 if (!Val0->getType()->isFPOrFPVectorTy())
3144 return Error(ID.Loc, "constexpr requires fp operands");
3145 break;
3146 default: llvm_unreachable("Unknown binary operator!");
3147 }
Dan Gohman1b849082009-09-07 23:54:19 +00003148 unsigned Flags = 0;
3149 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3150 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003151 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003152 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003153 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003154 ID.Kind = ValID::t_Constant;
3155 return false;
3156 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003157
Chris Lattnerac161bf2009-01-02 07:01:27 +00003158 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003159 case lltok::kw_and:
3160 case lltok::kw_or:
3161 case lltok::kw_xor: {
3162 unsigned Opc = Lex.getUIntVal();
3163 Constant *Val0, *Val1;
3164 Lex.Lex();
3165 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3166 ParseGlobalTypeAndValue(Val0) ||
3167 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3168 ParseGlobalTypeAndValue(Val1) ||
3169 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3170 return true;
3171 if (Val0->getType() != Val1->getType())
3172 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003173 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003174 return Error(ID.Loc,
3175 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003176 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003177 ID.Kind = ValID::t_Constant;
3178 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003179 }
3180
Chris Lattnerac161bf2009-01-02 07:01:27 +00003181 case lltok::kw_getelementptr:
3182 case lltok::kw_shufflevector:
3183 case lltok::kw_insertelement:
3184 case lltok::kw_extractelement:
3185 case lltok::kw_select: {
3186 unsigned Opc = Lex.getUIntVal();
3187 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003188 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003189 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003190 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003191
Dan Gohman1639c392009-07-27 21:53:46 +00003192 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003193 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003194
3195 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3196 return true;
3197
3198 LocTy ExplicitTypeLoc = Lex.getLoc();
3199 if (Opc == Instruction::GetElementPtr) {
3200 if (ParseType(Ty) ||
3201 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3202 return true;
3203 }
3204
Peter Collingbourned93620b2016-11-10 22:34:55 +00003205 Optional<unsigned> InRangeOp;
3206 if (ParseGlobalValueVector(
3207 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003208 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3209 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003210
Chris Lattnerac161bf2009-01-02 07:01:27 +00003211 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003212 if (Elts.size() == 0 ||
3213 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003214 return Error(ID.Loc, "base of getelementptr must be a pointer");
3215
3216 Type *BaseType = Elts[0]->getType();
3217 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003218 if (Ty != BasePointerType->getElementType())
3219 return Error(
3220 ExplicitTypeLoc,
3221 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003222
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003223 unsigned GEPWidth =
3224 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3225
Jay Foaded8db7d2011-07-21 14:31:17 +00003226 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003227 for (Constant *Val : Indices) {
3228 Type *ValTy = Val->getType();
3229 if (!ValTy->getScalarType()->isIntegerTy())
3230 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003231 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003232 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003233 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003234 return Error(
3235 ID.Loc,
3236 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003237 // GEPWidth may have been unknown because the base is a scalar,
3238 // but it is known now.
3239 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003240 }
3241 }
3242
Craig Toppere3dcce92015-08-01 22:20:21 +00003243 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003244 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003245 return Error(ID.Loc, "base element of getelementptr must be sized");
3246
David Blaikie4a2e73b2015-04-02 18:55:32 +00003247 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003248 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003249
3250 if (InRangeOp) {
3251 if (*InRangeOp == 0)
3252 return Error(ID.Loc,
3253 "inrange keyword may not appear on pointer operand");
3254 --*InRangeOp;
3255 }
3256
3257 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3258 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003259 } else if (Opc == Instruction::Select) {
3260 if (Elts.size() != 3)
3261 return Error(ID.Loc, "expected three operands to select");
3262 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3263 Elts[2]))
3264 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003265 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003266 } else if (Opc == Instruction::ShuffleVector) {
3267 if (Elts.size() != 3)
3268 return Error(ID.Loc, "expected three operands to shufflevector");
3269 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3270 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003271 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003272 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003273 } else if (Opc == Instruction::ExtractElement) {
3274 if (Elts.size() != 2)
3275 return Error(ID.Loc, "expected two operands to extractelement");
3276 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3277 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003278 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003279 } else {
3280 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3281 if (Elts.size() != 3)
3282 return Error(ID.Loc, "expected three operands to insertelement");
3283 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3284 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003285 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003286 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003287 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003288
Chris Lattnerac161bf2009-01-02 07:01:27 +00003289 ID.Kind = ValID::t_Constant;
3290 return false;
3291 }
3292 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003293
Chris Lattnerac161bf2009-01-02 07:01:27 +00003294 Lex.Lex();
3295 return false;
3296}
3297
3298/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003299bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003300 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003301 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003302 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003303 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003304 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003305 if (V && !(C = dyn_cast<Constant>(V)))
3306 return Error(ID.Loc, "global values must be constants");
3307 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003308}
3309
Victor Hernandez9d75c962010-01-11 22:31:58 +00003310bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003311 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003312 return ParseType(Ty) ||
3313 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003314}
3315
Rafael Espindola83a362c2015-01-06 22:55:16 +00003316bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003317 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003318
3319 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003320 if (!EatIfPresent(lltok::kw_comdat))
3321 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003322
3323 if (EatIfPresent(lltok::lparen)) {
3324 if (Lex.getKind() != lltok::ComdatVar)
3325 return TokError("expected comdat variable");
3326 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3327 Lex.Lex();
3328 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3329 return true;
3330 } else {
3331 if (GlobalName.empty())
3332 return TokError("comdat cannot be unnamed");
3333 C = getComdat(GlobalName, KwLoc);
3334 }
3335
David Majnemerdad0a642014-06-27 18:19:56 +00003336 return false;
3337}
3338
Victor Hernandez9d75c962010-01-11 22:31:58 +00003339/// ParseGlobalValueVector
3340/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003341/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3342bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3343 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003344 // Empty list.
3345 if (Lex.getKind() == lltok::rbrace ||
3346 Lex.getKind() == lltok::rsquare ||
3347 Lex.getKind() == lltok::greater ||
3348 Lex.getKind() == lltok::rparen)
3349 return false;
3350
Peter Collingbourned93620b2016-11-10 22:34:55 +00003351 do {
3352 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3353 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003354
Peter Collingbourned93620b2016-11-10 22:34:55 +00003355 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003356 if (ParseGlobalTypeAndValue(C)) return true;
3357 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003358 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003359
3360 return false;
3361}
3362
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003363bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003364 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003365 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003366 return true;
3367
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003368 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003369 return false;
3370}
3371
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003372/// MDNode:
3373/// ::= !{ ... }
3374/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003375/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003376bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003377 if (Lex.getKind() == lltok::MetadataVar)
3378 return ParseSpecializedMDNode(N);
3379
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003380 return ParseToken(lltok::exclaim, "expected '!' here") ||
3381 ParseMDNodeTail(N);
3382}
3383
3384bool LLParser::ParseMDNodeTail(MDNode *&N) {
3385 // !{ ... }
3386 if (Lex.getKind() == lltok::lbrace)
3387 return ParseMDTuple(N);
3388
3389 // !42
3390 return ParseMDNodeID(N);
3391}
3392
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003393namespace {
3394
3395/// Structure to represent an optional metadata field.
3396template <class FieldTy> struct MDFieldImpl {
3397 typedef MDFieldImpl ImplTy;
3398 FieldTy Val;
3399 bool Seen;
3400
3401 void assign(FieldTy Val) {
3402 Seen = true;
3403 this->Val = std::move(Val);
3404 }
3405
3406 explicit MDFieldImpl(FieldTy Default)
3407 : Val(std::move(Default)), Seen(false) {}
3408};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003409
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003410struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3411 uint64_t Max;
3412
3413 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3414 : ImplTy(Default), Max(Max) {}
3415};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003416
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003417struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003418 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003419};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003420
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003421struct ColumnField : public MDUnsignedField {
3422 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3423};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003424
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003425struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003426 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003427 DwarfTagField(dwarf::Tag DefaultTag)
3428 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003429};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003430
Amjad Abouda9bcf162015-12-10 12:56:35 +00003431struct DwarfMacinfoTypeField : public MDUnsignedField {
3432 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3433 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3434 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3435};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003436
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003437struct DwarfAttEncodingField : public MDUnsignedField {
3438 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3439};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003440
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003441struct DwarfVirtualityField : public MDUnsignedField {
3442 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3443};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003444
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003445struct DwarfLangField : public MDUnsignedField {
3446 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3447};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003448
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003449struct DwarfCCField : public MDUnsignedField {
3450 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3451};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003452
Adrian Prantlb939a252016-03-31 23:56:58 +00003453struct EmissionKindField : public MDUnsignedField {
3454 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3455};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003456
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003457struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3458 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003459};
3460
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003461struct MDSignedField : public MDFieldImpl<int64_t> {
3462 int64_t Min;
3463 int64_t Max;
3464
3465 MDSignedField(int64_t Default = 0)
3466 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3467 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3468 : ImplTy(Default), Min(Min), Max(Max) {}
3469};
3470
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003471struct MDBoolField : public MDFieldImpl<bool> {
3472 MDBoolField(bool Default = false) : ImplTy(Default) {}
3473};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003474
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003475struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003476 bool AllowNull;
3477
3478 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003479};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003480
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003481struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3482 MDConstant() : ImplTy(nullptr) {}
3483};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003484
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003485struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003486 bool AllowEmpty;
3487 MDStringField(bool AllowEmpty = true)
3488 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003489};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003490
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003491struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3492 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3493};
3494
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003495struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3496 ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3497 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3498};
3499
Eugene Zelenko1804a772016-08-25 00:45:04 +00003500} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003501
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003502namespace llvm {
3503
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003504template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003505bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003506 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003507 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3508 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003509
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003510 auto &U = Lex.getAPSIntVal();
3511 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003512 return TokError("value for '" + Name + "' too large, limit is " +
3513 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003514 Result.assign(U.getZExtValue());
3515 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003516 Lex.Lex();
3517 return false;
3518}
3519
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003520template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003521bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3522 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3523}
3524template <>
3525bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3526 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3527}
3528
3529template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003530bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3531 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003532 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003533
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003534 if (Lex.getKind() != lltok::DwarfTag)
3535 return TokError("expected DWARF tag");
3536
3537 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3538 if (Tag == dwarf::DW_TAG_invalid)
3539 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003540 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003541
3542 Result.assign(Tag);
3543 Lex.Lex();
3544 return false;
3545}
3546
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003547template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003548bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003549 DwarfMacinfoTypeField &Result) {
3550 if (Lex.getKind() == lltok::APSInt)
3551 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3552
3553 if (Lex.getKind() != lltok::DwarfMacinfo)
3554 return TokError("expected DWARF macinfo type");
3555
3556 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3557 if (Macinfo == dwarf::DW_MACINFO_invalid)
3558 return TokError(
3559 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3560 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3561
3562 Result.assign(Macinfo);
3563 Lex.Lex();
3564 return false;
3565}
3566
3567template <>
3568bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003569 DwarfVirtualityField &Result) {
3570 if (Lex.getKind() == lltok::APSInt)
3571 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3572
3573 if (Lex.getKind() != lltok::DwarfVirtuality)
3574 return TokError("expected DWARF virtuality code");
3575
3576 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003577 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003578 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3579 Lex.getStrVal() + "'");
3580 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3581 Result.assign(Virtuality);
3582 Lex.Lex();
3583 return false;
3584}
3585
3586template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003587bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3588 if (Lex.getKind() == lltok::APSInt)
3589 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3590
3591 if (Lex.getKind() != lltok::DwarfLang)
3592 return TokError("expected DWARF language");
3593
3594 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3595 if (!Lang)
3596 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3597 "'");
3598 assert(Lang <= Result.Max && "Expected valid DWARF language");
3599 Result.assign(Lang);
3600 Lex.Lex();
3601 return false;
3602}
3603
3604template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003605bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3606 if (Lex.getKind() == lltok::APSInt)
3607 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3608
3609 if (Lex.getKind() != lltok::DwarfCC)
3610 return TokError("expected DWARF calling convention");
3611
3612 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3613 if (!CC)
3614 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3615 "'");
3616 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3617 Result.assign(CC);
3618 Lex.Lex();
3619 return false;
3620}
3621
3622template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003623bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3624 if (Lex.getKind() == lltok::APSInt)
3625 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3626
3627 if (Lex.getKind() != lltok::EmissionKind)
3628 return TokError("expected emission kind");
3629
3630 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3631 if (!Kind)
3632 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3633 "'");
3634 assert(*Kind <= Result.Max && "Expected valid emission kind");
3635 Result.assign(*Kind);
3636 Lex.Lex();
3637 return false;
3638}
3639
3640template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003641bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003642 DwarfAttEncodingField &Result) {
3643 if (Lex.getKind() == lltok::APSInt)
3644 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3645
3646 if (Lex.getKind() != lltok::DwarfAttEncoding)
3647 return TokError("expected DWARF type attribute encoding");
3648
3649 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3650 if (!Encoding)
3651 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3652 Lex.getStrVal() + "'");
3653 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3654 Result.assign(Encoding);
3655 Lex.Lex();
3656 return false;
3657}
3658
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003659/// DIFlagField
3660/// ::= uint32
3661/// ::= DIFlagVector
3662/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3663template <>
3664bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003665
3666 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003667 auto parseFlag = [&](DINode::DIFlags &Val) {
3668 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3669 uint32_t TempVal = static_cast<uint32_t>(Val);
3670 bool Res = ParseUInt32(TempVal);
3671 Val = static_cast<DINode::DIFlags>(TempVal);
3672 return Res;
3673 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003674
3675 if (Lex.getKind() != lltok::DIFlag)
3676 return TokError("expected debug info flag");
3677
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003678 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003679 if (!Val)
3680 return TokError(Twine("invalid debug info flag flag '") +
3681 Lex.getStrVal() + "'");
3682 Lex.Lex();
3683 return false;
3684 };
3685
3686 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003687 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003688 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003689 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003690 if (parseFlag(Val))
3691 return true;
3692 Combined |= Val;
3693 } while (EatIfPresent(lltok::bar));
3694
3695 Result.assign(Combined);
3696 return false;
3697}
3698
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003699template <>
3700bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003701 MDSignedField &Result) {
3702 if (Lex.getKind() != lltok::APSInt)
3703 return TokError("expected signed integer");
3704
3705 auto &S = Lex.getAPSIntVal();
3706 if (S < Result.Min)
3707 return TokError("value for '" + Name + "' too small, limit is " +
3708 Twine(Result.Min));
3709 if (S > Result.Max)
3710 return TokError("value for '" + Name + "' too large, limit is " +
3711 Twine(Result.Max));
3712 Result.assign(S.getExtValue());
3713 assert(Result.Val >= Result.Min && "Expected value in range");
3714 assert(Result.Val <= Result.Max && "Expected value in range");
3715 Lex.Lex();
3716 return false;
3717}
3718
3719template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003720bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3721 switch (Lex.getKind()) {
3722 default:
3723 return TokError("expected 'true' or 'false'");
3724 case lltok::kw_true:
3725 Result.assign(true);
3726 break;
3727 case lltok::kw_false:
3728 Result.assign(false);
3729 break;
3730 }
3731 Lex.Lex();
3732 return false;
3733}
3734
3735template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003736bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003737 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003738 if (!Result.AllowNull)
3739 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003740 Lex.Lex();
3741 Result.assign(nullptr);
3742 return false;
3743 }
3744
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003745 Metadata *MD;
3746 if (ParseMetadata(MD, nullptr))
3747 return true;
3748
3749 Result.assign(MD);
3750 return false;
3751}
3752
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003753template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003754bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003755 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003756 std::string S;
3757 if (ParseStringConstant(S))
3758 return true;
3759
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003760 if (!Result.AllowEmpty && S.empty())
3761 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3762
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003763 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003764 return false;
3765}
3766
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003767template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003768bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3769 SmallVector<Metadata *, 4> MDs;
3770 if (ParseMDNodeVector(MDs))
3771 return true;
3772
3773 Result.assign(std::move(MDs));
3774 return false;
3775}
3776
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003777template <>
3778bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3779 ChecksumKindField &Result) {
3780 if (Lex.getKind() != lltok::ChecksumKind)
3781 return TokError(
3782 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3783
3784 DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3785
3786 Result.assign(CSKind);
3787 Lex.Lex();
3788 return false;
3789}
3790
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003791} // end namespace llvm
3792
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003793template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003794bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003795 do {
3796 if (Lex.getKind() != lltok::LabelStr)
3797 return TokError("expected field label here");
3798
3799 if (parseField())
3800 return true;
3801 } while (EatIfPresent(lltok::comma));
3802
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003803 return false;
3804}
3805
3806template <class ParserTy>
3807bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3808 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3809 Lex.Lex();
3810
3811 if (ParseToken(lltok::lparen, "expected '(' here"))
3812 return true;
3813 if (Lex.getKind() != lltok::rparen)
3814 if (ParseMDFieldsImplBody(parseField))
3815 return true;
3816
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003817 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003818 return ParseToken(lltok::rparen, "expected ')' here");
3819}
3820
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003821template <class FieldTy>
3822bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3823 if (Result.Seen)
3824 return TokError("field '" + Name + "' cannot be specified more than once");
3825
3826 LocTy Loc = Lex.getLoc();
3827 Lex.Lex();
3828 return ParseMDField(Loc, Name, Result);
3829}
3830
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003831bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3832 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003833
3834#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003835 if (Lex.getStrVal() == #CLASS) \
3836 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003837#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003838
3839 return TokError("expected metadata type");
3840}
3841
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003842#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3843#define NOP_FIELD(NAME, TYPE, INIT)
3844#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3845 if (!NAME.Seen) \
3846 return Error(ClosingLoc, "missing required field '" #NAME "'");
3847#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003848 if (Lex.getStrVal() == #NAME) \
3849 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003850#define PARSE_MD_FIELDS() \
3851 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3852 do { \
3853 LocTy ClosingLoc; \
3854 if (ParseMDFieldsImpl([&]() -> bool { \
3855 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3856 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3857 }, ClosingLoc)) \
3858 return true; \
3859 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3860 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003861#define GET_OR_DISTINCT(CLASS, ARGS) \
3862 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003863
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003864/// ParseDILocationFields:
3865/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3866bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003867#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003868 OPTIONAL(line, LineField, ); \
3869 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003870 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003871 OPTIONAL(inlinedAt, MDField, );
3872 PARSE_MD_FIELDS();
3873#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003874
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003875 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003876 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003877 return false;
3878}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003879
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003880/// ParseGenericDINode:
3881/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3882bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003883#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003884 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003885 OPTIONAL(header, MDStringField, ); \
3886 OPTIONAL(operands, MDFieldList, );
3887 PARSE_MD_FIELDS();
3888#undef VISIT_MD_FIELDS
3889
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003890 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003891 (Context, tag.Val, header.Val, operands.Val));
3892 return false;
3893}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003894
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003895/// ParseDISubrange:
3896/// ::= !DISubrange(count: 30, lowerBound: 2)
3897bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003898#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003899 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003900 OPTIONAL(lowerBound, MDSignedField, );
3901 PARSE_MD_FIELDS();
3902#undef VISIT_MD_FIELDS
3903
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003904 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003905 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003906}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003907
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003908/// ParseDIEnumerator:
3909/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3910bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003911#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003912 REQUIRED(name, MDStringField, ); \
3913 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003914 PARSE_MD_FIELDS();
3915#undef VISIT_MD_FIELDS
3916
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003917 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003918 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003919}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003920
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003921/// ParseDIBasicType:
3922/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3923bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003924#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003925 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003926 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003927 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003928 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003929 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003930 PARSE_MD_FIELDS();
3931#undef VISIT_MD_FIELDS
3932
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003933 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003934 align.Val, encoding.Val));
3935 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003936}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003937
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003938/// ParseDIDerivedType:
3939/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003940/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003941/// align: 32, offset: 0, flags: 0, extraData: !3,
3942/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003943bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003944#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3945 REQUIRED(tag, DwarfTagField, ); \
3946 OPTIONAL(name, MDStringField, ); \
3947 OPTIONAL(file, MDField, ); \
3948 OPTIONAL(line, LineField, ); \
3949 OPTIONAL(scope, MDField, ); \
3950 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003951 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003952 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003953 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003954 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003955 OPTIONAL(extraData, MDField, ); \
3956 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003957 PARSE_MD_FIELDS();
3958#undef VISIT_MD_FIELDS
3959
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003960 Optional<unsigned> DWARFAddressSpace;
3961 if (dwarfAddressSpace.Val != UINT32_MAX)
3962 DWARFAddressSpace = dwarfAddressSpace.Val;
3963
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003964 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003965 (Context, tag.Val, name.Val, file.Val, line.Val,
3966 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003967 offset.Val, DWARFAddressSpace, flags.Val,
3968 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003969 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003970}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003971
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003972bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003973#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3974 REQUIRED(tag, DwarfTagField, ); \
3975 OPTIONAL(name, MDStringField, ); \
3976 OPTIONAL(file, MDField, ); \
3977 OPTIONAL(line, LineField, ); \
3978 OPTIONAL(scope, MDField, ); \
3979 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003980 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003981 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003982 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003983 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003984 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003985 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003986 OPTIONAL(vtableHolder, MDField, ); \
3987 OPTIONAL(templateParams, MDField, ); \
3988 OPTIONAL(identifier, MDStringField, );
3989 PARSE_MD_FIELDS();
3990#undef VISIT_MD_FIELDS
3991
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00003992 // If this has an identifier try to build an ODR type.
3993 if (identifier.Val)
3994 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00003995 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3996 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3997 elements.Val, runtimeLang.Val, vtableHolder.Val,
3998 templateParams.Val)) {
3999 Result = CT;
4000 return false;
4001 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00004002
4003 // Create a new node, and save it in the context if it belongs in the type
4004 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004005 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004006 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004007 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4008 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4009 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
4010 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004011}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004012
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004013bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004014#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004015 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004016 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004017 REQUIRED(types, MDField, );
4018 PARSE_MD_FIELDS();
4019#undef VISIT_MD_FIELDS
4020
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004021 Result = GET_OR_DISTINCT(DISubroutineType,
4022 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004023 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004024}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004025
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004026/// ParseDIFileType:
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004027/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
4028/// checksumkind: CSK_MD5,
4029/// checksum: "000102030405060708090a0b0c0d0e0f")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004030bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004031#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4032 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004033 REQUIRED(directory, MDStringField, ); \
4034 OPTIONAL(checksumkind, ChecksumKindField, ); \
4035 OPTIONAL(checksum, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004036 PARSE_MD_FIELDS();
4037#undef VISIT_MD_FIELDS
4038
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004039 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4040 checksumkind.Val, checksum.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004041 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004042}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004043
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004044/// ParseDICompileUnit:
4045/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004046/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004047/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004048/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004049/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004050bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004051 if (!IsDistinct)
4052 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4053
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004054#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4055 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004056 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004057 OPTIONAL(producer, MDStringField, ); \
4058 OPTIONAL(isOptimized, MDBoolField, ); \
4059 OPTIONAL(flags, MDStringField, ); \
4060 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4061 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004062 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004063 OPTIONAL(enums, MDField, ); \
4064 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004065 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004066 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004067 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004068 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004069 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4070 OPTIONAL(debugInfoForProfiling, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004071 PARSE_MD_FIELDS();
4072#undef VISIT_MD_FIELDS
4073
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004074 Result = DICompileUnit::getDistinct(
4075 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4076 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004077 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
Dehao Chen0944a8c2017-02-01 22:45:09 +00004078 splitDebugInlining.Val, debugInfoForProfiling.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004079 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004080}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004081
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004082/// ParseDISubprogram:
4083/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004084/// file: !1, line: 7, type: !2, isLocal: false,
4085/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004086/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004087/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004088/// isOptimized: false, templateParams: !4, declaration: !5,
Adrian Prantl1d12b882017-04-26 22:56:44 +00004089/// variables: !6, thrownTypes: !7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004090bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004091 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004092#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4093 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004094 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004095 OPTIONAL(linkageName, MDStringField, ); \
4096 OPTIONAL(file, MDField, ); \
4097 OPTIONAL(line, LineField, ); \
4098 OPTIONAL(type, MDField, ); \
4099 OPTIONAL(isLocal, MDBoolField, ); \
4100 OPTIONAL(isDefinition, MDBoolField, (true)); \
4101 OPTIONAL(scopeLine, LineField, ); \
4102 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004103 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004104 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004105 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004106 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004107 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004108 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004109 OPTIONAL(templateParams, MDField, ); \
4110 OPTIONAL(declaration, MDField, ); \
Adrian Prantl1d12b882017-04-26 22:56:44 +00004111 OPTIONAL(variables, MDField, ); \
4112 OPTIONAL(thrownTypes, MDField, );
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004113 PARSE_MD_FIELDS();
4114#undef VISIT_MD_FIELDS
4115
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004116 if (isDefinition.Val && !IsDistinct)
4117 return Lex.Error(
4118 Loc,
4119 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4120
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004121 Result = GET_OR_DISTINCT(
Adrian Prantl1d12b882017-04-26 22:56:44 +00004122 DISubprogram,
4123 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4124 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4125 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4126 flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
4127 declaration.Val, variables.Val, thrownTypes.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004128 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004129}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004130
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004131/// ParseDILexicalBlock:
4132/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4133bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004134#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004135 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004136 OPTIONAL(file, MDField, ); \
4137 OPTIONAL(line, LineField, ); \
4138 OPTIONAL(column, ColumnField, );
4139 PARSE_MD_FIELDS();
4140#undef VISIT_MD_FIELDS
4141
4142 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004143 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004144 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004145}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004146
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004147/// ParseDILexicalBlockFile:
4148/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4149bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004150#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004151 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004152 OPTIONAL(file, MDField, ); \
4153 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4154 PARSE_MD_FIELDS();
4155#undef VISIT_MD_FIELDS
4156
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004157 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004158 (Context, scope.Val, file.Val, discriminator.Val));
4159 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004160}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004161
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004162/// ParseDINamespace:
4163/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4164bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004165#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4166 REQUIRED(scope, MDField, ); \
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004167 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004168 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004169 PARSE_MD_FIELDS();
4170#undef VISIT_MD_FIELDS
4171
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004172 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantlfed4f392017-04-28 22:25:46 +00004173 (Context, scope.Val, name.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004174 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004175}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004176
Amjad Abouda9bcf162015-12-10 12:56:35 +00004177/// ParseDIMacro:
4178/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4179bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4180#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4181 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004182 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004183 REQUIRED(name, MDStringField, ); \
4184 OPTIONAL(value, MDStringField, );
4185 PARSE_MD_FIELDS();
4186#undef VISIT_MD_FIELDS
4187
4188 Result = GET_OR_DISTINCT(DIMacro,
4189 (Context, type.Val, line.Val, name.Val, value.Val));
4190 return false;
4191}
4192
4193/// ParseDIMacroFile:
4194/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4195bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4196#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4197 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004198 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004199 REQUIRED(file, MDField, ); \
4200 OPTIONAL(nodes, MDField, );
4201 PARSE_MD_FIELDS();
4202#undef VISIT_MD_FIELDS
4203
4204 Result = GET_OR_DISTINCT(DIMacroFile,
4205 (Context, type.Val, line.Val, file.Val, nodes.Val));
4206 return false;
4207}
4208
Adrian Prantlab1243f2015-06-29 23:03:47 +00004209/// ParseDIModule:
4210/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4211/// includePath: "/usr/include", isysroot: "/")
4212bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4213#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4214 REQUIRED(scope, MDField, ); \
4215 REQUIRED(name, MDStringField, ); \
4216 OPTIONAL(configMacros, MDStringField, ); \
4217 OPTIONAL(includePath, MDStringField, ); \
4218 OPTIONAL(isysroot, MDStringField, );
4219 PARSE_MD_FIELDS();
4220#undef VISIT_MD_FIELDS
4221
4222 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4223 configMacros.Val, includePath.Val, isysroot.Val));
4224 return false;
4225}
4226
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004227/// ParseDITemplateTypeParameter:
4228/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4229bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004230#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004231 OPTIONAL(name, MDStringField, ); \
4232 REQUIRED(type, MDField, );
4233 PARSE_MD_FIELDS();
4234#undef VISIT_MD_FIELDS
4235
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004236 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004237 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004238 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004239}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004240
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004241/// ParseDITemplateValueParameter:
4242/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004243/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004244bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004245#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004246 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004247 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004248 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004249 REQUIRED(value, MDField, );
4250 PARSE_MD_FIELDS();
4251#undef VISIT_MD_FIELDS
4252
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004253 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004254 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004255 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004256}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004257
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004258/// ParseDIGlobalVariable:
4259/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004260/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004261/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004262bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004263#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004264 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004265 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004266 OPTIONAL(linkageName, MDStringField, ); \
4267 OPTIONAL(file, MDField, ); \
4268 OPTIONAL(line, LineField, ); \
4269 OPTIONAL(type, MDField, ); \
4270 OPTIONAL(isLocal, MDBoolField, ); \
4271 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004272 OPTIONAL(declaration, MDField, ); \
4273 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004274 PARSE_MD_FIELDS();
4275#undef VISIT_MD_FIELDS
4276
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004277 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004278 (Context, scope.Val, name.Val, linkageName.Val,
4279 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004280 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004281 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004282}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004283
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004284/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004285/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004286/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4287/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004288/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004289/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4290/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004291bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004292#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004293 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004294 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004295 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004296 OPTIONAL(file, MDField, ); \
4297 OPTIONAL(line, LineField, ); \
4298 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004299 OPTIONAL(flags, DIFlagField, ); \
4300 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004301 PARSE_MD_FIELDS();
4302#undef VISIT_MD_FIELDS
4303
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004304 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004305 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004306 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004307 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004308}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004309
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004310/// ParseDIExpression:
4311/// ::= !DIExpression(0, 7, -1)
4312bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004313 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4314 Lex.Lex();
4315
4316 if (ParseToken(lltok::lparen, "expected '(' here"))
4317 return true;
4318
4319 SmallVector<uint64_t, 8> Elements;
4320 if (Lex.getKind() != lltok::rparen)
4321 do {
4322 if (Lex.getKind() == lltok::DwarfOp) {
4323 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4324 Lex.Lex();
4325 Elements.push_back(Op);
4326 continue;
4327 }
4328 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4329 }
4330
4331 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4332 return TokError("expected unsigned integer");
4333
4334 auto &U = Lex.getAPSIntVal();
4335 if (U.ugt(UINT64_MAX))
4336 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4337 Elements.push_back(U.getZExtValue());
4338 Lex.Lex();
4339 } while (EatIfPresent(lltok::comma));
4340
4341 if (ParseToken(lltok::rparen, "expected ')' here"))
4342 return true;
4343
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004344 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004345 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004346}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004347
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004348/// ParseDIGlobalVariableExpression:
4349/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4350bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4351 bool IsDistinct) {
4352#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4353 REQUIRED(var, MDField, ); \
4354 OPTIONAL(expr, MDField, );
4355 PARSE_MD_FIELDS();
4356#undef VISIT_MD_FIELDS
4357
4358 Result =
4359 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4360 return false;
4361}
4362
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004363/// ParseDIObjCProperty:
4364/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004365/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004366bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004367#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004368 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004369 OPTIONAL(file, MDField, ); \
4370 OPTIONAL(line, LineField, ); \
4371 OPTIONAL(setter, MDStringField, ); \
4372 OPTIONAL(getter, MDStringField, ); \
4373 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4374 OPTIONAL(type, MDField, );
4375 PARSE_MD_FIELDS();
4376#undef VISIT_MD_FIELDS
4377
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004378 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004379 (Context, name.Val, file.Val, line.Val, setter.Val,
4380 getter.Val, attributes.Val, type.Val));
4381 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004382}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004383
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004384/// ParseDIImportedEntity:
4385/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004386/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004387bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004388#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4389 REQUIRED(tag, DwarfTagField, ); \
4390 REQUIRED(scope, MDField, ); \
4391 OPTIONAL(entity, MDField, ); \
4392 OPTIONAL(line, LineField, ); \
4393 OPTIONAL(name, MDStringField, );
4394 PARSE_MD_FIELDS();
4395#undef VISIT_MD_FIELDS
4396
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004397 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004398 entity.Val, line.Val, name.Val));
4399 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004400}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004401
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004402#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004403#undef NOP_FIELD
4404#undef REQUIRE_FIELD
4405#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004406
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004407/// ParseMetadataAsValue
4408/// ::= metadata i32 %local
4409/// ::= metadata i32 @global
4410/// ::= metadata i32 7
4411/// ::= metadata !0
4412/// ::= metadata !{...}
4413/// ::= metadata !"string"
4414bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4415 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004416 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004417 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004418 return true;
4419
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004420 V = MetadataAsValue::get(Context, MD);
4421 return false;
4422}
4423
4424/// ParseValueAsMetadata
4425/// ::= i32 %local
4426/// ::= i32 @global
4427/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004428bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4429 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004430 Type *Ty;
4431 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004432 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004433 return true;
4434 if (Ty->isMetadataTy())
4435 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4436
4437 Value *V;
4438 if (ParseValue(Ty, V, PFS))
4439 return true;
4440
4441 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004442 return false;
4443}
4444
4445/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004446/// ::= i32 %local
4447/// ::= i32 @global
4448/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004449/// ::= !42
4450/// ::= !{...}
4451/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004452/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004453bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004454 if (Lex.getKind() == lltok::MetadataVar) {
4455 MDNode *N;
4456 if (ParseSpecializedMDNode(N))
4457 return true;
4458 MD = N;
4459 return false;
4460 }
4461
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004462 // ValueAsMetadata:
4463 // <type> <value>
4464 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004465 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004466
4467 // '!'.
4468 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4469 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004470
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004471 // MDString:
4472 // ::= '!' STRINGCONSTANT
4473 if (Lex.getKind() == lltok::StringConstant) {
4474 MDString *S;
4475 if (ParseMDString(S))
4476 return true;
4477 MD = S;
4478 return false;
4479 }
4480
Dan Gohman8939ba332010-07-14 18:26:50 +00004481 // MDNode:
4482 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004483 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004484 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004485 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004486 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004487 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004488 return false;
4489}
4490
Victor Hernandez9d75c962010-01-11 22:31:58 +00004491//===----------------------------------------------------------------------===//
4492// Function Parsing.
4493//===----------------------------------------------------------------------===//
4494
Chris Lattner229907c2011-07-18 04:54:35 +00004495bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004496 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004497 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004498 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004499
Chris Lattnerac161bf2009-01-02 07:01:27 +00004500 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004501 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004502 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004503 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004504 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004505 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004506 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004507 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004508 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004509 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004510 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004511 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004512 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4513 (ID.UIntVal >> 1) & 1,
4514 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004515 return false;
4516 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004517 case ValID::t_GlobalName:
4518 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004519 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004520 case ValID::t_GlobalID:
4521 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004522 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004523 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004524 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004525 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004526 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004527 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004528 return false;
4529 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004530 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004531 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4532 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004533
Dan Gohman518cda42011-12-17 00:04:22 +00004534 // The lexer has no type info, so builds all half, float, and double FP
4535 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004536 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004537 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004538 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004539 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004540 &Ignored);
4541 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004542 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004543 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004544 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004545 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004546
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004547 if (V->getType() != Ty)
4548 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004549 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004550
Chris Lattnerac161bf2009-01-02 07:01:27 +00004551 return false;
4552 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004553 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004554 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004555 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004556 return false;
4557 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004558 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004559 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004560 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004561 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004562 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004563 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004564 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004565 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004566 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004567 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004568 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004569 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004570 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004571 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004572 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004573 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004574 case ValID::t_None:
4575 if (!Ty->isTokenTy())
4576 return Error(ID.Loc, "invalid type for none constant");
4577 V = Constant::getNullValue(Ty);
4578 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004579 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004580 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004581 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004582
Chris Lattnerac161bf2009-01-02 07:01:27 +00004583 V = ID.ConstantVal;
4584 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004585 case ValID::t_ConstantStruct:
4586 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004587 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004588 if (ST->getNumElements() != ID.UIntVal)
4589 return Error(ID.Loc,
4590 "initializer with struct type has wrong # elements");
4591 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4592 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004593
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004594 // Verify that the elements are compatible with the structtype.
4595 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4596 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4597 return Error(ID.Loc, "element " + Twine(i) +
4598 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004599
David Blaikieadbda4b2015-08-03 20:08:41 +00004600 V = ConstantStruct::get(
4601 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004602 } else
4603 return Error(ID.Loc, "constant expression type mismatch");
4604 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004605 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004606 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004607}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004608
Alex Lorenzd2255952015-07-17 22:07:03 +00004609bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4610 C = nullptr;
4611 ValID ID;
4612 auto Loc = Lex.getLoc();
4613 if (ParseValID(ID, /*PFS=*/nullptr))
4614 return true;
4615 switch (ID.Kind) {
4616 case ValID::t_APSInt:
4617 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004618 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004619 case ValID::t_Constant:
4620 case ValID::t_ConstantStruct:
4621 case ValID::t_PackedConstantStruct: {
4622 Value *V;
4623 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4624 return true;
4625 assert(isa<Constant>(V) && "Expected a constant value");
4626 C = cast<Constant>(V);
4627 return false;
4628 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00004629 case ValID::t_Null:
4630 C = Constant::getNullValue(Ty);
4631 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00004632 default:
4633 return Error(Loc, "expected a constant value");
4634 }
4635}
4636
David Majnemer8a1c45d2015-12-12 05:38:55 +00004637bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004638 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004639 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004640 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004641}
4642
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004643bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004644 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004645 return ParseType(Ty) ||
4646 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004647}
4648
Chris Lattner3ed871f2009-10-27 19:13:16 +00004649bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4650 PerFunctionState &PFS) {
4651 Value *V;
4652 Loc = Lex.getLoc();
4653 if (ParseTypeAndValue(V, PFS)) return true;
4654 if (!isa<BasicBlock>(V))
4655 return Error(Loc, "expected a basic block");
4656 BB = cast<BasicBlock>(V);
4657 return false;
4658}
4659
Chris Lattnerac161bf2009-01-02 07:01:27 +00004660/// FunctionHeader
4661/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004662/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004663/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004664bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4665 // Parse the linkage.
4666 LocTy LinkageLoc = Lex.getLoc();
4667 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004668
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004669 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004670 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004671 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004672 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004673 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004674 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004675 LocTy RetTypeLoc = Lex.getLoc();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004676 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4677 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004678 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004679 return true;
4680
4681 // Verify that the linkage is ok.
4682 switch ((GlobalValue::LinkageTypes)Linkage) {
4683 case GlobalValue::ExternalLinkage:
4684 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004685 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004686 if (isDefine)
4687 return Error(LinkageLoc, "invalid linkage for function definition");
4688 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004689 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004690 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004691 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004692 case GlobalValue::LinkOnceAnyLinkage:
4693 case GlobalValue::LinkOnceODRLinkage:
4694 case GlobalValue::WeakAnyLinkage:
4695 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004696 if (!isDefine)
4697 return Error(LinkageLoc, "invalid linkage for function declaration");
4698 break;
4699 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004700 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004701 return Error(LinkageLoc, "invalid function linkage type");
4702 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004703
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004704 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4705 return Error(LinkageLoc,
4706 "symbol with local linkage must have default visibility");
4707
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004708 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004709 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004710
Chris Lattnerac161bf2009-01-02 07:01:27 +00004711 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004712
4713 std::string FunctionName;
4714 if (Lex.getKind() == lltok::GlobalVar) {
4715 FunctionName = Lex.getStrVal();
4716 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4717 unsigned NameID = Lex.getUIntVal();
4718
4719 if (NameID != NumberedVals.size())
4720 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004721 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004722 } else {
4723 return TokError("expected function name");
4724 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004725
Chris Lattner3822f632009-01-02 08:05:26 +00004726 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004727
Chris Lattner3822f632009-01-02 08:05:26 +00004728 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004729 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004730
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004731 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004732 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004733 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004734 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004735 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004736 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004737 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004738 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004739 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004740 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004741 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004742 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004743 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004744 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004745
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004746 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004747 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004748 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004749 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004750 (EatIfPresent(lltok::kw_section) &&
4751 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004752 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004753 ParseOptionalAlignment(Alignment) ||
4754 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004755 ParseStringConstant(GC)) ||
4756 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004757 ParseGlobalTypeAndValue(Prefix)) ||
4758 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004759 ParseGlobalTypeAndValue(Prologue)) ||
4760 (EatIfPresent(lltok::kw_personality) &&
4761 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004762 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004763
Michael Gottesman41748d72013-06-27 00:25:01 +00004764 if (FuncAttrs.contains(Attribute::Builtin))
4765 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004766
Chris Lattnerac161bf2009-01-02 07:01:27 +00004767 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004768 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004769 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004770 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004771 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004772
Chris Lattnerac161bf2009-01-02 07:01:27 +00004773 // Okay, if we got here, the function is syntactically valid. Convert types
4774 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004775 std::vector<Type*> ParamTypeList;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004776 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004777
Chris Lattnerac161bf2009-01-02 07:01:27 +00004778 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004779 ParamTypeList.push_back(ArgList[i].Ty);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004780 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004781 }
4782
Reid Kleckner7f720332017-04-13 00:58:09 +00004783 AttributeList PAL =
4784 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
4785 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004786
Bill Wendling749a43d2012-12-30 13:50:49 +00004787 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004788 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4789
Chris Lattner229907c2011-07-18 04:54:35 +00004790 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004791 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004792 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004793
Craig Topper2617dcc2014-04-15 06:32:26 +00004794 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004795 if (!FunctionName.empty()) {
4796 // If this was a definition of a forward reference, remove the definition
4797 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004798 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004799 if (FRVI != ForwardRefVals.end()) {
4800 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004801 if (!Fn)
4802 return Error(FRVI->second.second, "invalid forward reference to "
4803 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004804 if (Fn->getType() != PFT)
4805 return Error(FRVI->second.second, "invalid forward reference to "
4806 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004807
Chris Lattnerac161bf2009-01-02 07:01:27 +00004808 ForwardRefVals.erase(FRVI);
4809 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004810 // Reject redefinitions.
4811 return Error(NameLoc, "invalid redefinition of function '" +
4812 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004813 } else if (M->getNamedValue(FunctionName)) {
4814 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004815 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004816
Dan Gohman399d6ae2009-08-29 23:37:49 +00004817 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004818 // If this is a definition of a forward referenced function, make sure the
4819 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004820 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004821 if (I != ForwardRefValIDs.end()) {
4822 Fn = cast<Function>(I->second.first);
4823 if (Fn->getType() != PFT)
4824 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004825 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004826 ForwardRefValIDs.erase(I);
4827 }
4828 }
4829
Craig Topper2617dcc2014-04-15 06:32:26 +00004830 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004831 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4832 else // Move the forward-reference to the correct spot in the module.
4833 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4834
4835 if (FunctionName.empty())
4836 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004837
Chris Lattnerac161bf2009-01-02 07:01:27 +00004838 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4839 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004840 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004841 Fn->setCallingConv(CC);
4842 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004843 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004844 Fn->setAlignment(Alignment);
4845 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004846 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004847 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00004848 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004849 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004850 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004851 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004852
Chris Lattnerac161bf2009-01-02 07:01:27 +00004853 // Add all of the arguments we parsed to the function.
4854 Function::arg_iterator ArgIt = Fn->arg_begin();
4855 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4856 // If the argument has a name, insert it into the argument symbol table.
4857 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004858
Chris Lattnerac161bf2009-01-02 07:01:27 +00004859 // Set the name, if it conflicted, it will be auto-renamed.
4860 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004861
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004862 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004863 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4864 ArgList[i].Name + "'");
4865 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004866
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004867 if (isDefine)
4868 return false;
4869
Robin Morisset039781e2014-08-29 21:53:01 +00004870 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004871 ValID ID;
4872 if (FunctionName.empty()) {
4873 ID.Kind = ValID::t_GlobalID;
4874 ID.UIntVal = NumberedVals.size() - 1;
4875 } else {
4876 ID.Kind = ValID::t_GlobalName;
4877 ID.StrVal = FunctionName;
4878 }
4879 auto Blocks = ForwardRefBlockAddresses.find(ID);
4880 if (Blocks != ForwardRefBlockAddresses.end())
4881 return Error(Blocks->first.Loc,
4882 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004883 return false;
4884}
4885
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004886bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4887 ValID ID;
4888 if (FunctionNumber == -1) {
4889 ID.Kind = ValID::t_GlobalName;
4890 ID.StrVal = F.getName();
4891 } else {
4892 ID.Kind = ValID::t_GlobalID;
4893 ID.UIntVal = FunctionNumber;
4894 }
4895
4896 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4897 if (Blocks == P.ForwardRefBlockAddresses.end())
4898 return false;
4899
4900 for (const auto &I : Blocks->second) {
4901 const ValID &BBID = I.first;
4902 GlobalValue *GV = I.second;
4903
4904 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4905 "Expected local id or name");
4906 BasicBlock *BB;
4907 if (BBID.Kind == ValID::t_LocalName)
4908 BB = GetBB(BBID.StrVal, BBID.Loc);
4909 else
4910 BB = GetBB(BBID.UIntVal, BBID.Loc);
4911 if (!BB)
4912 return P.Error(BBID.Loc, "referenced value is not a basic block");
4913
4914 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4915 GV->eraseFromParent();
4916 }
4917
4918 P.ForwardRefBlockAddresses.erase(Blocks);
4919 return false;
4920}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004921
4922/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004923/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004924bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004925 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004926 return TokError("expected '{' in function body");
4927 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004928
Chris Lattner3432c622009-10-28 03:39:23 +00004929 int FunctionNumber = -1;
4930 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004931
Chris Lattner3432c622009-10-28 03:39:23 +00004932 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004933
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004934 // Resolve block addresses and allow basic blocks to be forward-declared
4935 // within this function.
4936 if (PFS.resolveForwardRefBlockAddresses())
4937 return true;
4938 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4939
Chris Lattnerbbddd962010-01-09 19:20:07 +00004940 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004941 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004942 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004943
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004944 while (Lex.getKind() != lltok::rbrace &&
4945 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004946 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004947
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004948 while (Lex.getKind() != lltok::rbrace)
4949 if (ParseUseListOrder(&PFS))
4950 return true;
4951
Chris Lattnerac161bf2009-01-02 07:01:27 +00004952 // Eat the }.
4953 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004954
Chris Lattnerac161bf2009-01-02 07:01:27 +00004955 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004956 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004957}
4958
4959/// ParseBasicBlock
4960/// ::= LabelStr? Instruction*
4961bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4962 // If this basic block starts out with a name, remember it.
4963 std::string Name;
4964 LocTy NameLoc = Lex.getLoc();
4965 if (Lex.getKind() == lltok::LabelStr) {
4966 Name = Lex.getStrVal();
4967 Lex.Lex();
4968 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004969
Chris Lattnerac161bf2009-01-02 07:01:27 +00004970 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004971 if (!BB)
4972 return Error(NameLoc,
4973 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004974
Chris Lattnerac161bf2009-01-02 07:01:27 +00004975 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004976
Chris Lattnerac161bf2009-01-02 07:01:27 +00004977 // Parse the instructions in this block until we get a terminator.
4978 Instruction *Inst;
4979 do {
4980 // This instruction may have three possibilities for a name: a) none
4981 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4982 LocTy NameLoc = Lex.getLoc();
4983 int NameID = -1;
4984 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004985
Chris Lattnerac161bf2009-01-02 07:01:27 +00004986 if (Lex.getKind() == lltok::LocalVarID) {
4987 NameID = Lex.getUIntVal();
4988 Lex.Lex();
4989 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4990 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004991 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004992 NameStr = Lex.getStrVal();
4993 Lex.Lex();
4994 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4995 return true;
4996 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004997
Chris Lattner77b89dc2009-12-30 05:23:43 +00004998 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004999 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00005000 case InstError: return true;
5001 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005002 BB->getInstList().push_back(Inst);
5003
Chris Lattner77b89dc2009-12-30 05:23:43 +00005004 // With a normal result, we check to see if the instruction is followed by
5005 // a comma and metadata.
5006 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005007 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005008 return true;
5009 break;
5010 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005011 BB->getInstList().push_back(Inst);
5012
Chris Lattner77b89dc2009-12-30 05:23:43 +00005013 // If the instruction parser ate an extra comma at the end of it, it
5014 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005015 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005016 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005017 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005018 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005019
Chris Lattnerac161bf2009-01-02 07:01:27 +00005020 // Set the name on the instruction.
5021 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5022 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005023
Chris Lattnerac161bf2009-01-02 07:01:27 +00005024 return false;
5025}
5026
5027//===----------------------------------------------------------------------===//
5028// Instruction Parsing.
5029//===----------------------------------------------------------------------===//
5030
5031/// ParseInstruction - Parse one of the many different instructions.
5032///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005033int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5034 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005035 lltok::Kind Token = Lex.getKind();
5036 if (Token == lltok::Eof)
5037 return TokError("found end of file when expecting more instructions");
5038 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005039 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005040 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005041
Chris Lattnerac161bf2009-01-02 07:01:27 +00005042 switch (Token) {
5043 default: return Error(Loc, "expected instruction opcode");
5044 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005045 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005046 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5047 case lltok::kw_br: return ParseBr(Inst, PFS);
5048 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005049 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005050 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005051 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005052 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5053 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005054 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5055 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005056 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005057 // Binary Operators.
5058 case lltok::kw_add:
5059 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005060 case lltok::kw_mul:
5061 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005062 bool NUW = EatIfPresent(lltok::kw_nuw);
5063 bool NSW = EatIfPresent(lltok::kw_nsw);
5064 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005065
Chris Lattnera676c0f2011-02-07 16:40:21 +00005066 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005067
Chris Lattnera676c0f2011-02-07 16:40:21 +00005068 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5069 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5070 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005071 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005072 case lltok::kw_fadd:
5073 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005074 case lltok::kw_fmul:
5075 case lltok::kw_fdiv:
5076 case lltok::kw_frem: {
5077 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5078 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5079 if (Res != 0)
5080 return Res;
5081 if (FMF.any())
5082 Inst->setFastMathFlags(FMF);
5083 return 0;
5084 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005085
Chris Lattner35315d02011-02-06 21:44:57 +00005086 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005087 case lltok::kw_udiv:
5088 case lltok::kw_lshr:
5089 case lltok::kw_ashr: {
5090 bool Exact = EatIfPresent(lltok::kw_exact);
5091
5092 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5093 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5094 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005095 }
5096
Chris Lattnerac161bf2009-01-02 07:01:27 +00005097 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005098 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005099 case lltok::kw_and:
5100 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005101 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005102 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5103 case lltok::kw_fcmp: {
5104 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5105 int Res = ParseCompare(Inst, PFS, KeywordVal);
5106 if (Res != 0)
5107 return Res;
5108 if (FMF.any())
5109 Inst->setFastMathFlags(FMF);
5110 return 0;
5111 }
5112
Chris Lattnerac161bf2009-01-02 07:01:27 +00005113 // Casts.
5114 case lltok::kw_trunc:
5115 case lltok::kw_zext:
5116 case lltok::kw_sext:
5117 case lltok::kw_fptrunc:
5118 case lltok::kw_fpext:
5119 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005120 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005121 case lltok::kw_uitofp:
5122 case lltok::kw_sitofp:
5123 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005124 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005125 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005126 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005127 // Other.
5128 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005129 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005130 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5131 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5132 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5133 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005134 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005135 // Call.
5136 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5137 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5138 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005139 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005140 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005141 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005142 case lltok::kw_load: return ParseLoad(Inst, PFS);
5143 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005144 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5145 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005146 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005147 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5148 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5149 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5150 }
5151}
5152
5153/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5154bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005155 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005156 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005157 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005158 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5159 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5160 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5161 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5162 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5163 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5164 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5165 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5166 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5167 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5168 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5169 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5170 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5171 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5172 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5173 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5174 }
5175 } else {
5176 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005177 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005178 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5179 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5180 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5181 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5182 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5183 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5184 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5185 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5186 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5187 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5188 }
5189 }
5190 Lex.Lex();
5191 return false;
5192}
5193
5194//===----------------------------------------------------------------------===//
5195// Terminator Instructions.
5196//===----------------------------------------------------------------------===//
5197
5198/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005199/// ::= 'ret' void (',' !dbg, !1)*
5200/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005201bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005202 PerFunctionState &PFS) {
5203 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005204 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005205 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005206
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005207 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005208
Chris Lattnerfdd87902009-10-05 05:54:46 +00005209 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005210 if (!ResType->isVoidTy())
5211 return Error(TypeLoc, "value doesn't match function result type '" +
5212 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005213
Owen Anderson55f1c092009-08-13 21:58:54 +00005214 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005215 return false;
5216 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005217
Chris Lattnerac161bf2009-01-02 07:01:27 +00005218 Value *RV;
5219 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005220
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005221 if (ResType != RV->getType())
5222 return Error(TypeLoc, "value doesn't match function result type '" +
5223 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005224
Owen Anderson55f1c092009-08-13 21:58:54 +00005225 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005226 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005227}
5228
Chris Lattnerac161bf2009-01-02 07:01:27 +00005229/// ParseBr
5230/// ::= 'br' TypeAndValue
5231/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5232bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5233 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005234 Value *Op0;
5235 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005236 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005237
Chris Lattnerac161bf2009-01-02 07:01:27 +00005238 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5239 Inst = BranchInst::Create(BB);
5240 return false;
5241 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005242
Owen Anderson55f1c092009-08-13 21:58:54 +00005243 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005244 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005245
Chris Lattnerac161bf2009-01-02 07:01:27 +00005246 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005247 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005248 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005249 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005250 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005251
Chris Lattner3ed871f2009-10-27 19:13:16 +00005252 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005253 return false;
5254}
5255
5256/// ParseSwitch
5257/// Instruction
5258/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5259/// JumpTable
5260/// ::= (TypeAndValue ',' TypeAndValue)*
5261bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5262 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005263 Value *Cond;
5264 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005265 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5266 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005267 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005268 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5269 return true;
5270
Duncan Sands19d0b472010-02-16 11:11:14 +00005271 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005272 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005273
Chris Lattnerac161bf2009-01-02 07:01:27 +00005274 // Parse the jump table pairs.
5275 SmallPtrSet<Value*, 32> SeenCases;
5276 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5277 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005278 Value *Constant;
5279 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005280
Chris Lattnerac161bf2009-01-02 07:01:27 +00005281 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5282 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005283 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005284 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005285
David Blaikie70573dc2014-11-19 07:49:26 +00005286 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005287 return Error(CondLoc, "duplicate case value in switch");
5288 if (!isa<ConstantInt>(Constant))
5289 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005290
Chris Lattner3ed871f2009-10-27 19:13:16 +00005291 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005292 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005293
Chris Lattnerac161bf2009-01-02 07:01:27 +00005294 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005295
Chris Lattner3ed871f2009-10-27 19:13:16 +00005296 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005297 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5298 SI->addCase(Table[i].first, Table[i].second);
5299 Inst = SI;
5300 return false;
5301}
5302
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005303/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005304/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005305/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5306bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005307 LocTy AddrLoc;
5308 Value *Address;
5309 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005310 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5311 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005312 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005313
Duncan Sands19d0b472010-02-16 11:11:14 +00005314 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005315 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005316
Chris Lattner3ed871f2009-10-27 19:13:16 +00005317 // Parse the destination list.
5318 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005319
Chris Lattner3ed871f2009-10-27 19:13:16 +00005320 if (Lex.getKind() != lltok::rsquare) {
5321 BasicBlock *DestBB;
5322 if (ParseTypeAndBasicBlock(DestBB, PFS))
5323 return true;
5324 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005325
Chris Lattner3ed871f2009-10-27 19:13:16 +00005326 while (EatIfPresent(lltok::comma)) {
5327 if (ParseTypeAndBasicBlock(DestBB, PFS))
5328 return true;
5329 DestList.push_back(DestBB);
5330 }
5331 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005332
Chris Lattner3ed871f2009-10-27 19:13:16 +00005333 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5334 return true;
5335
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005336 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005337 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5338 IBI->addDestination(DestList[i]);
5339 Inst = IBI;
5340 return false;
5341}
5342
Chris Lattnerac161bf2009-01-02 07:01:27 +00005343/// ParseInvoke
5344/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5345/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5346bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5347 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005348 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005349 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005350 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005351 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005352 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005353 LocTy RetTypeLoc;
5354 ValID CalleeID;
5355 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005356 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005357
Chris Lattner3ed871f2009-10-27 19:13:16 +00005358 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005359 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005360 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005361 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005362 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5363 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005364 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005365 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005366 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005367 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005368 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005369 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005370
Chris Lattnerac161bf2009-01-02 07:01:27 +00005371 // If RetType is a non-function pointer type, then this is the short syntax
5372 // for the call, which means that RetType is just the return type. Infer the
5373 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005374 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5375 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005376 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005377 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005378 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5379 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005380
Chris Lattnerac161bf2009-01-02 07:01:27 +00005381 if (!FunctionType::isValidReturnType(RetType))
5382 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005383
Owen Anderson4056ca92009-07-29 22:17:13 +00005384 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005385 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005386
David Blaikie41ba2b42015-07-27 23:32:19 +00005387 CalleeID.FTy = Ty;
5388
Chris Lattnerac161bf2009-01-02 07:01:27 +00005389 // Look up the callee.
5390 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005391 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5392 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005393
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005394 // Set up the Attribute for the function.
Reid Kleckner7f720332017-04-13 00:58:09 +00005395 SmallVector<Value *, 8> Args;
5396 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005397
Chris Lattnerac161bf2009-01-02 07:01:27 +00005398 // Loop through FunctionType's arguments and ensure they are specified
5399 // correctly. Also, gather any parameter attributes.
5400 FunctionType::param_iterator I = Ty->param_begin();
5401 FunctionType::param_iterator E = Ty->param_end();
5402 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005403 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005404 if (I != E) {
5405 ExpectedTy = *I++;
5406 } else if (!Ty->isVarArg()) {
5407 return Error(ArgList[i].Loc, "too many arguments specified");
5408 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005409
Chris Lattnerac161bf2009-01-02 07:01:27 +00005410 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5411 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005412 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005413 Args.push_back(ArgList[i].V);
Reid Kleckner7f720332017-04-13 00:58:09 +00005414 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005415 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005416
Chris Lattnerac161bf2009-01-02 07:01:27 +00005417 if (I != E)
5418 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005419
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005420 if (FnAttrs.hasAlignmentAttr())
5421 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005422
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005423 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00005424 AttributeList PAL =
5425 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5426 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005427
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005428 InvokeInst *II =
5429 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005430 II->setCallingConv(CC);
5431 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005432 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005433 Inst = II;
5434 return false;
5435}
5436
Bill Wendlingf891bf82011-07-31 06:30:59 +00005437/// ParseResume
5438/// ::= 'resume' TypeAndValue
5439bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5440 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005441 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5442 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005443
Bill Wendlingf891bf82011-07-31 06:30:59 +00005444 ResumeInst *RI = ResumeInst::Create(Exn);
5445 Inst = RI;
5446 return false;
5447}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005448
David Majnemer654e1302015-07-31 17:58:14 +00005449bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5450 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005451 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005452 return true;
5453
5454 while (Lex.getKind() != lltok::rsquare) {
5455 // If this isn't the first argument, we need a comma.
5456 if (!Args.empty() &&
5457 ParseToken(lltok::comma, "expected ',' in argument list"))
5458 return true;
5459
5460 // Parse the argument.
5461 LocTy ArgLoc;
5462 Type *ArgTy = nullptr;
5463 if (ParseType(ArgTy, ArgLoc))
5464 return true;
5465
5466 Value *V;
5467 if (ArgTy->isMetadataTy()) {
5468 if (ParseMetadataAsValue(V, PFS))
5469 return true;
5470 } else {
5471 if (ParseValue(ArgTy, V, PFS))
5472 return true;
5473 }
5474 Args.push_back(V);
5475 }
5476
5477 Lex.Lex(); // Lex the ']'.
5478 return false;
5479}
5480
5481/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005482/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005483bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005484 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005485
David Majnemer8a1c45d2015-12-12 05:38:55 +00005486 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5487 return true;
5488
5489 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005490 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005491
5492 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5493 return true;
5494
5495 BasicBlock *UnwindBB = nullptr;
5496 if (Lex.getKind() == lltok::kw_to) {
5497 Lex.Lex();
5498 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5499 return true;
5500 } else {
5501 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5502 return true;
5503 }
5504 }
5505
David Majnemer8a1c45d2015-12-12 05:38:55 +00005506 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005507 return false;
5508}
5509
5510/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005511/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005512bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005513 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005514
David Majnemer8a1c45d2015-12-12 05:38:55 +00005515 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5516 return true;
5517
5518 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005519 return true;
5520
David Majnemer0bc0eef2015-08-15 02:46:08 +00005521 BasicBlock *BB;
5522 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5523 ParseTypeAndBasicBlock(BB, PFS))
5524 return true;
5525
David Majnemer8a1c45d2015-12-12 05:38:55 +00005526 Inst = CatchReturnInst::Create(CatchPad, BB);
5527 return false;
5528}
5529
5530/// ParseCatchSwitch
5531/// ::= 'catchswitch' within Parent
5532bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5533 Value *ParentPad;
5534 LocTy BBLoc;
5535
5536 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5537 return true;
5538
5539 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5540 Lex.getKind() != lltok::LocalVarID)
5541 return TokError("expected scope value for catchswitch");
5542
5543 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5544 return true;
5545
5546 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5547 return true;
5548
5549 SmallVector<BasicBlock *, 32> Table;
5550 do {
5551 BasicBlock *DestBB;
5552 if (ParseTypeAndBasicBlock(DestBB, PFS))
5553 return true;
5554 Table.push_back(DestBB);
5555 } while (EatIfPresent(lltok::comma));
5556
5557 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5558 return true;
5559
5560 if (ParseToken(lltok::kw_unwind,
5561 "expected 'unwind' after catchswitch scope"))
5562 return true;
5563
5564 BasicBlock *UnwindBB = nullptr;
5565 if (EatIfPresent(lltok::kw_to)) {
5566 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5567 return true;
5568 } else {
5569 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5570 return true;
5571 }
5572
5573 auto *CatchSwitch =
5574 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5575 for (BasicBlock *DestBB : Table)
5576 CatchSwitch->addHandler(DestBB);
5577 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005578 return false;
5579}
5580
5581/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005582/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005583bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005584 Value *CatchSwitch = nullptr;
5585
5586 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5587 return true;
5588
5589 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5590 return TokError("expected scope value for catchpad");
5591
5592 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5593 return true;
5594
David Majnemer654e1302015-07-31 17:58:14 +00005595 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005596 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005597 return true;
5598
David Majnemer8a1c45d2015-12-12 05:38:55 +00005599 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005600 return false;
5601}
5602
David Majnemer654e1302015-07-31 17:58:14 +00005603/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005604/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005605bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005606 Value *ParentPad = nullptr;
5607
5608 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5609 return true;
5610
5611 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5612 Lex.getKind() != lltok::LocalVarID)
5613 return TokError("expected scope value for cleanuppad");
5614
5615 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5616 return true;
5617
David Majnemer654e1302015-07-31 17:58:14 +00005618 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005619 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005620 return true;
5621
David Majnemer8a1c45d2015-12-12 05:38:55 +00005622 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005623 return false;
5624}
5625
Chris Lattnerac161bf2009-01-02 07:01:27 +00005626//===----------------------------------------------------------------------===//
5627// Binary Operators.
5628//===----------------------------------------------------------------------===//
5629
5630/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005631/// ::= ArithmeticOps TypeAndValue ',' Value
5632///
5633/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5634/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005635bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005636 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005637 LocTy Loc; Value *LHS, *RHS;
5638 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5639 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5640 ParseValue(LHS->getType(), RHS, PFS))
5641 return true;
5642
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005643 bool Valid;
5644 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005645 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005646 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005647 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5648 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005649 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005650 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5651 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005652 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005653
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005654 if (!Valid)
5655 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005656
Chris Lattnerac161bf2009-01-02 07:01:27 +00005657 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5658 return false;
5659}
5660
5661/// ParseLogical
5662/// ::= ArithmeticOps TypeAndValue ',' Value {
5663bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5664 unsigned Opc) {
5665 LocTy Loc; Value *LHS, *RHS;
5666 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5667 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5668 ParseValue(LHS->getType(), RHS, PFS))
5669 return true;
5670
Duncan Sands9dff9be2010-02-15 16:12:20 +00005671 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005672 return Error(Loc,"instruction requires integer or integer vector operands");
5673
5674 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5675 return false;
5676}
5677
Chris Lattnerac161bf2009-01-02 07:01:27 +00005678/// ParseCompare
5679/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5680/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005681bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5682 unsigned Opc) {
5683 // Parse the integer/fp comparison predicate.
5684 LocTy Loc;
5685 unsigned Pred;
5686 Value *LHS, *RHS;
5687 if (ParseCmpPredicate(Pred, Opc) ||
5688 ParseTypeAndValue(LHS, Loc, PFS) ||
5689 ParseToken(lltok::comma, "expected ',' after compare value") ||
5690 ParseValue(LHS->getType(), RHS, PFS))
5691 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005692
Chris Lattnerac161bf2009-01-02 07:01:27 +00005693 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005694 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005695 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005696 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005697 } else {
5698 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005699 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005700 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005701 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005702 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005703 }
5704 return false;
5705}
5706
5707//===----------------------------------------------------------------------===//
5708// Other Instructions.
5709//===----------------------------------------------------------------------===//
5710
5711
5712/// ParseCast
5713/// ::= CastOpc TypeAndValue 'to' Type
5714bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5715 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005716 LocTy Loc;
5717 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005718 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005719 if (ParseTypeAndValue(Op, Loc, PFS) ||
5720 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5721 ParseType(DestTy))
5722 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005723
Chris Lattner89d856e2009-03-01 00:53:13 +00005724 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5725 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005726 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005727 getTypeString(Op->getType()) + "' to '" +
5728 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005729 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005730 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5731 return false;
5732}
5733
5734/// ParseSelect
5735/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5736bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5737 LocTy Loc;
5738 Value *Op0, *Op1, *Op2;
5739 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5740 ParseToken(lltok::comma, "expected ',' after select condition") ||
5741 ParseTypeAndValue(Op1, PFS) ||
5742 ParseToken(lltok::comma, "expected ',' after select value") ||
5743 ParseTypeAndValue(Op2, PFS))
5744 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005745
Chris Lattnerac161bf2009-01-02 07:01:27 +00005746 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5747 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005748
Chris Lattnerac161bf2009-01-02 07:01:27 +00005749 Inst = SelectInst::Create(Op0, Op1, Op2);
5750 return false;
5751}
5752
Chris Lattnerb55ab542009-01-05 08:18:44 +00005753/// ParseVA_Arg
5754/// ::= 'va_arg' TypeAndValue ',' Type
5755bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005756 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005757 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005758 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005759 if (ParseTypeAndValue(Op, PFS) ||
5760 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005761 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005762 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005763
Chris Lattnerb55ab542009-01-05 08:18:44 +00005764 if (!EltTy->isFirstClassType())
5765 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005766
5767 Inst = new VAArgInst(Op, EltTy);
5768 return false;
5769}
5770
5771/// ParseExtractElement
5772/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5773bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5774 LocTy Loc;
5775 Value *Op0, *Op1;
5776 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5777 ParseToken(lltok::comma, "expected ',' after extract value") ||
5778 ParseTypeAndValue(Op1, PFS))
5779 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005780
Chris Lattnerac161bf2009-01-02 07:01:27 +00005781 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5782 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005783
Eric Christopherc9742252009-07-25 02:28:41 +00005784 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005785 return false;
5786}
5787
5788/// ParseInsertElement
5789/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5790bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5791 LocTy Loc;
5792 Value *Op0, *Op1, *Op2;
5793 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5794 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5795 ParseTypeAndValue(Op1, PFS) ||
5796 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5797 ParseTypeAndValue(Op2, PFS))
5798 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005799
Chris Lattnerac161bf2009-01-02 07:01:27 +00005800 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005801 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005802
Chris Lattnerac161bf2009-01-02 07:01:27 +00005803 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5804 return false;
5805}
5806
5807/// ParseShuffleVector
5808/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5809bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5810 LocTy Loc;
5811 Value *Op0, *Op1, *Op2;
5812 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5813 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5814 ParseTypeAndValue(Op1, PFS) ||
5815 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5816 ParseTypeAndValue(Op2, PFS))
5817 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005818
Chris Lattnerac161bf2009-01-02 07:01:27 +00005819 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005820 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005821
Chris Lattnerac161bf2009-01-02 07:01:27 +00005822 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5823 return false;
5824}
5825
5826/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005827/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005828int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005829 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005830 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005831
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005832 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005833 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5834 ParseValue(Ty, Op0, PFS) ||
5835 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005836 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005837 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5838 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005839
Chris Lattnerf4f03422009-12-30 05:27:33 +00005840 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005841 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005842
5843 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005844 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005845
Chris Lattner3822f632009-01-02 08:05:26 +00005846 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005847 break;
5848
Chris Lattnerf4f03422009-12-30 05:27:33 +00005849 if (Lex.getKind() == lltok::MetadataVar) {
5850 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005851 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005852 }
Devang Patel8f842d32009-10-16 18:45:49 +00005853
Chris Lattner3822f632009-01-02 08:05:26 +00005854 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005855 ParseValue(Ty, Op0, PFS) ||
5856 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005857 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005858 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5859 return true;
5860 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005861
Chris Lattnerac161bf2009-01-02 07:01:27 +00005862 if (!Ty->isFirstClassType())
5863 return Error(TypeLoc, "phi node must have first class type");
5864
Jay Foad52131342011-03-30 11:28:46 +00005865 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005866 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5867 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5868 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005869 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005870}
5871
Bill Wendlingfae14752011-08-12 20:24:12 +00005872/// ParseLandingPad
5873/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5874/// Clause
5875/// ::= 'catch' TypeAndValue
5876/// ::= 'filter'
5877/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5878bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005879 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005880
David Majnemer7fddecc2015-06-17 20:52:32 +00005881 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005882 return true;
5883
David Majnemer7fddecc2015-06-17 20:52:32 +00005884 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005885 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5886
5887 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5888 LandingPadInst::ClauseType CT;
5889 if (EatIfPresent(lltok::kw_catch))
5890 CT = LandingPadInst::Catch;
5891 else if (EatIfPresent(lltok::kw_filter))
5892 CT = LandingPadInst::Filter;
5893 else
5894 return TokError("expected 'catch' or 'filter' clause type");
5895
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005896 Value *V;
5897 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005898 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005899 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005900
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005901 // A 'catch' type expects a non-array constant. A filter clause expects an
5902 // array constant.
5903 if (CT == LandingPadInst::Catch) {
5904 if (isa<ArrayType>(V->getType()))
5905 Error(VLoc, "'catch' clause has an invalid type");
5906 } else {
5907 if (!isa<ArrayType>(V->getType()))
5908 Error(VLoc, "'filter' clause has an invalid type");
5909 }
5910
Owen Andersonf8f259d2015-03-09 07:13:42 +00005911 Constant *CV = dyn_cast<Constant>(V);
5912 if (!CV)
5913 return Error(VLoc, "clause argument must be a constant");
5914 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005915 }
5916
Owen Andersonf8f259d2015-03-09 07:13:42 +00005917 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005918 return false;
5919}
5920
Chris Lattnerac161bf2009-01-02 07:01:27 +00005921/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005922/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5923/// OptionalAttrs Type Value ParameterList OptionalAttrs
5924/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5925/// OptionalAttrs Type Value ParameterList OptionalAttrs
5926/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5927/// OptionalAttrs Type Value ParameterList OptionalAttrs
5928/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5929/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005930bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005931 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005932 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005933 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005934 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005935 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005936 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005937 LocTy RetTypeLoc;
5938 ValID CalleeID;
5939 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005940 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005941 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005942
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005943 if (TCK != CallInst::TCK_None &&
5944 ParseToken(lltok::kw_call,
5945 "expected 'tail call', 'musttail call', or 'notail call'"))
5946 return true;
5947
5948 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5949
5950 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005951 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005952 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005953 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5954 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005955 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5956 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005957 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005958
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005959 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5960 return Error(CallLoc, "fast-math-flags specified for call without "
5961 "floating-point scalar or vector return type");
5962
Chris Lattnerac161bf2009-01-02 07:01:27 +00005963 // If RetType is a non-function pointer type, then this is the short syntax
5964 // for the call, which means that RetType is just the return type. Infer the
5965 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005966 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5967 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005968 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005969 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005970 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5971 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005972
Chris Lattnerac161bf2009-01-02 07:01:27 +00005973 if (!FunctionType::isValidReturnType(RetType))
5974 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005975
Owen Anderson4056ca92009-07-29 22:17:13 +00005976 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005977 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005978
David Blaikie41ba2b42015-07-27 23:32:19 +00005979 CalleeID.FTy = Ty;
5980
Chris Lattnerac161bf2009-01-02 07:01:27 +00005981 // Look up the callee.
5982 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005983 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5984 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005985
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005986 // Set up the Attribute for the function.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00005987 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005988
Chris Lattnerac161bf2009-01-02 07:01:27 +00005989 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005990
Chris Lattnerac161bf2009-01-02 07:01:27 +00005991 // Loop through FunctionType's arguments and ensure they are specified
5992 // correctly. Also, gather any parameter attributes.
5993 FunctionType::param_iterator I = Ty->param_begin();
5994 FunctionType::param_iterator E = Ty->param_end();
5995 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005996 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005997 if (I != E) {
5998 ExpectedTy = *I++;
5999 } else if (!Ty->isVarArg()) {
6000 return Error(ArgList[i].Loc, "too many arguments specified");
6001 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006002
Chris Lattnerac161bf2009-01-02 07:01:27 +00006003 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6004 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006005 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006006 Args.push_back(ArgList[i].V);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006007 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006008 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006009
Chris Lattnerac161bf2009-01-02 07:01:27 +00006010 if (I != E)
6011 return Error(CallLoc, "not enough parameters specified for call");
6012
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006013 if (FnAttrs.hasAlignmentAttr())
6014 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006015
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006016 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006017 AttributeList PAL =
6018 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6019 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006020
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006021 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006022 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006023 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006024 if (FMF.any())
6025 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006026 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006027 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006028 Inst = CI;
6029 return false;
6030}
6031
6032//===----------------------------------------------------------------------===//
6033// Memory Instructions.
6034//===----------------------------------------------------------------------===//
6035
6036/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006037/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6038/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00006039int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006040 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006041 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006042 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006043 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006044 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006045
6046 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006047 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006048
David Majnemera3b0eb22015-02-16 08:38:03 +00006049 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006050
David Majnemera3b0eb22015-02-16 08:38:03 +00006051 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6052 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006053
Chris Lattnerb2f39502009-12-30 05:44:30 +00006054 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006055 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006056 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006057 if (ParseOptionalAlignment(Alignment))
6058 return true;
6059 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6060 return true;
6061 } else if (Lex.getKind() == lltok::kw_addrspace) {
6062 ASLoc = Lex.getLoc();
6063 if (ParseOptionalAddrSpace(AddrSpace))
6064 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006065 } else if (Lex.getKind() == lltok::MetadataVar) {
6066 AteExtraComma = true;
6067 } else {
6068 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006069 ParseOptionalCommaAlign(Alignment, AteExtraComma) ||
6070 (!AteExtraComma &&
6071 ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006072 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006073 }
6074 }
6075
Dan Gohman2140a742010-05-28 01:14:11 +00006076 if (Size && !Size->getType()->isIntegerTy())
6077 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006078
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006079 const DataLayout &DL = M->getDataLayout();
6080 unsigned AS = DL.getAllocaAddrSpace();
6081 if (AS != AddrSpace) {
6082 // TODO: In the future it should be possible to specify addrspace per-alloca.
6083 return Error(ASLoc, "address space must match datalayout");
6084 }
6085
6086 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006087 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006088 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006089 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006090 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006091}
6092
6093/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006094/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006095/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006096/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006097int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006098 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006099 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006100 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006101 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006102 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006103 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006104
6105 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006106 isAtomic = true;
6107 Lex.Lex();
6108 }
6109
Chris Lattnerbc639292011-11-27 06:56:53 +00006110 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006111 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006112 isVolatile = true;
6113 Lex.Lex();
6114 }
6115
David Blaikie15d9a4c2015-04-06 20:59:48 +00006116 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006117 LocTy ExplicitTypeLoc = Lex.getLoc();
6118 if (ParseType(Ty) ||
6119 ParseToken(lltok::comma, "expected comma after load's type") ||
6120 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006121 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006122 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6123 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006124
David Blaikie15d9a4c2015-04-06 20:59:48 +00006125 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006126 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006127 if (isAtomic && !Alignment)
6128 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006129 if (Ordering == AtomicOrdering::Release ||
6130 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006131 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006132
David Blaikiea79ac142015-02-27 21:17:42 +00006133 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6134 return Error(ExplicitTypeLoc,
6135 "explicit pointee type doesn't match operand's pointee type");
6136
David Blaikie15d9a4c2015-04-06 20:59:48 +00006137 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006138 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006139}
6140
6141/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006142
6143/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6144/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006145/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006146int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006147 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006148 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006149 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006150 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006151 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006152 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006153
6154 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006155 isAtomic = true;
6156 Lex.Lex();
6157 }
6158
Chris Lattnerbc639292011-11-27 06:56:53 +00006159 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006160 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006161 isVolatile = true;
6162 Lex.Lex();
6163 }
6164
Chris Lattnerac161bf2009-01-02 07:01:27 +00006165 if (ParseTypeAndValue(Val, Loc, PFS) ||
6166 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006167 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006168 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006169 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006170 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006171
Duncan Sands19d0b472010-02-16 11:11:14 +00006172 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006173 return Error(PtrLoc, "store operand must be a pointer");
6174 if (!Val->getType()->isFirstClassType())
6175 return Error(Loc, "store operand must be a first class value");
6176 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6177 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006178 if (isAtomic && !Alignment)
6179 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006180 if (Ordering == AtomicOrdering::Acquire ||
6181 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006182 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006183
Eli Friedman59b66882011-08-09 23:02:53 +00006184 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006185 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006186}
6187
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006188/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006189/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6190/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006191int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006192 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6193 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006194 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6195 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006196 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006197 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006198 bool isWeak = false;
6199
6200 if (EatIfPresent(lltok::kw_weak))
6201 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006202
6203 if (EatIfPresent(lltok::kw_volatile))
6204 isVolatile = true;
6205
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006206 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6207 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6208 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6209 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6210 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006211 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6212 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006213 return true;
6214
JF Bastien800f87a2016-04-06 21:19:33 +00006215 if (SuccessOrdering == AtomicOrdering::Unordered ||
6216 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006217 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006218 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6219 return TokError("cmpxchg failure argument shall be no stronger than the "
6220 "success argument");
6221 if (FailureOrdering == AtomicOrdering::Release ||
6222 FailureOrdering == AtomicOrdering::AcquireRelease)
6223 return TokError(
6224 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006225 if (!Ptr->getType()->isPointerTy())
6226 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6227 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6228 return Error(CmpLoc, "compare value and pointer type do not match");
6229 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6230 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006231 if (!New->getType()->isFirstClassType())
6232 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006233 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6234 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006235 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006236 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006237 Inst = CXI;
6238 return AteExtraComma ? InstExtraComma : InstNormal;
6239}
6240
6241/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006242/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6243/// 'singlethread'? AtomicOrdering
6244int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006245 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6246 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006247 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006248 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006249 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006250 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006251
6252 if (EatIfPresent(lltok::kw_volatile))
6253 isVolatile = true;
6254
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006255 switch (Lex.getKind()) {
6256 default: return TokError("expected binary operation in atomicrmw");
6257 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6258 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6259 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6260 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6261 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6262 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6263 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6264 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6265 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6266 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6267 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6268 }
6269 Lex.Lex(); // Eat the operation.
6270
6271 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6272 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6273 ParseTypeAndValue(Val, ValLoc, PFS) ||
6274 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6275 return true;
6276
JF Bastien800f87a2016-04-06 21:19:33 +00006277 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006278 return TokError("atomicrmw cannot be unordered");
6279 if (!Ptr->getType()->isPointerTy())
6280 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6281 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6282 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6283 if (!Val->getType()->isIntegerTy())
6284 return Error(ValLoc, "atomicrmw operand must be an integer");
6285 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6286 if (Size < 8 || (Size & (Size - 1)))
6287 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6288 " integer");
6289
6290 AtomicRMWInst *RMWI =
6291 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6292 RMWI->setVolatile(isVolatile);
6293 Inst = RMWI;
6294 return AteExtraComma ? InstExtraComma : InstNormal;
6295}
6296
Eli Friedmanfee02c62011-07-25 23:16:38 +00006297/// ParseFence
6298/// ::= 'fence' 'singlethread'? AtomicOrdering
6299int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006300 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanfee02c62011-07-25 23:16:38 +00006301 SynchronizationScope Scope = CrossThread;
6302 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6303 return true;
6304
JF Bastien800f87a2016-04-06 21:19:33 +00006305 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006306 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006307 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006308 return TokError("fence cannot be monotonic");
6309
6310 Inst = new FenceInst(Context, Ordering, Scope);
6311 return InstNormal;
6312}
6313
Chris Lattnerac161bf2009-01-02 07:01:27 +00006314/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006315/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006316int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006317 Value *Ptr = nullptr;
6318 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006319 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006320
Dan Gohman16cbbe42009-07-29 15:58:36 +00006321 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006322
David Blaikie79e6c742015-02-27 19:29:02 +00006323 Type *Ty = nullptr;
6324 LocTy ExplicitTypeLoc = Lex.getLoc();
6325 if (ParseType(Ty) ||
6326 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6327 ParseTypeAndValue(Ptr, Loc, PFS))
6328 return true;
6329
Eli Benderskyd9806682013-04-22 17:03:42 +00006330 Type *BaseType = Ptr->getType();
6331 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6332 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006333 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006334
David Blaikie8d757942015-03-09 23:08:44 +00006335 if (Ty != BasePointerType->getElementType())
6336 return Error(ExplicitTypeLoc,
6337 "explicit pointee type doesn't match operand's pointee type");
6338
Chris Lattnerac161bf2009-01-02 07:01:27 +00006339 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006340 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006341 // GEP returns a vector of pointers if at least one of parameters is a vector.
6342 // All vector parameters should have the same vector width.
6343 unsigned GEPWidth = BaseType->isVectorTy() ?
6344 BaseType->getVectorNumElements() : 0;
6345
Chris Lattner3822f632009-01-02 08:05:26 +00006346 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006347 if (Lex.getKind() == lltok::MetadataVar) {
6348 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006349 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006350 }
Chris Lattner3822f632009-01-02 08:05:26 +00006351 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006352 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006353 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006354
Nadav Rotem3924cb02011-12-05 06:29:09 +00006355 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006356 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6357 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006358 return Error(EltLoc,
6359 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006360 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006361 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006362 Indices.push_back(Val);
6363 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006364
Craig Toppere3dcce92015-08-01 22:20:21 +00006365 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006366 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006367 return Error(Loc, "base element of getelementptr must be sized");
6368
David Blaikied33bad32015-04-17 22:32:13 +00006369 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006370 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006371 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006372 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006373 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006374 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006375}
6376
6377/// ParseExtractValue
6378/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006379int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006380 Value *Val; LocTy Loc;
6381 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006382 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006383 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006384 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006385 return true;
6386
Chris Lattner392be582010-02-12 20:49:41 +00006387 if (!Val->getType()->isAggregateType())
6388 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006389
Jay Foad57aa6362011-07-13 10:26:04 +00006390 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006391 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006392 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006393 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006394}
6395
6396/// ParseInsertValue
6397/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006398int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006399 Value *Val0, *Val1; LocTy Loc0, Loc1;
6400 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006401 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006402 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6403 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6404 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006405 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006406 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006407
Chris Lattner392be582010-02-12 20:49:41 +00006408 if (!Val0->getType()->isAggregateType())
6409 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006410
David Majnemer30074532015-02-11 07:43:58 +00006411 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6412 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006413 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006414 if (IndexedType != Val1->getType())
6415 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6416 getTypeString(Val1->getType()) + "' instead of '" +
6417 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006418 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006419 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006420}
Nick Lewycky49f89192009-04-04 07:22:01 +00006421
6422//===----------------------------------------------------------------------===//
6423// Embedded metadata.
6424//===----------------------------------------------------------------------===//
6425
6426/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006427/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006428/// Element
6429/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006430bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006431 if (ParseToken(lltok::lbrace, "expected '{' here"))
6432 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006433
Dan Gohman1e0213a2010-07-13 19:33:27 +00006434 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006435 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006436 return false;
6437
Nick Lewycky49f89192009-04-04 07:22:01 +00006438 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006439 // Null is a special case since it is typeless.
6440 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006441 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006442 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006443 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006444
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006445 Metadata *MD;
6446 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006447 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006448 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006449 } while (EatIfPresent(lltok::comma));
6450
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006451 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006452}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006453
6454//===----------------------------------------------------------------------===//
6455// Use-list order directives.
6456//===----------------------------------------------------------------------===//
6457bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6458 SMLoc Loc) {
6459 if (V->use_empty())
6460 return Error(Loc, "value has no uses");
6461
6462 unsigned NumUses = 0;
6463 SmallDenseMap<const Use *, unsigned, 16> Order;
6464 for (const Use &U : V->uses()) {
6465 if (++NumUses > Indexes.size())
6466 break;
6467 Order[&U] = Indexes[NumUses - 1];
6468 }
6469 if (NumUses < 2)
6470 return Error(Loc, "value only has one use");
6471 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6472 return Error(Loc, "wrong number of indexes, expected " +
6473 Twine(std::distance(V->use_begin(), V->use_end())));
6474
6475 V->sortUseList([&](const Use &L, const Use &R) {
6476 return Order.lookup(&L) < Order.lookup(&R);
6477 });
6478 return false;
6479}
6480
6481/// ParseUseListOrderIndexes
6482/// ::= '{' uint32 (',' uint32)+ '}'
6483bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6484 SMLoc Loc = Lex.getLoc();
6485 if (ParseToken(lltok::lbrace, "expected '{' here"))
6486 return true;
6487 if (Lex.getKind() == lltok::rbrace)
6488 return Lex.Error("expected non-empty list of uselistorder indexes");
6489
6490 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6491 // indexes should be distinct numbers in the range [0, size-1], and should
6492 // not be in order.
6493 unsigned Offset = 0;
6494 unsigned Max = 0;
6495 bool IsOrdered = true;
6496 assert(Indexes.empty() && "Expected empty order vector");
6497 do {
6498 unsigned Index;
6499 if (ParseUInt32(Index))
6500 return true;
6501
6502 // Update consistency checks.
6503 Offset += Index - Indexes.size();
6504 Max = std::max(Max, Index);
6505 IsOrdered &= Index == Indexes.size();
6506
6507 Indexes.push_back(Index);
6508 } while (EatIfPresent(lltok::comma));
6509
6510 if (ParseToken(lltok::rbrace, "expected '}' here"))
6511 return true;
6512
6513 if (Indexes.size() < 2)
6514 return Error(Loc, "expected >= 2 uselistorder indexes");
6515 if (Offset != 0 || Max >= Indexes.size())
6516 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6517 if (IsOrdered)
6518 return Error(Loc, "expected uselistorder indexes to change the order");
6519
6520 return false;
6521}
6522
6523/// ParseUseListOrder
6524/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6525bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6526 SMLoc Loc = Lex.getLoc();
6527 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6528 return true;
6529
6530 Value *V;
6531 SmallVector<unsigned, 16> Indexes;
6532 if (ParseTypeAndValue(V, PFS) ||
6533 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6534 ParseUseListOrderIndexes(Indexes))
6535 return true;
6536
6537 return sortUseListOrder(V, Indexes, Loc);
6538}
6539
6540/// ParseUseListOrderBB
6541/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6542bool LLParser::ParseUseListOrderBB() {
6543 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6544 SMLoc Loc = Lex.getLoc();
6545 Lex.Lex();
6546
6547 ValID Fn, Label;
6548 SmallVector<unsigned, 16> Indexes;
6549 if (ParseValID(Fn) ||
6550 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6551 ParseValID(Label) ||
6552 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6553 ParseUseListOrderIndexes(Indexes))
6554 return true;
6555
6556 // Check the function.
6557 GlobalValue *GV;
6558 if (Fn.Kind == ValID::t_GlobalName)
6559 GV = M->getNamedValue(Fn.StrVal);
6560 else if (Fn.Kind == ValID::t_GlobalID)
6561 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6562 else
6563 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6564 if (!GV)
6565 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6566 auto *F = dyn_cast<Function>(GV);
6567 if (!F)
6568 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6569 if (F->isDeclaration())
6570 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6571
6572 // Check the basic block.
6573 if (Label.Kind == ValID::t_LocalID)
6574 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6575 if (Label.Kind != ValID::t_LocalName)
6576 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00006577 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006578 if (!V)
6579 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6580 if (!isa<BasicBlock>(V))
6581 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6582
6583 return sortUseListOrder(V, Indexes, Loc);
6584}