blob: b5c7f16ea2b8d344f0d35c2572baca9ca9f051c9 [file] [log] [blame]
Chris Lattnerac161bf2009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth91065212014-03-05 10:34:14 +000016#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/CallingConv.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/DerivedTypes.h"
20#include "llvm/IR/InlineAsm.h"
21#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000022#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Module.h"
24#include "llvm/IR/Operator.h"
25#include "llvm/IR/ValueSymbolTable.h"
Torok Edwin56d06592009-07-11 20:10:48 +000026#include "llvm/Support/ErrorHandling.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000027#include "llvm/Support/raw_ostream.h"
28using namespace llvm;
29
Chris Lattner229907c2011-07-18 04:54:35 +000030static std::string getTypeString(Type *T) {
Chris Lattner0f214eb2011-06-18 21:18:23 +000031 std::string Result;
32 raw_string_ostream Tmp(Result);
33 Tmp << *T;
34 return Tmp.str();
35}
36
Chris Lattner3822f632009-01-02 08:05:26 +000037/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000038bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000039 // Prime the lexer.
40 Lex.Lex();
41
Chris Lattnerad6f3352009-01-04 20:44:11 +000042 return ParseTopLevelEntities() ||
43 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000044}
45
46/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
47/// module.
48bool LLParser::ValidateEndOfModule() {
Chris Lattner8eff0152010-04-01 05:14:45 +000049 // Handle any instruction metadata forward references.
50 if (!ForwardRefInstMetadata.empty()) {
51 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
52 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
53 I != E; ++I) {
54 Instruction *Inst = I->first;
55 const std::vector<MDRef> &MDList = I->second;
Michael Ilseman26ee2b82012-11-15 22:34:00 +000056
Chris Lattner8eff0152010-04-01 05:14:45 +000057 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
58 unsigned SlotNo = MDList[i].MDSlot;
Michael Ilseman26ee2b82012-11-15 22:34:00 +000059
Chris Lattner8eff0152010-04-01 05:14:45 +000060 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
61 return Error(MDList[i].Loc, "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +000062 Twine(SlotNo) + "'");
Chris Lattner8eff0152010-04-01 05:14:45 +000063 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
64 }
65 }
66 ForwardRefInstMetadata.clear();
67 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +000068
Manman Ren209b17c2013-09-28 00:22:27 +000069 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
70 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
71
Bill Wendlingb32b0412013-02-08 06:32:06 +000072 // Handle any function attribute group forward references.
73 for (std::map<Value*, std::vector<unsigned> >::iterator
74 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
75 I != E; ++I) {
76 Value *V = I->first;
77 std::vector<unsigned> &Vec = I->second;
78 AttrBuilder B;
79
80 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
81 VI != VE; ++VI)
82 B.merge(NumberedAttrBuilders[*VI]);
83
84 if (Function *Fn = dyn_cast<Function>(V)) {
85 AttributeSet AS = Fn->getAttributes();
86 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
87 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
88 AS.getFnAttributes());
89
90 FnAttrs.merge(B);
91
92 // If the alignment was parsed as an attribute, move to the alignment
93 // field.
94 if (FnAttrs.hasAlignmentAttr()) {
95 Fn->setAlignment(FnAttrs.getAlignment());
96 FnAttrs.removeAttribute(Attribute::Alignment);
97 }
98
99 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
100 AttributeSet::get(Context,
101 AttributeSet::FunctionIndex,
102 FnAttrs));
103 Fn->setAttributes(AS);
104 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
105 AttributeSet AS = CI->getAttributes();
106 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
107 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
108 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000109 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000110 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
111 AttributeSet::get(Context,
112 AttributeSet::FunctionIndex,
113 FnAttrs));
114 CI->setAttributes(AS);
115 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
116 AttributeSet AS = II->getAttributes();
117 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
118 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
119 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000120 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000121 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
122 AttributeSet::get(Context,
123 AttributeSet::FunctionIndex,
124 FnAttrs));
125 II->setAttributes(AS);
126 } else {
127 llvm_unreachable("invalid object with forward attribute group reference");
128 }
129 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000130
Chris Lattner3432c622009-10-28 03:39:23 +0000131 // If there are entries in ForwardRefBlockAddresses at this point, they are
132 // references after the function was defined. Resolve those now.
133 while (!ForwardRefBlockAddresses.empty()) {
134 // Okay, we are referencing an already-parsed function, resolve them now.
135 Function *TheFn = 0;
136 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
137 if (Fn.Kind == ValID::t_GlobalName)
138 TheFn = M->getFunction(Fn.StrVal);
139 else if (Fn.UIntVal < NumberedVals.size())
140 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000141
Chris Lattner3432c622009-10-28 03:39:23 +0000142 if (TheFn == 0)
143 return Error(Fn.Loc, "unknown function referenced by blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000144
Chris Lattner3432c622009-10-28 03:39:23 +0000145 // Resolve all these references.
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000146 if (ResolveForwardRefBlockAddresses(TheFn,
Chris Lattner3432c622009-10-28 03:39:23 +0000147 ForwardRefBlockAddresses.begin()->second,
148 0))
149 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000150
Chris Lattner3432c622009-10-28 03:39:23 +0000151 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
152 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000153
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000154 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
155 if (NumberedTypes[i].second.isValid())
156 return Error(NumberedTypes[i].second,
157 "use of undefined type '%" + Twine(i) + "'");
158
159 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
160 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
161 if (I->second.second.isValid())
162 return Error(I->second.second,
163 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000164
Chris Lattnerac161bf2009-01-02 07:01:27 +0000165 if (!ForwardRefVals.empty())
166 return Error(ForwardRefVals.begin()->second.second,
167 "use of undefined value '@" + ForwardRefVals.begin()->first +
168 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000169
Chris Lattnerac161bf2009-01-02 07:01:27 +0000170 if (!ForwardRefValIDs.empty())
171 return Error(ForwardRefValIDs.begin()->second.second,
172 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000173 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000174
Devang Pateld2541152009-07-08 19:23:54 +0000175 if (!ForwardRefMDNodes.empty())
176 return Error(ForwardRefMDNodes.begin()->second.second,
177 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000178 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000179
Devang Pateld2541152009-07-08 19:23:54 +0000180
Chris Lattnerac161bf2009-01-02 07:01:27 +0000181 // Look for intrinsic functions and CallInst that need to be upgraded
182 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
183 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000184
Manman Ren8b4306c2013-12-02 21:29:56 +0000185 UpgradeDebugInfo(*M);
186
Chris Lattnerac161bf2009-01-02 07:01:27 +0000187 return false;
188}
189
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000190bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
Chris Lattner3432c622009-10-28 03:39:23 +0000191 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
192 PerFunctionState *PFS) {
193 // Loop over all the references, resolving them.
194 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
195 BasicBlock *Res;
Chris Lattneraa99c942009-11-01 01:27:45 +0000196 if (PFS) {
Chris Lattner3432c622009-10-28 03:39:23 +0000197 if (Refs[i].first.Kind == ValID::t_LocalName)
198 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattneraa99c942009-11-01 01:27:45 +0000199 else
Chris Lattner3432c622009-10-28 03:39:23 +0000200 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
201 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
202 return Error(Refs[i].first.Loc,
Chris Lattnera38a4df2009-11-02 18:28:45 +0000203 "cannot take address of numeric label after the function is defined");
Chris Lattner3432c622009-10-28 03:39:23 +0000204 } else {
205 Res = dyn_cast_or_null<BasicBlock>(
206 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
207 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000208
Chris Lattneraa99c942009-11-01 01:27:45 +0000209 if (Res == 0)
Chris Lattner3432c622009-10-28 03:39:23 +0000210 return Error(Refs[i].first.Loc,
211 "referenced value is not a basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000212
Chris Lattner3432c622009-10-28 03:39:23 +0000213 // Get the BlockAddress for this and update references to use it.
214 BlockAddress *BA = BlockAddress::get(TheFn, Res);
215 Refs[i].second->replaceAllUsesWith(BA);
216 Refs[i].second->eraseFromParent();
217 }
218 return false;
219}
220
221
Chris Lattnerac161bf2009-01-02 07:01:27 +0000222//===----------------------------------------------------------------------===//
223// Top-Level Entities
224//===----------------------------------------------------------------------===//
225
226bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000227 while (1) {
228 switch (Lex.getKind()) {
229 default: return TokError("expected top-level entity");
230 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000231 case lltok::kw_declare: if (ParseDeclare()) return true; break;
232 case lltok::kw_define: if (ParseDefine()) return true; break;
233 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
234 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000235 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000236 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000237 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000238 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000239 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000240 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000241 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000242
243 // The Global variable production with no name can have many different
244 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000245 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
246 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000247 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000248 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000249 case lltok::kw_internal: // OptionalLinkage
Saleem Abdulrasoolc1281352014-04-05 20:51:58 +0000250 case lltok::kw_linker_private: // Obsolete OptionalLinkage
251 case lltok::kw_linker_private_weak: // Obsolete OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000252 case lltok::kw_weak: // OptionalLinkage
253 case lltok::kw_weak_odr: // OptionalLinkage
254 case lltok::kw_linkonce: // OptionalLinkage
255 case lltok::kw_linkonce_odr: // OptionalLinkage
256 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000257 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000258 case lltok::kw_extern_weak: // OptionalLinkage
259 case lltok::kw_external: { // OptionalLinkage
Nico Rieck7157bb72014-01-14 15:22:47 +0000260 unsigned Linkage, Visibility, DLLStorageClass;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000261 if (ParseOptionalLinkage(Linkage) ||
262 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000263 ParseOptionalDLLStorageClass(DLLStorageClass) ||
264 ParseGlobal("", SMLoc(), Linkage, true, Visibility, DLLStorageClass))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000265 return true;
266 break;
267 }
268 case lltok::kw_default: // OptionalVisibility
269 case lltok::kw_hidden: // OptionalVisibility
270 case lltok::kw_protected: { // OptionalVisibility
Nico Rieck7157bb72014-01-14 15:22:47 +0000271 unsigned Visibility, DLLStorageClass;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000272 if (ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000273 ParseOptionalDLLStorageClass(DLLStorageClass) ||
274 ParseGlobal("", SMLoc(), 0, false, Visibility, DLLStorageClass))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000275 return true;
276 break;
277 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000278
Chris Lattnerac161bf2009-01-02 07:01:27 +0000279 case lltok::kw_thread_local: // OptionalThreadLocal
280 case lltok::kw_addrspace: // OptionalAddrSpace
281 case lltok::kw_constant: // GlobalType
282 case lltok::kw_global: // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000283 if (ParseGlobal("", SMLoc(), 0, false, 0, 0)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000284 break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000285
286 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000287 }
288 }
289}
290
291
292/// toplevelentity
293/// ::= 'module' 'asm' STRINGCONSTANT
294bool LLParser::ParseModuleAsm() {
295 assert(Lex.getKind() == lltok::kw_module);
296 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000297
298 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000299 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
300 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000301
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000302 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000303 return false;
304}
305
306/// toplevelentity
307/// ::= 'target' 'triple' '=' STRINGCONSTANT
308/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
309bool LLParser::ParseTargetDefinition() {
310 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000311 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000312 switch (Lex.Lex()) {
313 default: return TokError("unknown target property");
314 case lltok::kw_triple:
315 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000316 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
317 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000318 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000319 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000320 return false;
321 case lltok::kw_datalayout:
322 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000323 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
324 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000325 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000326 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000327 return false;
328 }
329}
330
Bill Wendling706d3d62012-11-28 08:41:48 +0000331/// toplevelentity
332/// ::= 'deplibs' '=' '[' ']'
333/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
334/// FIXME: Remove in 4.0. Currently parse, but ignore.
335bool LLParser::ParseDepLibs() {
336 assert(Lex.getKind() == lltok::kw_deplibs);
337 Lex.Lex();
338 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
339 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
340 return true;
341
342 if (EatIfPresent(lltok::rsquare))
343 return false;
344
345 do {
346 std::string Str;
347 if (ParseStringConstant(Str)) return true;
348 } while (EatIfPresent(lltok::comma));
349
350 return ParseToken(lltok::rsquare, "expected ']' at end of list");
351}
352
Dan Gohman466876b2009-08-12 23:32:33 +0000353/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000354/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000355bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000356 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000357 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000358 Lex.Lex(); // eat LocalVarID;
359
360 if (ParseToken(lltok::equal, "expected '=' after name") ||
361 ParseToken(lltok::kw_type, "expected 'type' after '='"))
362 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000363
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000364 if (TypeID >= NumberedTypes.size())
365 NumberedTypes.resize(TypeID+1);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000366
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000367 Type *Result = 0;
368 if (ParseStructDefinition(TypeLoc, "",
369 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000370
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000371 if (!isa<StructType>(Result)) {
372 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
373 if (Entry.first)
374 return Error(TypeLoc, "non-struct types may not be recursive");
375 Entry.first = Result;
376 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000377 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000378
Chris Lattnerac161bf2009-01-02 07:01:27 +0000379 return false;
380}
381
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000382
Chris Lattnerac161bf2009-01-02 07:01:27 +0000383/// toplevelentity
384/// ::= LocalVar '=' 'type' type
385bool LLParser::ParseNamedType() {
386 std::string Name = Lex.getStrVal();
387 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000388 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000389
Chris Lattner3822f632009-01-02 08:05:26 +0000390 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000391 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000392 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000393
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000394 Type *Result = 0;
395 if (ParseStructDefinition(NameLoc, Name,
396 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000397
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000398 if (!isa<StructType>(Result)) {
399 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
400 if (Entry.first)
401 return Error(NameLoc, "non-struct types may not be recursive");
402 Entry.first = Result;
403 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000404 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000405
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000406 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000407}
408
409
410/// toplevelentity
411/// ::= 'declare' FunctionHeader
412bool LLParser::ParseDeclare() {
413 assert(Lex.getKind() == lltok::kw_declare);
414 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000415
Chris Lattnerac161bf2009-01-02 07:01:27 +0000416 Function *F;
417 return ParseFunctionHeader(F, false);
418}
419
420/// toplevelentity
421/// ::= 'define' FunctionHeader '{' ...
422bool LLParser::ParseDefine() {
423 assert(Lex.getKind() == lltok::kw_define);
424 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000425
Chris Lattnerac161bf2009-01-02 07:01:27 +0000426 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000427 return ParseFunctionHeader(F, true) ||
428 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000429}
430
Chris Lattner3822f632009-01-02 08:05:26 +0000431/// ParseGlobalType
432/// ::= 'constant'
433/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000434bool LLParser::ParseGlobalType(bool &IsConstant) {
435 if (Lex.getKind() == lltok::kw_constant)
436 IsConstant = true;
437 else if (Lex.getKind() == lltok::kw_global)
438 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000439 else {
440 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000441 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000442 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000443 Lex.Lex();
444 return false;
445}
446
Dan Gohman466876b2009-08-12 23:32:33 +0000447/// ParseUnnamedGlobal:
448/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000449/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
450/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000451/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000452/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
453/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000454bool LLParser::ParseUnnamedGlobal() {
455 unsigned VarID = NumberedVals.size();
456 std::string Name;
457 LocTy NameLoc = Lex.getLoc();
458
459 // Handle the GlobalID form.
460 if (Lex.getKind() == lltok::GlobalID) {
461 if (Lex.getUIntVal() != VarID)
462 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000463 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000464 Lex.Lex(); // eat GlobalID;
465
466 if (ParseToken(lltok::equal, "expected '=' after name"))
467 return true;
468 }
469
470 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000471 unsigned Linkage, Visibility, DLLStorageClass;
Dan Gohman466876b2009-08-12 23:32:33 +0000472 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000473 ParseOptionalVisibility(Visibility) ||
474 ParseOptionalDLLStorageClass(DLLStorageClass))
Dan Gohman466876b2009-08-12 23:32:33 +0000475 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000476
Dan Gohman466876b2009-08-12 23:32:33 +0000477 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000478 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
479 DLLStorageClass);
480 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass);
Dan Gohman466876b2009-08-12 23:32:33 +0000481}
482
Chris Lattnerac161bf2009-01-02 07:01:27 +0000483/// ParseNamedGlobal:
484/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000485/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
486/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000487bool LLParser::ParseNamedGlobal() {
488 assert(Lex.getKind() == lltok::GlobalVar);
489 LocTy NameLoc = Lex.getLoc();
490 std::string Name = Lex.getStrVal();
491 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000492
Chris Lattnerac161bf2009-01-02 07:01:27 +0000493 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000494 unsigned Linkage, Visibility, DLLStorageClass;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000495 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
496 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000497 ParseOptionalVisibility(Visibility) ||
498 ParseOptionalDLLStorageClass(DLLStorageClass))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000499 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000500
Chris Lattnerac161bf2009-01-02 07:01:27 +0000501 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000502 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
503 DLLStorageClass);
504 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000505}
506
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000507// MDString:
508// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000509bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000510 std::string Str;
511 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000512 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000513 return false;
514}
515
516// MDNode:
517// ::= '!' MDNodeNumber
Chris Lattner8eff0152010-04-01 05:14:45 +0000518//
519/// This version of ParseMDNodeID returns the slot number and null in the case
520/// of a forward reference.
521bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
522 // !{ ..., !42, ... }
523 if (ParseUInt32(SlotNo)) return true;
524
525 // Check existing MDNode.
526 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
527 Result = NumberedMetadata[SlotNo];
528 else
529 Result = 0;
530 return false;
531}
532
Chris Lattner6dac02a2009-12-30 04:15:23 +0000533bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000534 // !{ ..., !42, ... }
535 unsigned MID = 0;
Chris Lattner8eff0152010-04-01 05:14:45 +0000536 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000537
Chris Lattner8eff0152010-04-01 05:14:45 +0000538 // If not a forward reference, just return it now.
539 if (Result) return false;
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000540
Chris Lattner8eff0152010-04-01 05:14:45 +0000541 // Otherwise, create MDNode forward reference.
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000542 MDNode *FwdNode = MDNode::getTemporary(Context, None);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000543 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000544
Chris Lattnerfc58af22009-12-30 04:51:58 +0000545 if (NumberedMetadata.size() <= MID)
546 NumberedMetadata.resize(MID+1);
547 NumberedMetadata[MID] = FwdNode;
Chris Lattner1797fc72009-12-29 21:53:55 +0000548 Result = FwdNode;
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000549 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000550}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000551
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000552/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000553/// !foo = !{ !1, !2 }
554bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000555 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000556 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000557 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000558
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000559 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000560 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000561 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000562 return true;
563
Dan Gohman2637cc12010-07-21 23:38:33 +0000564 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000565 if (Lex.getKind() != lltok::rbrace)
566 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000567 if (ParseToken(lltok::exclaim, "Expected '!' here"))
568 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000569
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000570 MDNode *N = 0;
571 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000572 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000573 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000574
575 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
576 return true;
577
Devang Patelbe626972009-07-29 00:34:02 +0000578 return false;
579}
580
Devang Patel39e64d42009-07-01 19:21:12 +0000581/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000582/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000583bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000584 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000585 Lex.Lex();
586 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000587
588 LocTy TyLoc;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000589 Type *Ty = 0;
Devang Patele059ba6e2009-07-23 01:07:34 +0000590 SmallVector<Value *, 16> Elts;
Chris Lattner278bc952009-12-29 22:40:21 +0000591 if (ParseUInt32(MetadataID) ||
592 ParseToken(lltok::equal, "expected '=' here") ||
593 ParseType(Ty, TyLoc) ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000594 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner278bc952009-12-29 22:40:21 +0000595 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandezb8fd1522010-01-10 07:14:18 +0000596 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner278bc952009-12-29 22:40:21 +0000597 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patele059ba6e2009-07-23 01:07:34 +0000598 return true;
599
Jay Foad5514afe2011-04-21 19:59:31 +0000600 MDNode *Init = MDNode::get(Context, Elts);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000601
Chris Lattnerfc58af22009-12-30 04:51:58 +0000602 // See if this was forward referenced, if so, handle it.
Chris Lattner218b22f2009-12-29 21:43:58 +0000603 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Pateld2541152009-07-08 19:23:54 +0000604 FI = ForwardRefMDNodes.find(MetadataID);
605 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman16a5d982010-08-20 22:02:26 +0000606 MDNode *Temp = FI->second.first;
607 Temp->replaceAllUsesWith(Init);
608 MDNode::deleteTemporary(Temp);
Devang Pateld2541152009-07-08 19:23:54 +0000609 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000610
Chris Lattnerfc58af22009-12-30 04:51:58 +0000611 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
612 } else {
613 if (MetadataID >= NumberedMetadata.size())
614 NumberedMetadata.resize(MetadataID+1);
615
616 if (NumberedMetadata[MetadataID] != 0)
617 return TokError("Metadata id is already used");
618 NumberedMetadata[MetadataID] = Init;
Devang Pateld2541152009-07-08 19:23:54 +0000619 }
620
Devang Patel39e64d42009-07-01 19:21:12 +0000621 return false;
622}
623
Chris Lattnerac161bf2009-01-02 07:01:27 +0000624/// ParseAlias:
Nico Rieck7157bb72014-01-14 15:22:47 +0000625/// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass 'alias'
626/// OptionalLinkage Aliasee
Chris Lattnerac161bf2009-01-02 07:01:27 +0000627/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000628/// ::= TypeAndValue
629/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohman1639c392009-07-27 21:53:46 +0000630/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000631///
Nico Rieck7157bb72014-01-14 15:22:47 +0000632/// Everything through DLL storage class has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000633///
634bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
Nico Rieck7157bb72014-01-14 15:22:47 +0000635 unsigned Visibility, unsigned DLLStorageClass) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000636 assert(Lex.getKind() == lltok::kw_alias);
637 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000638 LocTy LinkageLoc = Lex.getLoc();
Rafael Espindola78527052013-10-06 15:10:43 +0000639 unsigned L;
640 if (ParseOptionalLinkage(L))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000641 return true;
642
Rafael Espindola78527052013-10-06 15:10:43 +0000643 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
644
Rafael Espindolacaa43562013-10-09 16:07:32 +0000645 if(!GlobalAlias::isValidLinkage(Linkage))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000646 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000647
Chris Lattnerac161bf2009-01-02 07:01:27 +0000648 Constant *Aliasee;
649 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000650 if (Lex.getKind() != lltok::kw_bitcast &&
651 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000652 if (ParseGlobalTypeAndValue(Aliasee)) return true;
653 } else {
654 // The bitcast dest type is not present, it is implied by the dest type.
655 ValID ID;
656 if (ParseValID(ID)) return true;
657 if (ID.Kind != ValID::t_Constant)
658 return Error(AliaseeLoc, "invalid aliasee");
659 Aliasee = ID.ConstantVal;
660 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000661
Duncan Sands19d0b472010-02-16 11:11:14 +0000662 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +0000663 return Error(AliaseeLoc, "alias must have pointer type");
664
665 // Okay, create the alias but do not insert it into the module yet.
666 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
667 (GlobalValue::LinkageTypes)Linkage, Name,
668 Aliasee);
669 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000670 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000671
Chris Lattnerac161bf2009-01-02 07:01:27 +0000672 // See if this value already exists in the symbol table. If so, it is either
673 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000674 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000675 // See if this was a redefinition. If so, there is no entry in
676 // ForwardRefVals.
677 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
678 I = ForwardRefVals.find(Name);
679 if (I == ForwardRefVals.end())
680 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
681
682 // Otherwise, this was a definition of forward ref. Verify that types
683 // agree.
684 if (Val->getType() != GA->getType())
685 return Error(NameLoc,
686 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000687
Chris Lattnerac161bf2009-01-02 07:01:27 +0000688 // If they agree, just RAUW the old value with the alias and remove the
689 // forward ref info.
690 Val->replaceAllUsesWith(GA);
691 Val->eraseFromParent();
692 ForwardRefVals.erase(I);
693 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000694
Chris Lattnerac161bf2009-01-02 07:01:27 +0000695 // Insert into the module, we know its name won't collide now.
696 M->getAliasList().push_back(GA);
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000697 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000698
Chris Lattnerac161bf2009-01-02 07:01:27 +0000699 return false;
700}
701
702/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000703/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
704/// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000705/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000706/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
707/// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000708/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000709///
David Majnemerc4ab61c2014-03-09 06:41:58 +0000710/// Everything up to and including OptionalDLLStorageClass has been parsed
711/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000712///
713bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
714 unsigned Linkage, bool HasLinkage,
Nico Rieck7157bb72014-01-14 15:22:47 +0000715 unsigned Visibility, unsigned DLLStorageClass) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000716 unsigned AddrSpace;
Shuxin Yang2e1890e2013-10-27 03:08:44 +0000717 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000718 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola026d1522011-01-13 01:30:30 +0000719 LocTy UnnamedAddrLoc;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000720 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000721 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000722
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000723 Type *Ty = 0;
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000724 if (ParseOptionalThreadLocal(TLM) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000725 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindola026d1522011-01-13 01:30:30 +0000726 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
727 &UnnamedAddrLoc) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000728 ParseOptionalToken(lltok::kw_externally_initialized,
729 IsExternallyInitialized,
730 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000731 ParseGlobalType(IsConstant) ||
732 ParseType(Ty, TyLoc))
733 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000734
Chris Lattnerac161bf2009-01-02 07:01:27 +0000735 // If the linkage is specified and is external, then no initializer is
736 // present.
737 Constant *Init = 0;
Nico Rieck7157bb72014-01-14 15:22:47 +0000738 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000739 Linkage != GlobalValue::ExternalLinkage)) {
740 if (ParseGlobalValue(Ty, Init))
741 return true;
742 }
743
Duncan Sands19d0b472010-02-16 11:11:14 +0000744 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000745 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000746
Chris Lattnerac161bf2009-01-02 07:01:27 +0000747 GlobalVariable *GV = 0;
748
749 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000750 if (!Name.empty()) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000751 if (GlobalValue *GVal = M->getNamedValue(Name)) {
752 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
753 return Error(NameLoc, "redefinition of global '@" + Name + "'");
754 GV = cast<GlobalVariable>(GVal);
755 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000756 } else {
757 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
758 I = ForwardRefValIDs.find(NumberedVals.size());
759 if (I != ForwardRefValIDs.end()) {
760 GV = cast<GlobalVariable>(I->second.first);
761 ForwardRefValIDs.erase(I);
762 }
763 }
764
765 if (GV == 0) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000766 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000767 Name, 0, GlobalVariable::NotThreadLocal,
768 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000769 } else {
770 if (GV->getType()->getElementType() != Ty)
771 return Error(TyLoc,
772 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000773
Chris Lattnerac161bf2009-01-02 07:01:27 +0000774 // Move the forward-reference to the correct spot in the module.
775 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
776 }
777
778 if (Name.empty())
779 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000780
Chris Lattnerac161bf2009-01-02 07:01:27 +0000781 // Set the parsed properties on the global.
782 if (Init)
783 GV->setInitializer(Init);
784 GV->setConstant(IsConstant);
785 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
786 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000787 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000788 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000789 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000790 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000791
Chris Lattnerac161bf2009-01-02 07:01:27 +0000792 // Parse attributes on the global.
793 while (Lex.getKind() == lltok::comma) {
794 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000795
Chris Lattnerac161bf2009-01-02 07:01:27 +0000796 if (Lex.getKind() == lltok::kw_section) {
797 Lex.Lex();
798 GV->setSection(Lex.getStrVal());
799 if (ParseToken(lltok::StringConstant, "expected global section string"))
800 return true;
801 } else if (Lex.getKind() == lltok::kw_align) {
802 unsigned Alignment;
803 if (ParseOptionalAlignment(Alignment)) return true;
804 GV->setAlignment(Alignment);
805 } else {
806 TokError("unknown global variable property!");
807 }
808 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000809
Chris Lattnerac161bf2009-01-02 07:01:27 +0000810 return false;
811}
812
Bill Wendling63b88192013-02-06 06:52:58 +0000813/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000814/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000815bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000816 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000817 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000818 Lex.Lex();
819
820 assert(Lex.getKind() == lltok::AttrGrpID);
Bill Wendling63b88192013-02-06 06:52:58 +0000821 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000822 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000823 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000824 Lex.Lex();
825
826 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000827 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000828 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000829 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000830 ParseToken(lltok::rbrace, "expected end of attribute group"))
831 return true;
832
Bill Wendlingb32b0412013-02-08 06:32:06 +0000833 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000834 return Error(AttrGrpLoc, "attribute group has no attributes");
835
836 return false;
837}
838
Bill Wendling8b0321d2013-02-08 00:52:31 +0000839/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000840/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000841bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
842 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000843 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000844 bool HaveError = false;
845
846 B.clear();
847
Bill Wendling63b88192013-02-06 06:52:58 +0000848 while (true) {
849 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000850 if (Token == lltok::kw_builtin)
851 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000852 switch (Token) {
853 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000854 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000855 return Error(Lex.getLoc(), "unterminated attribute group");
856 case lltok::rbrace:
857 // Finished.
858 return false;
859
Bill Wendlingb32b0412013-02-08 06:32:06 +0000860 case lltok::AttrGrpID: {
861 // Allow a function to reference an attribute group:
862 //
863 // define void @foo() #1 { ... }
864 if (inAttrGrp)
865 HaveError |=
866 Error(Lex.getLoc(),
867 "cannot have an attribute group reference in an attribute group");
868
869 unsigned AttrGrpNum = Lex.getUIntVal();
870 if (inAttrGrp) break;
871
872 // Save the reference to the attribute group. We'll fill it in later.
873 FwdRefAttrGrps.push_back(AttrGrpNum);
874 break;
875 }
Bill Wendling63b88192013-02-06 06:52:58 +0000876 // Target-dependent attributes:
877 case lltok::StringConstant: {
878 std::string Attr = Lex.getStrVal();
879 Lex.Lex();
880 std::string Val;
881 if (EatIfPresent(lltok::equal) &&
882 ParseStringConstant(Val))
883 return true;
884
885 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000886 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000887 }
888
889 // Target-independent attributes:
890 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000891 // As a hack, we allow function alignment to be initially parsed as an
892 // attribute on a function declaration/definition or added to an attribute
893 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000894 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000895 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000896 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000897 if (ParseToken(lltok::equal, "expected '=' here") ||
898 ParseUInt32(Alignment))
899 return true;
900 } else {
901 if (ParseOptionalAlignment(Alignment))
902 return true;
903 }
Bill Wendling63b88192013-02-06 06:52:58 +0000904 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000905 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000906 }
907 case lltok::kw_alignstack: {
908 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000909 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000910 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000911 if (ParseToken(lltok::equal, "expected '=' here") ||
912 ParseUInt32(Alignment))
913 return true;
914 } else {
915 if (ParseOptionalStackAlignment(Alignment))
916 return true;
917 }
Bill Wendling63b88192013-02-06 06:52:58 +0000918 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000919 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000920 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000921 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000922 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000923 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000924 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
925 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
926 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
927 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
928 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
929 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
930 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
931 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
932 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
933 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
934 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000935 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000936 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
937 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
938 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
939 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
940 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
941 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
942 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
943 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
944 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
945 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
946 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000947
948 // Error handling.
949 case lltok::kw_inreg:
950 case lltok::kw_signext:
951 case lltok::kw_zeroext:
952 HaveError |=
953 Error(Lex.getLoc(),
954 "invalid use of attribute on a function");
955 break;
956 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +0000957 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000958 case lltok::kw_nest:
959 case lltok::kw_noalias:
960 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +0000961 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000962 case lltok::kw_sret:
963 HaveError |=
964 Error(Lex.getLoc(),
965 "invalid use of parameter-only attribute on a function");
966 break;
Bill Wendling63b88192013-02-06 06:52:58 +0000967 }
968
969 Lex.Lex();
970 }
971}
Chris Lattnerac161bf2009-01-02 07:01:27 +0000972
973//===----------------------------------------------------------------------===//
974// GlobalValue Reference/Resolution Routines.
975//===----------------------------------------------------------------------===//
976
977/// GetGlobalVal - Get a value with the specified name or ID, creating a
978/// forward reference record if needed. This can return null if the value
979/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +0000980GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +0000981 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +0000982 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000983 if (PTy == 0) {
984 Error(Loc, "global variable reference must have pointer type");
985 return 0;
986 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000987
Chris Lattnerac161bf2009-01-02 07:01:27 +0000988 // Look this name up in the normal function symbol table.
989 GlobalValue *Val =
990 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000991
Chris Lattnerac161bf2009-01-02 07:01:27 +0000992 // If this is a forward reference for the value, see if we already created a
993 // forward ref record.
994 if (Val == 0) {
995 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
996 I = ForwardRefVals.find(Name);
997 if (I != ForwardRefVals.end())
998 Val = I->second.first;
999 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001000
Chris Lattnerac161bf2009-01-02 07:01:27 +00001001 // If we have the value in the symbol table or fwd-ref table, return it.
1002 if (Val) {
1003 if (Val->getType() == Ty) return Val;
1004 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001005 getTypeString(Val->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001006 return 0;
1007 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001008
Chris Lattnerac161bf2009-01-02 07:01:27 +00001009 // Otherwise, create a new forward reference for this value and remember it.
1010 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001011 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001012 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001013 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001014 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001015 GlobalValue::ExternalWeakLinkage, 0, Name,
1016 0, GlobalVariable::NotThreadLocal,
1017 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001018
Chris Lattnerac161bf2009-01-02 07:01:27 +00001019 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1020 return FwdVal;
1021}
1022
Chris Lattner229907c2011-07-18 04:54:35 +00001023GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1024 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001025 if (PTy == 0) {
1026 Error(Loc, "global variable reference must have pointer type");
1027 return 0;
1028 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001029
Chris Lattnerac161bf2009-01-02 07:01:27 +00001030 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001031
Chris Lattnerac161bf2009-01-02 07:01:27 +00001032 // If this is a forward reference for the value, see if we already created a
1033 // forward ref record.
1034 if (Val == 0) {
1035 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1036 I = ForwardRefValIDs.find(ID);
1037 if (I != ForwardRefValIDs.end())
1038 Val = I->second.first;
1039 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001040
Chris Lattnerac161bf2009-01-02 07:01:27 +00001041 // If we have the value in the symbol table or fwd-ref table, return it.
1042 if (Val) {
1043 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001044 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001045 getTypeString(Val->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001046 return 0;
1047 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001048
Chris Lattnerac161bf2009-01-02 07:01:27 +00001049 // Otherwise, create a new forward reference for this value and remember it.
1050 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001051 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001052 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001053 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001054 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1055 GlobalValue::ExternalWeakLinkage, 0, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001056
Chris Lattnerac161bf2009-01-02 07:01:27 +00001057 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1058 return FwdVal;
1059}
1060
1061
1062//===----------------------------------------------------------------------===//
1063// Helper Routines.
1064//===----------------------------------------------------------------------===//
1065
1066/// ParseToken - If the current token has the specified kind, eat it and return
1067/// success. Otherwise, emit the specified error and return failure.
1068bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1069 if (Lex.getKind() != T)
1070 return TokError(ErrMsg);
1071 Lex.Lex();
1072 return false;
1073}
1074
Chris Lattner3822f632009-01-02 08:05:26 +00001075/// ParseStringConstant
1076/// ::= StringConstant
1077bool LLParser::ParseStringConstant(std::string &Result) {
1078 if (Lex.getKind() != lltok::StringConstant)
1079 return TokError("expected string constant");
1080 Result = Lex.getStrVal();
1081 Lex.Lex();
1082 return false;
1083}
1084
1085/// ParseUInt32
1086/// ::= uint32
1087bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001088 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1089 return TokError("expected integer");
1090 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1091 if (Val64 != unsigned(Val64))
1092 return TokError("expected 32-bit integer (too large)");
1093 Val = Val64;
1094 Lex.Lex();
1095 return false;
1096}
1097
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001098/// ParseTLSModel
1099/// := 'localdynamic'
1100/// := 'initialexec'
1101/// := 'localexec'
1102bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1103 switch (Lex.getKind()) {
1104 default:
1105 return TokError("expected localdynamic, initialexec or localexec");
1106 case lltok::kw_localdynamic:
1107 TLM = GlobalVariable::LocalDynamicTLSModel;
1108 break;
1109 case lltok::kw_initialexec:
1110 TLM = GlobalVariable::InitialExecTLSModel;
1111 break;
1112 case lltok::kw_localexec:
1113 TLM = GlobalVariable::LocalExecTLSModel;
1114 break;
1115 }
1116
1117 Lex.Lex();
1118 return false;
1119}
1120
1121/// ParseOptionalThreadLocal
1122/// := /*empty*/
1123/// := 'thread_local'
1124/// := 'thread_local' '(' tlsmodel ')'
1125bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1126 TLM = GlobalVariable::NotThreadLocal;
1127 if (!EatIfPresent(lltok::kw_thread_local))
1128 return false;
1129
1130 TLM = GlobalVariable::GeneralDynamicTLSModel;
1131 if (Lex.getKind() == lltok::lparen) {
1132 Lex.Lex();
1133 return ParseTLSModel(TLM) ||
1134 ParseToken(lltok::rparen, "expected ')' after thread local model");
1135 }
1136 return false;
1137}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001138
1139/// ParseOptionalAddrSpace
1140/// := /*empty*/
1141/// := 'addrspace' '(' uint32 ')'
1142bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1143 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001144 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001145 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001146 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001147 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001148 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001149}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001150
Bill Wendling34c2eb22012-12-04 23:40:58 +00001151/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1152bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1153 bool HaveError = false;
1154
1155 B.clear();
1156
1157 while (1) {
1158 lltok::Kind Token = Lex.getKind();
1159 switch (Token) {
1160 default: // End of attributes.
1161 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001162 case lltok::kw_align: {
1163 unsigned Alignment;
1164 if (ParseOptionalAlignment(Alignment))
1165 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001166 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001167 continue;
1168 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001169 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Reid Klecknera534a382013-12-19 02:14:12 +00001170 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001171 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1172 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1173 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1174 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001175 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1176 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001177 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001178 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1179 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1180 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001181
Stephen Lin7577ed52013-04-20 13:16:13 +00001182 case lltok::kw_alignstack:
1183 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001184 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001185 case lltok::kw_inlinehint:
1186 case lltok::kw_minsize:
1187 case lltok::kw_naked:
1188 case lltok::kw_nobuiltin:
1189 case lltok::kw_noduplicate:
1190 case lltok::kw_noimplicitfloat:
1191 case lltok::kw_noinline:
1192 case lltok::kw_nonlazybind:
1193 case lltok::kw_noredzone:
1194 case lltok::kw_noreturn:
1195 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001196 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001197 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001198 case lltok::kw_returns_twice:
1199 case lltok::kw_sanitize_address:
1200 case lltok::kw_sanitize_memory:
1201 case lltok::kw_sanitize_thread:
1202 case lltok::kw_ssp:
1203 case lltok::kw_sspreq:
1204 case lltok::kw_sspstrong:
1205 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001206 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1207 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001208 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001209
Bill Wendling34c2eb22012-12-04 23:40:58 +00001210 Lex.Lex();
1211 }
1212}
1213
1214/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1215bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1216 bool HaveError = false;
1217
1218 B.clear();
1219
1220 while (1) {
1221 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001222 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001223 default: // End of attributes.
1224 return HaveError;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001225 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1226 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1227 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1228 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001229
Bill Wendling34c2eb22012-12-04 23:40:58 +00001230 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001231 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001232 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001233 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001234 case lltok::kw_nest:
1235 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001236 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001237 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001238 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001239 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001240
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001241 case lltok::kw_alignstack:
1242 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001243 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001244 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001245 case lltok::kw_inlinehint:
1246 case lltok::kw_minsize:
1247 case lltok::kw_naked:
1248 case lltok::kw_nobuiltin:
1249 case lltok::kw_noduplicate:
1250 case lltok::kw_noimplicitfloat:
1251 case lltok::kw_noinline:
1252 case lltok::kw_nonlazybind:
1253 case lltok::kw_noredzone:
1254 case lltok::kw_noreturn:
1255 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001256 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001257 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001258 case lltok::kw_returns_twice:
1259 case lltok::kw_sanitize_address:
1260 case lltok::kw_sanitize_memory:
1261 case lltok::kw_sanitize_thread:
1262 case lltok::kw_ssp:
1263 case lltok::kw_sspreq:
1264 case lltok::kw_sspstrong:
1265 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001266 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001267 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001268
1269 case lltok::kw_readnone:
1270 case lltok::kw_readonly:
1271 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001272 }
1273
Chris Lattnerac161bf2009-01-02 07:01:27 +00001274 Lex.Lex();
1275 }
1276}
1277
1278/// ParseOptionalLinkage
1279/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001280/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001281/// ::= 'internal'
1282/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001283/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001284/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001285/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001286/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001287/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001288/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001289/// ::= 'extern_weak'
1290/// ::= 'external'
Saleem Abdulrasoolc1281352014-04-05 20:51:58 +00001291///
1292/// Deprecated Values:
1293/// ::= 'linker_private'
1294/// ::= 'linker_private_weak'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001295bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1296 HasLinkage = false;
1297 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001298 default: Res=GlobalValue::ExternalLinkage; return false;
1299 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001300 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1301 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1302 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1303 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1304 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001305 case lltok::kw_available_externally:
1306 Res = GlobalValue::AvailableExternallyLinkage;
1307 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001308 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001309 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001310 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1311 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Saleem Abdulrasoolc1281352014-04-05 20:51:58 +00001312
1313 case lltok::kw_linker_private:
1314 case lltok::kw_linker_private_weak:
Saleem Abdulrasoolefa31a92014-04-05 22:42:53 +00001315 Lex.Warning("'" + Lex.getStrVal() + "' is deprecated, treating as"
1316 " PrivateLinkage");
Saleem Abdulrasoolc1281352014-04-05 20:51:58 +00001317 Lex.Lex();
1318 // treat linker_private and linker_private_weak as PrivateLinkage
1319 Res = GlobalValue::PrivateLinkage;
1320 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001321 }
1322 Lex.Lex();
1323 HasLinkage = true;
1324 return false;
1325}
1326
1327/// ParseOptionalVisibility
1328/// ::= /*empty*/
1329/// ::= 'default'
1330/// ::= 'hidden'
1331/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001332///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001333bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1334 switch (Lex.getKind()) {
1335 default: Res = GlobalValue::DefaultVisibility; return false;
1336 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1337 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1338 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1339 }
1340 Lex.Lex();
1341 return false;
1342}
1343
Nico Rieck7157bb72014-01-14 15:22:47 +00001344/// ParseOptionalDLLStorageClass
1345/// ::= /*empty*/
1346/// ::= 'dllimport'
1347/// ::= 'dllexport'
1348///
1349bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1350 switch (Lex.getKind()) {
1351 default: Res = GlobalValue::DefaultStorageClass; return false;
1352 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1353 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1354 }
1355 Lex.Lex();
1356 return false;
1357}
1358
Chris Lattnerac161bf2009-01-02 07:01:27 +00001359/// ParseOptionalCallingConv
1360/// ::= /*empty*/
1361/// ::= 'ccc'
1362/// ::= 'fastcc'
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001363/// ::= 'kw_intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001364/// ::= 'coldcc'
1365/// ::= 'x86_stdcallcc'
1366/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001367/// ::= 'x86_thiscallcc'
Reid Kleckner1c843222014-01-31 17:41:22 +00001368/// ::= 'x86_cdeclmethodcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001369/// ::= 'arm_apcscc'
1370/// ::= 'arm_aapcscc'
1371/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001372/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001373/// ::= 'ptx_kernel'
1374/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001375/// ::= 'spir_func'
1376/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001377/// ::= 'x86_64_sysvcc'
1378/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001379/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001380/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001381/// ::= 'preserve_mostcc'
1382/// ::= 'preserve_allcc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001383/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001384///
Sandeep Patel68c5f472009-09-02 08:44:58 +00001385bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001386 switch (Lex.getKind()) {
1387 default: CC = CallingConv::C; return false;
1388 case lltok::kw_ccc: CC = CallingConv::C; break;
1389 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1390 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1391 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1392 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001393 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner1c843222014-01-31 17:41:22 +00001394 case lltok::kw_x86_cdeclmethodcc:CC = CallingConv::X86_CDeclMethod; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001395 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1396 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1397 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001398 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001399 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1400 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001401 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1402 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001403 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001404 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1405 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001406 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001407 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001408 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1409 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001410 case lltok::kw_cc: {
1411 unsigned ArbitraryCC;
1412 Lex.Lex();
David Blaikie46a9f012012-01-20 21:51:11 +00001413 if (ParseUInt32(ArbitraryCC))
Sandeep Patel68c5f472009-09-02 08:44:58 +00001414 return true;
David Blaikie46a9f012012-01-20 21:51:11 +00001415 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1416 return false;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001417 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001418 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001419
Chris Lattnerac161bf2009-01-02 07:01:27 +00001420 Lex.Lex();
1421 return false;
1422}
1423
Chris Lattner5c427632009-12-30 05:31:19 +00001424/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001425/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001426bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1427 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001428 do {
1429 if (Lex.getKind() != lltok::MetadataVar)
1430 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001431
Chris Lattner596760d2009-12-29 21:25:40 +00001432 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001433 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001434 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001435
Chris Lattner1797fc72009-12-29 21:53:55 +00001436 MDNode *Node;
Chris Lattner8eff0152010-04-01 05:14:45 +00001437 SMLoc Loc = Lex.getLoc();
Dan Gohmanc828c542010-08-24 02:24:03 +00001438
1439 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001440 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001441
Dan Gohmanf0715b12010-08-24 14:35:45 +00001442 // This code is similar to that of ParseMetadataValue, however it needs to
1443 // have special-case code for a forward reference; see the comments on
1444 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1445 // at the top level here.
Dan Gohmanc828c542010-08-24 02:24:03 +00001446 if (Lex.getKind() == lltok::lbrace) {
1447 ValID ID;
1448 if (ParseMetadataListValue(ID, PFS))
1449 return true;
1450 assert(ID.Kind == ValID::t_MDNode);
1451 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner8eff0152010-04-01 05:14:45 +00001452 } else {
Nick Lewycky912888f2010-09-30 21:04:13 +00001453 unsigned NodeID = 0;
Dan Gohmanc828c542010-08-24 02:24:03 +00001454 if (ParseMDNodeID(Node, NodeID))
1455 return true;
1456 if (Node) {
1457 // If we got the node, add it to the instruction.
1458 Inst->setMetadata(MDK, Node);
1459 } else {
1460 MDRef R = { Loc, MDK, NodeID };
1461 // Otherwise, remember that this should be resolved later.
1462 ForwardRefInstMetadata[Inst].push_back(R);
1463 }
Chris Lattner8eff0152010-04-01 05:14:45 +00001464 }
Chris Lattner596760d2009-12-29 21:25:40 +00001465
Manman Ren209b17c2013-09-28 00:22:27 +00001466 if (MDK == LLVMContext::MD_tbaa)
1467 InstsWithTBAATag.push_back(Inst);
1468
Chris Lattner596760d2009-12-29 21:25:40 +00001469 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001470 } while (EatIfPresent(lltok::comma));
1471 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001472}
1473
Chris Lattnerac161bf2009-01-02 07:01:27 +00001474/// ParseOptionalAlignment
1475/// ::= /* empty */
1476/// ::= 'align' 4
1477bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1478 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001479 if (!EatIfPresent(lltok::kw_align))
1480 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001481 LocTy AlignLoc = Lex.getLoc();
1482 if (ParseUInt32(Alignment)) return true;
1483 if (!isPowerOf2_32(Alignment))
1484 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001485 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001486 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001487 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001488}
1489
Chris Lattnerb2f39502009-12-30 05:44:30 +00001490/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001491/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001492/// ::= ',' align 4
1493///
1494/// This returns with AteExtraComma set to true if it ate an excess comma at the
1495/// end.
1496bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1497 bool &AteExtraComma) {
1498 AteExtraComma = false;
1499 while (EatIfPresent(lltok::comma)) {
1500 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001501 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001502 AteExtraComma = true;
1503 return false;
1504 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001505
Chris Lattner95b0ff42010-04-23 00:50:50 +00001506 if (Lex.getKind() != lltok::kw_align)
1507 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001508
Chris Lattner95b0ff42010-04-23 00:50:50 +00001509 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001510 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001511
Devang Patelea8a4b92009-09-17 23:04:48 +00001512 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001513}
1514
Eli Friedmanfee02c62011-07-25 23:16:38 +00001515/// ParseScopeAndOrdering
1516/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1517/// else: ::=
1518///
1519/// This sets Scope and Ordering to the parsed values.
1520bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1521 AtomicOrdering &Ordering) {
1522 if (!isAtomic)
1523 return false;
1524
1525 Scope = CrossThread;
1526 if (EatIfPresent(lltok::kw_singlethread))
1527 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001528
1529 return ParseOrdering(Ordering);
1530}
1531
1532/// ParseOrdering
1533/// ::= AtomicOrdering
1534///
1535/// This sets Ordering to the parsed value.
1536bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001537 switch (Lex.getKind()) {
1538 default: return TokError("Expected ordering on atomic instruction");
1539 case lltok::kw_unordered: Ordering = Unordered; break;
1540 case lltok::kw_monotonic: Ordering = Monotonic; break;
1541 case lltok::kw_acquire: Ordering = Acquire; break;
1542 case lltok::kw_release: Ordering = Release; break;
1543 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1544 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1545 }
1546 Lex.Lex();
1547 return false;
1548}
1549
Charles Davisbe5557e2010-02-12 00:31:15 +00001550/// ParseOptionalStackAlignment
1551/// ::= /* empty */
1552/// ::= 'alignstack' '(' 4 ')'
1553bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1554 Alignment = 0;
1555 if (!EatIfPresent(lltok::kw_alignstack))
1556 return false;
1557 LocTy ParenLoc = Lex.getLoc();
1558 if (!EatIfPresent(lltok::lparen))
1559 return Error(ParenLoc, "expected '('");
1560 LocTy AlignLoc = Lex.getLoc();
1561 if (ParseUInt32(Alignment)) return true;
1562 ParenLoc = Lex.getLoc();
1563 if (!EatIfPresent(lltok::rparen))
1564 return Error(ParenLoc, "expected ')'");
1565 if (!isPowerOf2_32(Alignment))
1566 return Error(AlignLoc, "stack alignment is not a power of two");
1567 return false;
1568}
Devang Patelea8a4b92009-09-17 23:04:48 +00001569
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001570/// ParseIndexList - This parses the index list for an insert/extractvalue
1571/// instruction. This sets AteExtraComma in the case where we eat an extra
1572/// comma at the end of the line and find that it is followed by metadata.
1573/// Clients that don't allow metadata can call the version of this function that
1574/// only takes one argument.
1575///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001576/// ParseIndexList
1577/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001578///
1579bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1580 bool &AteExtraComma) {
1581 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001582
Chris Lattnerac161bf2009-01-02 07:01:27 +00001583 if (Lex.getKind() != lltok::comma)
1584 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001585
Chris Lattner3822f632009-01-02 08:05:26 +00001586 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001587 if (Lex.getKind() == lltok::MetadataVar) {
1588 AteExtraComma = true;
1589 return false;
1590 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001591 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001592 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001593 Indices.push_back(Idx);
1594 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001595
Chris Lattnerac161bf2009-01-02 07:01:27 +00001596 return false;
1597}
1598
1599//===----------------------------------------------------------------------===//
1600// Type Parsing.
1601//===----------------------------------------------------------------------===//
1602
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001603/// ParseType - Parse a type.
1604bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1605 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001606 switch (Lex.getKind()) {
1607 default:
1608 return TokError("expected type");
1609 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001610 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001611 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001612 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001613 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001614 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001615 // Type ::= StructType
1616 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001617 return true;
1618 break;
1619 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001620 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001621 Lex.Lex(); // eat the lsquare.
1622 if (ParseArrayVectorType(Result, false))
1623 return true;
1624 break;
1625 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001626 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001627 Lex.Lex();
1628 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001629 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001630 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001631 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001632 } else if (ParseArrayVectorType(Result, true))
1633 return true;
1634 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001635 case lltok::LocalVar: {
1636 // Type ::= %foo
1637 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001638
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001639 // If the type hasn't been defined yet, create a forward definition and
1640 // remember where that forward def'n was seen (in case it never is defined).
1641 if (Entry.first == 0) {
Chris Lattner335d3992011-08-12 18:06:37 +00001642 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001643 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001644 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001645 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001646 Lex.Lex();
1647 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001648 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001649
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001650 case lltok::LocalVarID: {
1651 // Type ::= %4
1652 if (Lex.getUIntVal() >= NumberedTypes.size())
1653 NumberedTypes.resize(Lex.getUIntVal()+1);
1654 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001655
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001656 // If the type hasn't been defined yet, create a forward definition and
1657 // remember where that forward def'n was seen (in case it never is defined).
1658 if (Entry.first == 0) {
Chris Lattner335d3992011-08-12 18:06:37 +00001659 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001660 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001661 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001662 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001663 Lex.Lex();
1664 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001665 }
1666 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001667
1668 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001669 while (1) {
1670 switch (Lex.getKind()) {
1671 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001672 default:
1673 if (!AllowVoid && Result->isVoidTy())
1674 return Error(TypeLoc, "void type only allowed for function results");
1675 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001676
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001677 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001678 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001679 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001680 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001681 if (Result->isVoidTy())
1682 return TokError("pointers to void are invalid - use i8* instead");
1683 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001684 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001685 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001686 Lex.Lex();
1687 break;
1688
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001689 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001690 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001691 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001692 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001693 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001694 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001695 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001696 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001697 unsigned AddrSpace;
1698 if (ParseOptionalAddrSpace(AddrSpace) ||
1699 ParseToken(lltok::star, "expected '*' in address space"))
1700 return true;
1701
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001702 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001703 break;
1704 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001705
Chris Lattnerac161bf2009-01-02 07:01:27 +00001706 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1707 case lltok::lparen:
1708 if (ParseFunctionType(Result))
1709 return true;
1710 break;
1711 }
1712 }
1713}
1714
1715/// ParseParameterList
1716/// ::= '(' ')'
1717/// ::= '(' Arg (',' Arg)* ')'
1718/// Arg
1719/// ::= Type OptionalAttributes Value OptionalAttributes
1720bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1721 PerFunctionState &PFS) {
1722 if (ParseToken(lltok::lparen, "expected '(' in call"))
1723 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001724
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001725 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001726 while (Lex.getKind() != lltok::rparen) {
1727 // If this isn't the first argument, we need a comma.
1728 if (!ArgList.empty() &&
1729 ParseToken(lltok::comma, "expected ',' in argument list"))
1730 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001731
Chris Lattnerac161bf2009-01-02 07:01:27 +00001732 // Parse the argument.
1733 LocTy ArgLoc;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001734 Type *ArgTy = 0;
Bill Wendling50d27842012-10-15 20:35:56 +00001735 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001736 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001737 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001738 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001739
Chris Lattner5b4a9622009-12-30 02:11:14 +00001740 // Otherwise, handle normal operands.
Bill Wendling34c2eb22012-12-04 23:40:58 +00001741 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
Chris Lattner5b4a9622009-12-30 02:11:14 +00001742 return true;
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001743 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1744 AttrIndex++,
1745 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001746 }
1747
1748 Lex.Lex(); // Lex the ')'.
1749 return false;
1750}
1751
1752
1753
Chris Lattner2ed06b42009-01-05 18:34:07 +00001754/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001755/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001756/// ::= '(' ArgTypeListI ')'
1757/// ArgTypeListI
1758/// ::= /*empty*/
1759/// ::= '...'
1760/// ::= ArgTypeList ',' '...'
1761/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001762///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001763bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1764 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001765 isVarArg = false;
1766 assert(Lex.getKind() == lltok::lparen);
1767 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001768
Chris Lattnerac161bf2009-01-02 07:01:27 +00001769 if (Lex.getKind() == lltok::rparen) {
1770 // empty
1771 } else if (Lex.getKind() == lltok::dotdotdot) {
1772 isVarArg = true;
1773 Lex.Lex();
1774 } else {
1775 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001776 Type *ArgTy = 0;
Bill Wendling50d27842012-10-15 20:35:56 +00001777 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001778 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001779
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001780 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001781 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001782
Chris Lattnerfdd87902009-10-05 05:54:46 +00001783 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001784 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001785
Chris Lattnerdef19492011-06-17 06:36:20 +00001786 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001787 Name = Lex.getStrVal();
1788 Lex.Lex();
1789 }
Chris Lattner3822f632009-01-02 08:05:26 +00001790
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001791 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001792 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001793
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001794 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001795 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001796 AttributeSet::get(ArgTy->getContext(),
1797 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001798
Chris Lattner3822f632009-01-02 08:05:26 +00001799 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001800 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001801 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001802 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001803 break;
1804 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001805
Chris Lattnerac161bf2009-01-02 07:01:27 +00001806 // Otherwise must be an argument type.
1807 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001808 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001809
Chris Lattnerfdd87902009-10-05 05:54:46 +00001810 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001811 return Error(TypeLoc, "argument can not have void type");
1812
Chris Lattnerdef19492011-06-17 06:36:20 +00001813 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001814 Name = Lex.getStrVal();
1815 Lex.Lex();
1816 } else {
1817 Name = "";
1818 }
Chris Lattner3822f632009-01-02 08:05:26 +00001819
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001820 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001821 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001822
Bill Wendlingd079a442012-10-15 04:46:55 +00001823 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001824 AttributeSet::get(ArgTy->getContext(),
1825 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001826 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001827 }
1828 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001829
Chris Lattner3822f632009-01-02 08:05:26 +00001830 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001831}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001832
Chris Lattnerac161bf2009-01-02 07:01:27 +00001833/// ParseFunctionType
1834/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001835bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001836 assert(Lex.getKind() == lltok::lparen);
1837
Chris Lattnerce473c72009-01-05 08:04:33 +00001838 if (!FunctionType::isValidReturnType(Result))
1839 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001840
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001841 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001842 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001843 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001844 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001845
Chris Lattnerac161bf2009-01-02 07:01:27 +00001846 // Reject names on the arguments lists.
1847 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1848 if (!ArgList[i].Name.empty())
1849 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001850 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001851 return Error(ArgList[i].Loc,
1852 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001853 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001854
Jay Foadb804a2b2011-07-12 14:06:48 +00001855 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001856 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001857 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001858
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001859 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001860 return false;
1861}
1862
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001863/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1864/// other structs.
1865bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1866 SmallVector<Type*, 8> Elts;
1867 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001868
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001869 Result = StructType::get(Context, Elts, Packed);
1870 return false;
1871}
1872
1873/// ParseStructDefinition - Parse a struct in a 'type' definition.
1874bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1875 std::pair<Type*, LocTy> &Entry,
1876 Type *&ResultTy) {
1877 // If the type was already defined, diagnose the redefinition.
1878 if (Entry.first && !Entry.second.isValid())
1879 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001880
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001881 // If we have opaque, just return without filling in the definition for the
1882 // struct. This counts as a definition as far as the .ll file goes.
1883 if (EatIfPresent(lltok::kw_opaque)) {
1884 // This type is being defined, so clear the location to indicate this.
1885 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001886
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001887 // If this type number has never been uttered, create it.
1888 if (Entry.first == 0)
Chris Lattner335d3992011-08-12 18:06:37 +00001889 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001890 ResultTy = Entry.first;
1891 return false;
1892 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001893
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001894 // If the type starts with '<', then it is either a packed struct or a vector.
1895 bool isPacked = EatIfPresent(lltok::less);
1896
1897 // If we don't have a struct, then we have a random type alias, which we
1898 // accept for compatibility with old files. These types are not allowed to be
1899 // forward referenced and not allowed to be recursive.
1900 if (Lex.getKind() != lltok::lbrace) {
1901 if (Entry.first)
1902 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001903
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001904 ResultTy = 0;
1905 if (isPacked)
1906 return ParseArrayVectorType(ResultTy, true);
1907 return ParseType(ResultTy);
1908 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001909
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001910 // This type is being defined, so clear the location to indicate this.
1911 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001912
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001913 // If this type number has never been uttered, create it.
1914 if (Entry.first == 0)
Chris Lattner335d3992011-08-12 18:06:37 +00001915 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001916
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001917 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001918
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001919 SmallVector<Type*, 8> Body;
1920 if (ParseStructBody(Body) ||
1921 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1922 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001923
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001924 STy->setBody(Body, isPacked);
1925 ResultTy = STy;
1926 return false;
1927}
1928
1929
Chris Lattnerac161bf2009-01-02 07:01:27 +00001930/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001931/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00001932/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001933/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001934/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001935/// ::= '<' '{' Type (',' Type)* '}' '>'
1936bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001937 assert(Lex.getKind() == lltok::lbrace);
1938 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001939
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001940 // Handle the empty struct.
1941 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001942 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001943
Chris Lattnerf880ca22009-03-09 04:49:14 +00001944 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001945 Type *Ty = 0;
1946 if (ParseType(Ty)) return true;
1947 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001948
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001949 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001950 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001951
Chris Lattner3822f632009-01-02 08:05:26 +00001952 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00001953 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001954 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001955
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001956 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001957 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001958
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001959 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001960 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001961
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001962 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001963}
1964
1965/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1966/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001967/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00001968/// ::= '[' APSINTVAL 'x' Types ']'
1969/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001970bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001971 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1972 Lex.getAPSIntVal().getBitWidth() > 64)
1973 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001974
Chris Lattnerac161bf2009-01-02 07:01:27 +00001975 LocTy SizeLoc = Lex.getLoc();
1976 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00001977 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001978
Chris Lattner3822f632009-01-02 08:05:26 +00001979 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1980 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001981
1982 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001983 Type *EltTy = 0;
1984 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00001985
Chris Lattner3822f632009-01-02 08:05:26 +00001986 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1987 "expected end of sequential type"))
1988 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001989
Chris Lattnerac161bf2009-01-02 07:01:27 +00001990 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00001991 if (Size == 0)
1992 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001993 if ((unsigned)Size != Size)
1994 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001995 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00001996 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00001997 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001998 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001999 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002000 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002001 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002002 }
2003 return false;
2004}
2005
2006//===----------------------------------------------------------------------===//
2007// Function Semantic Analysis.
2008//===----------------------------------------------------------------------===//
2009
Chris Lattner3432c622009-10-28 03:39:23 +00002010LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2011 int functionNumber)
2012 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002013
2014 // Insert unnamed arguments into the NumberedVals list.
2015 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2016 AI != E; ++AI)
2017 if (!AI->hasName())
2018 NumberedVals.push_back(AI);
2019}
2020
2021LLParser::PerFunctionState::~PerFunctionState() {
2022 // If there were any forward referenced non-basicblock values, delete them.
2023 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2024 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2025 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002026 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002027 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002028 delete I->second.first;
2029 I->second.first = 0;
2030 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002031
Chris Lattnerac161bf2009-01-02 07:01:27 +00002032 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2033 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2034 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002035 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002036 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002037 delete I->second.first;
2038 I->second.first = 0;
2039 }
2040}
2041
Chris Lattner3432c622009-10-28 03:39:23 +00002042bool LLParser::PerFunctionState::FinishFunction() {
2043 // Check to see if someone took the address of labels in this block.
2044 if (!P.ForwardRefBlockAddresses.empty()) {
2045 ValID FunctionID;
2046 if (!F.getName().empty()) {
2047 FunctionID.Kind = ValID::t_GlobalName;
2048 FunctionID.StrVal = F.getName();
2049 } else {
2050 FunctionID.Kind = ValID::t_GlobalID;
2051 FunctionID.UIntVal = FunctionNumber;
2052 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002053
Chris Lattner3432c622009-10-28 03:39:23 +00002054 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2055 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2056 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2057 // Resolve all these references.
2058 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2059 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002060
Chris Lattner3432c622009-10-28 03:39:23 +00002061 P.ForwardRefBlockAddresses.erase(FRBAI);
2062 }
2063 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002064
Chris Lattnerac161bf2009-01-02 07:01:27 +00002065 if (!ForwardRefVals.empty())
2066 return P.Error(ForwardRefVals.begin()->second.second,
2067 "use of undefined value '%" + ForwardRefVals.begin()->first +
2068 "'");
2069 if (!ForwardRefValIDs.empty())
2070 return P.Error(ForwardRefValIDs.begin()->second.second,
2071 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002072 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002073 return false;
2074}
2075
2076
2077/// GetVal - Get a value with the specified name or ID, creating a
2078/// forward reference record if needed. This can return null if the value
2079/// exists but does not have the right type.
2080Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002081 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002082 // Look this name up in the normal function symbol table.
2083 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002084
Chris Lattnerac161bf2009-01-02 07:01:27 +00002085 // If this is a forward reference for the value, see if we already created a
2086 // forward ref record.
2087 if (Val == 0) {
2088 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2089 I = ForwardRefVals.find(Name);
2090 if (I != ForwardRefVals.end())
2091 Val = I->second.first;
2092 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002093
Chris Lattnerac161bf2009-01-02 07:01:27 +00002094 // If we have the value in the symbol table or fwd-ref table, return it.
2095 if (Val) {
2096 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002097 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002098 P.Error(Loc, "'%" + Name + "' is not a basic block");
2099 else
2100 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002101 getTypeString(Val->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002102 return 0;
2103 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002104
Chris Lattnerac161bf2009-01-02 07:01:27 +00002105 // Don't make placeholders with invalid type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002106 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002107 P.Error(Loc, "invalid use of a non-first-class type");
2108 return 0;
2109 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002110
Chris Lattnerac161bf2009-01-02 07:01:27 +00002111 // Otherwise, create a new forward reference for this value and remember it.
2112 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002113 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002114 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002115 else
2116 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002117
Chris Lattnerac161bf2009-01-02 07:01:27 +00002118 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2119 return FwdVal;
2120}
2121
Chris Lattner229907c2011-07-18 04:54:35 +00002122Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002123 LocTy Loc) {
2124 // Look this name up in the normal function symbol table.
2125 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002126
Chris Lattnerac161bf2009-01-02 07:01:27 +00002127 // If this is a forward reference for the value, see if we already created a
2128 // forward ref record.
2129 if (Val == 0) {
2130 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2131 I = ForwardRefValIDs.find(ID);
2132 if (I != ForwardRefValIDs.end())
2133 Val = I->second.first;
2134 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002135
Chris Lattnerac161bf2009-01-02 07:01:27 +00002136 // If we have the value in the symbol table or fwd-ref table, return it.
2137 if (Val) {
2138 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002139 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002140 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002141 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002142 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002143 getTypeString(Val->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002144 return 0;
2145 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002146
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002147 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002148 P.Error(Loc, "invalid use of a non-first-class type");
2149 return 0;
2150 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002151
Chris Lattnerac161bf2009-01-02 07:01:27 +00002152 // Otherwise, create a new forward reference for this value and remember it.
2153 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002154 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002155 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002156 else
2157 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002158
Chris Lattnerac161bf2009-01-02 07:01:27 +00002159 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2160 return FwdVal;
2161}
2162
2163/// SetInstName - After an instruction is parsed and inserted into its
2164/// basic block, this installs its name.
2165bool LLParser::PerFunctionState::SetInstName(int NameID,
2166 const std::string &NameStr,
2167 LocTy NameLoc, Instruction *Inst) {
2168 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002169 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002170 if (NameID != -1 || !NameStr.empty())
2171 return P.Error(NameLoc, "instructions returning void cannot have a name");
2172 return false;
2173 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002174
Chris Lattnerac161bf2009-01-02 07:01:27 +00002175 // If this was a numbered instruction, verify that the instruction is the
2176 // expected value and resolve any forward references.
2177 if (NameStr.empty()) {
2178 // If neither a name nor an ID was specified, just use the next ID.
2179 if (NameID == -1)
2180 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002181
Chris Lattnerac161bf2009-01-02 07:01:27 +00002182 if (unsigned(NameID) != NumberedVals.size())
2183 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002184 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002185
Chris Lattnerac161bf2009-01-02 07:01:27 +00002186 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2187 ForwardRefValIDs.find(NameID);
2188 if (FI != ForwardRefValIDs.end()) {
2189 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002190 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002191 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002192 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002193 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002194 ForwardRefValIDs.erase(FI);
2195 }
2196
2197 NumberedVals.push_back(Inst);
2198 return false;
2199 }
2200
2201 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2202 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2203 FI = ForwardRefVals.find(NameStr);
2204 if (FI != ForwardRefVals.end()) {
2205 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002206 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002207 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002208 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002209 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002210 ForwardRefVals.erase(FI);
2211 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002212
Chris Lattnerac161bf2009-01-02 07:01:27 +00002213 // Set the name on the instruction.
2214 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002215
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002216 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002217 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002218 NameStr + "'");
2219 return false;
2220}
2221
2222/// GetBB - Get a basic block with the specified name or ID, creating a
2223/// forward reference record if needed.
2224BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2225 LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002226 return cast_or_null<BasicBlock>(GetVal(Name,
2227 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002228}
2229
2230BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002231 return cast_or_null<BasicBlock>(GetVal(ID,
2232 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002233}
2234
2235/// DefineBB - Define the specified basic block, which is either named or
2236/// unnamed. If there is an error, this returns null otherwise it returns
2237/// the block being defined.
2238BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2239 LocTy Loc) {
2240 BasicBlock *BB;
2241 if (Name.empty())
2242 BB = GetBB(NumberedVals.size(), Loc);
2243 else
2244 BB = GetBB(Name, Loc);
2245 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002246
Chris Lattnerac161bf2009-01-02 07:01:27 +00002247 // Move the block to the end of the function. Forward ref'd blocks are
2248 // inserted wherever they happen to be referenced.
2249 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002250
Chris Lattnerac161bf2009-01-02 07:01:27 +00002251 // Remove the block from forward ref sets.
2252 if (Name.empty()) {
2253 ForwardRefValIDs.erase(NumberedVals.size());
2254 NumberedVals.push_back(BB);
2255 } else {
2256 // BB forward references are already in the function symbol table.
2257 ForwardRefVals.erase(Name);
2258 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002259
Chris Lattnerac161bf2009-01-02 07:01:27 +00002260 return BB;
2261}
2262
2263//===----------------------------------------------------------------------===//
2264// Constants.
2265//===----------------------------------------------------------------------===//
2266
2267/// ParseValID - Parse an abstract value that doesn't necessarily have a
2268/// type implied. For example, if we parse "4" we don't know what integer type
2269/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002270/// sanity. PFS is used to convert function-local operands of metadata (since
2271/// metadata operands are not just parsed here but also converted to values).
2272/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002273bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002274 ID.Loc = Lex.getLoc();
2275 switch (Lex.getKind()) {
2276 default: return TokError("expected value token");
2277 case lltok::GlobalID: // @42
2278 ID.UIntVal = Lex.getUIntVal();
2279 ID.Kind = ValID::t_GlobalID;
2280 break;
2281 case lltok::GlobalVar: // @foo
2282 ID.StrVal = Lex.getStrVal();
2283 ID.Kind = ValID::t_GlobalName;
2284 break;
2285 case lltok::LocalVarID: // %42
2286 ID.UIntVal = Lex.getUIntVal();
2287 ID.Kind = ValID::t_LocalID;
2288 break;
2289 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002290 ID.StrVal = Lex.getStrVal();
2291 ID.Kind = ValID::t_LocalName;
2292 break;
Dan Gohman8939ba332010-07-14 18:26:50 +00002293 case lltok::exclaim: // !42, !{...}, or !"foo"
2294 return ParseMetadataValue(ID, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002295 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002296 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002297 ID.Kind = ValID::t_APSInt;
2298 break;
2299 case lltok::APFloat:
2300 ID.APFloatVal = Lex.getAPFloatVal();
2301 ID.Kind = ValID::t_APFloat;
2302 break;
2303 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002304 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002305 ID.Kind = ValID::t_Constant;
2306 break;
2307 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002308 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002309 ID.Kind = ValID::t_Constant;
2310 break;
2311 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2312 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2313 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002314
Chris Lattnerac161bf2009-01-02 07:01:27 +00002315 case lltok::lbrace: {
2316 // ValID ::= '{' ConstVector '}'
2317 Lex.Lex();
2318 SmallVector<Constant*, 16> Elts;
2319 if (ParseGlobalValueVector(Elts) ||
2320 ParseToken(lltok::rbrace, "expected end of struct constant"))
2321 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002322
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002323 ID.ConstantStructElts = new Constant*[Elts.size()];
2324 ID.UIntVal = Elts.size();
2325 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2326 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002327 return false;
2328 }
2329 case lltok::less: {
2330 // ValID ::= '<' ConstVector '>' --> Vector.
2331 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2332 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002333 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002334
Chris Lattnerac161bf2009-01-02 07:01:27 +00002335 SmallVector<Constant*, 16> Elts;
2336 LocTy FirstEltLoc = Lex.getLoc();
2337 if (ParseGlobalValueVector(Elts) ||
2338 (isPackedStruct &&
2339 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2340 ParseToken(lltok::greater, "expected end of constant"))
2341 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002342
Chris Lattnerac161bf2009-01-02 07:01:27 +00002343 if (isPackedStruct) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002344 ID.ConstantStructElts = new Constant*[Elts.size()];
2345 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2346 ID.UIntVal = Elts.size();
2347 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002348 return false;
2349 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002350
Chris Lattnerac161bf2009-01-02 07:01:27 +00002351 if (Elts.empty())
2352 return Error(ID.Loc, "constant vector must not be empty");
2353
Duncan Sands9dff9be2010-02-15 16:12:20 +00002354 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002355 !Elts[0]->getType()->isFloatingPointTy() &&
2356 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002357 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002358 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002359
Chris Lattnerac161bf2009-01-02 07:01:27 +00002360 // Verify that all the vector elements have the same type.
2361 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2362 if (Elts[i]->getType() != Elts[0]->getType())
2363 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002364 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002365 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002366
Chris Lattner69229312011-02-15 00:14:00 +00002367 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002368 ID.Kind = ValID::t_Constant;
2369 return false;
2370 }
2371 case lltok::lsquare: { // Array Constant
2372 Lex.Lex();
2373 SmallVector<Constant*, 16> Elts;
2374 LocTy FirstEltLoc = Lex.getLoc();
2375 if (ParseGlobalValueVector(Elts) ||
2376 ParseToken(lltok::rsquare, "expected end of array constant"))
2377 return true;
2378
2379 // Handle empty element.
2380 if (Elts.empty()) {
2381 // Use undef instead of an array because it's inconvenient to determine
2382 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002383 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002384 return false;
2385 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002386
Chris Lattnerac161bf2009-01-02 07:01:27 +00002387 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002388 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002389 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002390
Owen Anderson4056ca92009-07-29 22:17:13 +00002391 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002392
Chris Lattnerac161bf2009-01-02 07:01:27 +00002393 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002394 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002395 if (Elts[i]->getType() != Elts[0]->getType())
2396 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002397 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002398 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002399 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002400
Jay Foad83be3612011-06-22 09:24:39 +00002401 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002402 ID.Kind = ValID::t_Constant;
2403 return false;
2404 }
2405 case lltok::kw_c: // c "foo"
2406 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002407 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2408 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002409 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2410 ID.Kind = ValID::t_Constant;
2411 return false;
2412
2413 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002414 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2415 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002416 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002417 Lex.Lex();
2418 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002419 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002420 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002421 ParseStringConstant(ID.StrVal) ||
2422 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002423 ParseToken(lltok::StringConstant, "expected constraint string"))
2424 return true;
2425 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002426 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002427 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002428 ID.Kind = ValID::t_InlineAsm;
2429 return false;
2430 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002431
Chris Lattner3432c622009-10-28 03:39:23 +00002432 case lltok::kw_blockaddress: {
2433 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2434 Lex.Lex();
2435
2436 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002437
Chris Lattner3432c622009-10-28 03:39:23 +00002438 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2439 ParseValID(Fn) ||
2440 ParseToken(lltok::comma, "expected comma in block address expression")||
2441 ParseValID(Label) ||
2442 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2443 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002444
Chris Lattner3432c622009-10-28 03:39:23 +00002445 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2446 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002447 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002448 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002449
Chris Lattner3432c622009-10-28 03:39:23 +00002450 // Make a global variable as a placeholder for this reference.
2451 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2452 false, GlobalValue::InternalLinkage,
2453 0, "");
2454 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2455 ID.ConstantVal = FwdRef;
2456 ID.Kind = ValID::t_Constant;
2457 return false;
2458 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002459
Chris Lattnerac161bf2009-01-02 07:01:27 +00002460 case lltok::kw_trunc:
2461 case lltok::kw_zext:
2462 case lltok::kw_sext:
2463 case lltok::kw_fptrunc:
2464 case lltok::kw_fpext:
2465 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002466 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002467 case lltok::kw_uitofp:
2468 case lltok::kw_sitofp:
2469 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002470 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002471 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002472 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002473 unsigned Opc = Lex.getUIntVal();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002474 Type *DestTy = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002475 Constant *SrcVal;
2476 Lex.Lex();
2477 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2478 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002479 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002480 ParseType(DestTy) ||
2481 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2482 return true;
2483 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2484 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002485 getTypeString(SrcVal->getType()) + "' to '" +
2486 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002487 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002488 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002489 ID.Kind = ValID::t_Constant;
2490 return false;
2491 }
2492 case lltok::kw_extractvalue: {
2493 Lex.Lex();
2494 Constant *Val;
2495 SmallVector<unsigned, 4> Indices;
2496 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2497 ParseGlobalTypeAndValue(Val) ||
2498 ParseIndexList(Indices) ||
2499 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2500 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002501
Chris Lattner392be582010-02-12 20:49:41 +00002502 if (!Val->getType()->isAggregateType())
2503 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002504 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002505 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002506 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002507 ID.Kind = ValID::t_Constant;
2508 return false;
2509 }
2510 case lltok::kw_insertvalue: {
2511 Lex.Lex();
2512 Constant *Val0, *Val1;
2513 SmallVector<unsigned, 4> Indices;
2514 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2515 ParseGlobalTypeAndValue(Val0) ||
2516 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2517 ParseGlobalTypeAndValue(Val1) ||
2518 ParseIndexList(Indices) ||
2519 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2520 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002521 if (!Val0->getType()->isAggregateType())
2522 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002523 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002524 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002525 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002526 ID.Kind = ValID::t_Constant;
2527 return false;
2528 }
2529 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002530 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002531 unsigned PredVal, Opc = Lex.getUIntVal();
2532 Constant *Val0, *Val1;
2533 Lex.Lex();
2534 if (ParseCmpPredicate(PredVal, Opc) ||
2535 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2536 ParseGlobalTypeAndValue(Val0) ||
2537 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2538 ParseGlobalTypeAndValue(Val1) ||
2539 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2540 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002541
Chris Lattnerac161bf2009-01-02 07:01:27 +00002542 if (Val0->getType() != Val1->getType())
2543 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002544
Chris Lattnerac161bf2009-01-02 07:01:27 +00002545 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002546
Chris Lattnerac161bf2009-01-02 07:01:27 +00002547 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002548 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002549 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002550 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002551 } else {
2552 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002553 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002554 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002555 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002556 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002557 }
2558 ID.Kind = ValID::t_Constant;
2559 return false;
2560 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002561
Chris Lattnerac161bf2009-01-02 07:01:27 +00002562 // Binary Operators.
2563 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002564 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002565 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002566 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002567 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002568 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002569 case lltok::kw_udiv:
2570 case lltok::kw_sdiv:
2571 case lltok::kw_fdiv:
2572 case lltok::kw_urem:
2573 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002574 case lltok::kw_frem:
2575 case lltok::kw_shl:
2576 case lltok::kw_lshr:
2577 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002578 bool NUW = false;
2579 bool NSW = false;
2580 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002581 unsigned Opc = Lex.getUIntVal();
2582 Constant *Val0, *Val1;
2583 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002584 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002585 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2586 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002587 if (EatIfPresent(lltok::kw_nuw))
2588 NUW = true;
2589 if (EatIfPresent(lltok::kw_nsw)) {
2590 NSW = true;
2591 if (EatIfPresent(lltok::kw_nuw))
2592 NUW = true;
2593 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002594 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2595 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002596 if (EatIfPresent(lltok::kw_exact))
2597 Exact = true;
2598 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002599 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2600 ParseGlobalTypeAndValue(Val0) ||
2601 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2602 ParseGlobalTypeAndValue(Val1) ||
2603 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2604 return true;
2605 if (Val0->getType() != Val1->getType())
2606 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002607 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002608 if (NUW)
2609 return Error(ModifierLoc, "nuw only applies to integer operations");
2610 if (NSW)
2611 return Error(ModifierLoc, "nsw only applies to integer operations");
2612 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002613 // Check that the type is valid for the operator.
2614 switch (Opc) {
2615 case Instruction::Add:
2616 case Instruction::Sub:
2617 case Instruction::Mul:
2618 case Instruction::UDiv:
2619 case Instruction::SDiv:
2620 case Instruction::URem:
2621 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002622 case Instruction::Shl:
2623 case Instruction::AShr:
2624 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002625 if (!Val0->getType()->isIntOrIntVectorTy())
2626 return Error(ID.Loc, "constexpr requires integer operands");
2627 break;
2628 case Instruction::FAdd:
2629 case Instruction::FSub:
2630 case Instruction::FMul:
2631 case Instruction::FDiv:
2632 case Instruction::FRem:
2633 if (!Val0->getType()->isFPOrFPVectorTy())
2634 return Error(ID.Loc, "constexpr requires fp operands");
2635 break;
2636 default: llvm_unreachable("Unknown binary operator!");
2637 }
Dan Gohman1b849082009-09-07 23:54:19 +00002638 unsigned Flags = 0;
2639 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2640 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002641 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002642 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002643 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002644 ID.Kind = ValID::t_Constant;
2645 return false;
2646 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002647
Chris Lattnerac161bf2009-01-02 07:01:27 +00002648 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002649 case lltok::kw_and:
2650 case lltok::kw_or:
2651 case lltok::kw_xor: {
2652 unsigned Opc = Lex.getUIntVal();
2653 Constant *Val0, *Val1;
2654 Lex.Lex();
2655 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2656 ParseGlobalTypeAndValue(Val0) ||
2657 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2658 ParseGlobalTypeAndValue(Val1) ||
2659 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2660 return true;
2661 if (Val0->getType() != Val1->getType())
2662 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002663 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002664 return Error(ID.Loc,
2665 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002666 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002667 ID.Kind = ValID::t_Constant;
2668 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002669 }
2670
Chris Lattnerac161bf2009-01-02 07:01:27 +00002671 case lltok::kw_getelementptr:
2672 case lltok::kw_shufflevector:
2673 case lltok::kw_insertelement:
2674 case lltok::kw_extractelement:
2675 case lltok::kw_select: {
2676 unsigned Opc = Lex.getUIntVal();
2677 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002678 bool InBounds = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002679 Lex.Lex();
Dan Gohman1639c392009-07-27 21:53:46 +00002680 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002681 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002682 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2683 ParseGlobalValueVector(Elts) ||
2684 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2685 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002686
Chris Lattnerac161bf2009-01-02 07:01:27 +00002687 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002688 if (Elts.size() == 0 ||
2689 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002690 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002691
Jay Foaded8db7d2011-07-21 14:31:17 +00002692 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foadd1b78492011-07-25 09:48:08 +00002693 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002694 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002695 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2696 InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002697 } else if (Opc == Instruction::Select) {
2698 if (Elts.size() != 3)
2699 return Error(ID.Loc, "expected three operands to select");
2700 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2701 Elts[2]))
2702 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002703 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002704 } else if (Opc == Instruction::ShuffleVector) {
2705 if (Elts.size() != 3)
2706 return Error(ID.Loc, "expected three operands to shufflevector");
2707 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2708 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002709 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002710 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002711 } else if (Opc == Instruction::ExtractElement) {
2712 if (Elts.size() != 2)
2713 return Error(ID.Loc, "expected two operands to extractelement");
2714 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2715 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002716 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002717 } else {
2718 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2719 if (Elts.size() != 3)
2720 return Error(ID.Loc, "expected three operands to insertelement");
2721 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2722 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002723 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002724 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002725 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002726
Chris Lattnerac161bf2009-01-02 07:01:27 +00002727 ID.Kind = ValID::t_Constant;
2728 return false;
2729 }
2730 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002731
Chris Lattnerac161bf2009-01-02 07:01:27 +00002732 Lex.Lex();
2733 return false;
2734}
2735
2736/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002737bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002738 C = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002739 ValID ID;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002740 Value *V = NULL;
2741 bool Parsed = ParseValID(ID) ||
2742 ConvertValIDToValue(Ty, ID, V, NULL);
2743 if (V && !(C = dyn_cast<Constant>(V)))
2744 return Error(ID.Loc, "global values must be constants");
2745 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002746}
2747
Victor Hernandez9d75c962010-01-11 22:31:58 +00002748bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002749 Type *Ty = 0;
2750 return ParseType(Ty) ||
2751 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002752}
2753
2754/// ParseGlobalValueVector
2755/// ::= /*empty*/
2756/// ::= TypeAndValue (',' TypeAndValue)*
2757bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2758 // Empty list.
2759 if (Lex.getKind() == lltok::rbrace ||
2760 Lex.getKind() == lltok::rsquare ||
2761 Lex.getKind() == lltok::greater ||
2762 Lex.getKind() == lltok::rparen)
2763 return false;
2764
2765 Constant *C;
2766 if (ParseGlobalTypeAndValue(C)) return true;
2767 Elts.push_back(C);
2768
2769 while (EatIfPresent(lltok::comma)) {
2770 if (ParseGlobalTypeAndValue(C)) return true;
2771 Elts.push_back(C);
2772 }
2773
2774 return false;
2775}
2776
Dan Gohmanc828c542010-08-24 02:24:03 +00002777bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2778 assert(Lex.getKind() == lltok::lbrace);
2779 Lex.Lex();
2780
2781 SmallVector<Value*, 16> Elts;
2782 if (ParseMDNodeVector(Elts, PFS) ||
2783 ParseToken(lltok::rbrace, "expected end of metadata node"))
2784 return true;
2785
Jay Foad5514afe2011-04-21 19:59:31 +00002786 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002787 ID.Kind = ValID::t_MDNode;
2788 return false;
2789}
2790
Dan Gohman8939ba332010-07-14 18:26:50 +00002791/// ParseMetadataValue
2792/// ::= !42
2793/// ::= !{...}
2794/// ::= !"string"
2795bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2796 assert(Lex.getKind() == lltok::exclaim);
2797 Lex.Lex();
2798
2799 // MDNode:
2800 // !{ ... }
Dan Gohmanc828c542010-08-24 02:24:03 +00002801 if (Lex.getKind() == lltok::lbrace)
2802 return ParseMetadataListValue(ID, PFS);
Dan Gohman8939ba332010-07-14 18:26:50 +00002803
2804 // Standalone metadata reference
2805 // !42
2806 if (Lex.getKind() == lltok::APSInt) {
2807 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2808 ID.Kind = ValID::t_MDNode;
2809 return false;
2810 }
2811
2812 // MDString:
2813 // ::= '!' STRINGCONSTANT
2814 if (ParseMDString(ID.MDStringVal)) return true;
2815 ID.Kind = ValID::t_MDString;
2816 return false;
2817}
2818
Victor Hernandez9d75c962010-01-11 22:31:58 +00002819
2820//===----------------------------------------------------------------------===//
2821// Function Parsing.
2822//===----------------------------------------------------------------------===//
2823
Chris Lattner229907c2011-07-18 04:54:35 +00002824bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00002825 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002826 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002827 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002828
Chris Lattnerac161bf2009-01-02 07:01:27 +00002829 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002830 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00002831 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2832 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2833 return (V == 0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002834 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00002835 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2836 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2837 return (V == 0);
2838 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00002839 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002840 FunctionType *FTy =
Victor Hernandez9d75c962010-01-11 22:31:58 +00002841 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2842 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2843 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00002844 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00002845 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00002846 return false;
2847 }
2848 case ValID::t_MDNode:
2849 if (!Ty->isMetadataTy())
2850 return Error(ID.Loc, "metadata value must have metadata type");
2851 V = ID.MDNodeVal;
2852 return false;
2853 case ValID::t_MDString:
2854 if (!Ty->isMetadataTy())
2855 return Error(ID.Loc, "metadata value must have metadata type");
2856 V = ID.MDStringVal;
2857 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002858 case ValID::t_GlobalName:
2859 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2860 return V == 0;
2861 case ValID::t_GlobalID:
2862 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2863 return V == 0;
2864 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00002865 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002866 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00002867 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00002868 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002869 return false;
2870 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00002871 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002872 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2873 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002874
Dan Gohman518cda42011-12-17 00:04:22 +00002875 // The lexer has no type info, so builds all half, float, and double FP
2876 // constants as double. Fix this here. Long double does not need this.
2877 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002878 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00002879 if (Ty->isHalfTy())
2880 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2881 &Ignored);
2882 else if (Ty->isFloatTy())
2883 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2884 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002885 }
Owen Anderson69c464d2009-07-27 20:59:43 +00002886 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002887
Chris Lattner8f57d29e2009-01-05 18:24:23 +00002888 if (V->getType() != Ty)
2889 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002890 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002891
Chris Lattnerac161bf2009-01-02 07:01:27 +00002892 return false;
2893 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00002894 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002895 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00002896 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002897 return false;
2898 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00002899 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002900 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00002901 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00002902 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002903 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00002904 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00002905 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00002906 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00002907 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00002908 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002909 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00002910 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002911 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002912 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00002913 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002914 return false;
2915 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00002916 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002917 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00002918
Chris Lattnerac161bf2009-01-02 07:01:27 +00002919 V = ID.ConstantVal;
2920 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002921 case ValID::t_ConstantStruct:
2922 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00002923 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002924 if (ST->getNumElements() != ID.UIntVal)
2925 return Error(ID.Loc,
2926 "initializer with struct type has wrong # elements");
2927 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2928 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002929
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002930 // Verify that the elements are compatible with the structtype.
2931 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2932 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2933 return Error(ID.Loc, "element " + Twine(i) +
2934 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002935
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002936 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2937 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002938 } else
2939 return Error(ID.Loc, "constant expression type mismatch");
2940 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002941 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00002942 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002943}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002944
Chris Lattner229907c2011-07-18 04:54:35 +00002945bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002946 V = 0;
2947 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002948 return ParseValID(ID, PFS) ||
2949 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002950}
2951
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002952bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2953 Type *Ty = 0;
2954 return ParseType(Ty) ||
2955 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002956}
2957
Chris Lattner3ed871f2009-10-27 19:13:16 +00002958bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2959 PerFunctionState &PFS) {
2960 Value *V;
2961 Loc = Lex.getLoc();
2962 if (ParseTypeAndValue(V, PFS)) return true;
2963 if (!isa<BasicBlock>(V))
2964 return Error(Loc, "expected a basic block");
2965 BB = cast<BasicBlock>(V);
2966 return false;
2967}
2968
2969
Chris Lattnerac161bf2009-01-02 07:01:27 +00002970/// FunctionHeader
2971/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00002972/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002973/// OptionalAlign OptGC OptionalPrefix
Chris Lattnerac161bf2009-01-02 07:01:27 +00002974bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2975 // Parse the linkage.
2976 LocTy LinkageLoc = Lex.getLoc();
2977 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002978
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00002979 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00002980 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00002981 AttrBuilder RetAttrs;
Sandeep Patel68c5f472009-09-02 08:44:58 +00002982 CallingConv::ID CC;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002983 Type *RetType = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002984 LocTy RetTypeLoc = Lex.getLoc();
2985 if (ParseOptionalLinkage(Linkage) ||
2986 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00002987 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002988 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002989 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00002990 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002991 return true;
2992
2993 // Verify that the linkage is ok.
2994 switch ((GlobalValue::LinkageTypes)Linkage) {
2995 case GlobalValue::ExternalLinkage:
2996 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00002997 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002998 if (isDefine)
2999 return Error(LinkageLoc, "invalid linkage for function definition");
3000 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00003001 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003002 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00003003 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00003004 case GlobalValue::LinkOnceAnyLinkage:
3005 case GlobalValue::LinkOnceODRLinkage:
3006 case GlobalValue::WeakAnyLinkage:
3007 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003008 if (!isDefine)
3009 return Error(LinkageLoc, "invalid linkage for function declaration");
3010 break;
3011 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00003012 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003013 return Error(LinkageLoc, "invalid function linkage type");
3014 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003015
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003016 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003017 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003018
Chris Lattnerac161bf2009-01-02 07:01:27 +00003019 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00003020
3021 std::string FunctionName;
3022 if (Lex.getKind() == lltok::GlobalVar) {
3023 FunctionName = Lex.getStrVal();
3024 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3025 unsigned NameID = Lex.getUIntVal();
3026
3027 if (NameID != NumberedVals.size())
3028 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003029 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00003030 } else {
3031 return TokError("expected function name");
3032 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003033
Chris Lattner3822f632009-01-02 08:05:26 +00003034 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003035
Chris Lattner3822f632009-01-02 08:05:26 +00003036 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003037 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003038
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003039 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003040 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00003041 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003042 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003043 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003044 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003045 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00003046 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003047 bool UnnamedAddr;
3048 LocTy UnnamedAddrLoc;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003049 Constant *Prefix = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00003050
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003051 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003052 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3053 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003054 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00003055 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003056 (EatIfPresent(lltok::kw_section) &&
3057 ParseStringConstant(Section)) ||
3058 ParseOptionalAlignment(Alignment) ||
3059 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003060 ParseStringConstant(GC)) ||
3061 (EatIfPresent(lltok::kw_prefix) &&
3062 ParseGlobalTypeAndValue(Prefix)))
Chris Lattner3822f632009-01-02 08:05:26 +00003063 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003064
Michael Gottesman41748d72013-06-27 00:25:01 +00003065 if (FuncAttrs.contains(Attribute::Builtin))
3066 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00003067
Chris Lattnerac161bf2009-01-02 07:01:27 +00003068 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00003069 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00003070 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003071 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003072 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003073
Chris Lattnerac161bf2009-01-02 07:01:27 +00003074 // Okay, if we got here, the function is syntactically valid. Convert types
3075 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00003076 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00003077 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003078
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003079 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003080 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3081 AttributeSet::ReturnIndex,
3082 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003083
Chris Lattnerac161bf2009-01-02 07:01:27 +00003084 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003085 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003086 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3087 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003088 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3089 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003090 }
3091
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003092 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003093 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3094 AttributeSet::FunctionIndex,
3095 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003096
Bill Wendlinge94d8432012-12-07 23:16:57 +00003097 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003098
Bill Wendling749a43d2012-12-30 13:50:49 +00003099 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003100 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3101
Chris Lattner229907c2011-07-18 04:54:35 +00003102 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00003103 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00003104 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003105
3106 Fn = 0;
3107 if (!FunctionName.empty()) {
3108 // If this was a definition of a forward reference, remove the definition
3109 // from the forward reference table and fill in the forward ref.
3110 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3111 ForwardRefVals.find(FunctionName);
3112 if (FRVI != ForwardRefVals.end()) {
3113 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00003114 if (!Fn)
3115 return Error(FRVI->second.second, "invalid forward reference to "
3116 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00003117 if (Fn->getType() != PFT)
3118 return Error(FRVI->second.second, "invalid forward reference to "
3119 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003120
Chris Lattnerac161bf2009-01-02 07:01:27 +00003121 ForwardRefVals.erase(FRVI);
3122 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00003123 // Reject redefinitions.
3124 return Error(NameLoc, "invalid redefinition of function '" +
3125 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00003126 } else if (M->getNamedValue(FunctionName)) {
3127 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003128 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003129
Dan Gohman399d6ae2009-08-29 23:37:49 +00003130 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003131 // If this is a definition of a forward referenced function, make sure the
3132 // types agree.
3133 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3134 = ForwardRefValIDs.find(NumberedVals.size());
3135 if (I != ForwardRefValIDs.end()) {
3136 Fn = cast<Function>(I->second.first);
3137 if (Fn->getType() != PFT)
3138 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003139 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003140 ForwardRefValIDs.erase(I);
3141 }
3142 }
3143
3144 if (Fn == 0)
3145 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3146 else // Move the forward-reference to the correct spot in the module.
3147 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3148
3149 if (FunctionName.empty())
3150 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003151
Chris Lattnerac161bf2009-01-02 07:01:27 +00003152 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3153 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00003154 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003155 Fn->setCallingConv(CC);
3156 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003157 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003158 Fn->setAlignment(Alignment);
3159 Fn->setSection(Section);
3160 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003161 Fn->setPrefixData(Prefix);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003162 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003163
Chris Lattnerac161bf2009-01-02 07:01:27 +00003164 // Add all of the arguments we parsed to the function.
3165 Function::arg_iterator ArgIt = Fn->arg_begin();
3166 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3167 // If the argument has a name, insert it into the argument symbol table.
3168 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003169
Chris Lattnerac161bf2009-01-02 07:01:27 +00003170 // Set the name, if it conflicted, it will be auto-renamed.
3171 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003172
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00003173 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003174 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3175 ArgList[i].Name + "'");
3176 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003177
Chris Lattnerac161bf2009-01-02 07:01:27 +00003178 return false;
3179}
3180
3181
3182/// ParseFunctionBody
3183/// ::= '{' BasicBlock+ '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00003184///
3185bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00003186 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003187 return TokError("expected '{' in function body");
3188 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003189
Chris Lattner3432c622009-10-28 03:39:23 +00003190 int FunctionNumber = -1;
3191 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003192
Chris Lattner3432c622009-10-28 03:39:23 +00003193 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003194
Chris Lattnerbbddd962010-01-09 19:20:07 +00003195 // We need at least one basic block.
Chris Lattner4649a732011-06-17 06:42:57 +00003196 if (Lex.getKind() == lltok::rbrace)
Chris Lattnerbbddd962010-01-09 19:20:07 +00003197 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003198
Chris Lattner4649a732011-06-17 06:42:57 +00003199 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003200 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003201
Chris Lattnerac161bf2009-01-02 07:01:27 +00003202 // Eat the }.
3203 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003204
Chris Lattnerac161bf2009-01-02 07:01:27 +00003205 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00003206 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003207}
3208
3209/// ParseBasicBlock
3210/// ::= LabelStr? Instruction*
3211bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3212 // If this basic block starts out with a name, remember it.
3213 std::string Name;
3214 LocTy NameLoc = Lex.getLoc();
3215 if (Lex.getKind() == lltok::LabelStr) {
3216 Name = Lex.getStrVal();
3217 Lex.Lex();
3218 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003219
Chris Lattnerac161bf2009-01-02 07:01:27 +00003220 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3221 if (BB == 0) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003222
Chris Lattnerac161bf2009-01-02 07:01:27 +00003223 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003224
Chris Lattnerac161bf2009-01-02 07:01:27 +00003225 // Parse the instructions in this block until we get a terminator.
3226 Instruction *Inst;
3227 do {
3228 // This instruction may have three possibilities for a name: a) none
3229 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3230 LocTy NameLoc = Lex.getLoc();
3231 int NameID = -1;
3232 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003233
Chris Lattnerac161bf2009-01-02 07:01:27 +00003234 if (Lex.getKind() == lltok::LocalVarID) {
3235 NameID = Lex.getUIntVal();
3236 Lex.Lex();
3237 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3238 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00003239 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003240 NameStr = Lex.getStrVal();
3241 Lex.Lex();
3242 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3243 return true;
3244 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003245
Chris Lattner77b89dc2009-12-30 05:23:43 +00003246 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00003247 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00003248 case InstError: return true;
3249 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003250 BB->getInstList().push_back(Inst);
3251
Chris Lattner77b89dc2009-12-30 05:23:43 +00003252 // With a normal result, we check to see if the instruction is followed by
3253 // a comma and metadata.
3254 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00003255 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003256 return true;
3257 break;
3258 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003259 BB->getInstList().push_back(Inst);
3260
Chris Lattner77b89dc2009-12-30 05:23:43 +00003261 // If the instruction parser ate an extra comma at the end of it, it
3262 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00003263 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003264 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003265 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00003266 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003267
Chris Lattnerac161bf2009-01-02 07:01:27 +00003268 // Set the name on the instruction.
3269 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3270 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003271
Chris Lattnerac161bf2009-01-02 07:01:27 +00003272 return false;
3273}
3274
3275//===----------------------------------------------------------------------===//
3276// Instruction Parsing.
3277//===----------------------------------------------------------------------===//
3278
3279/// ParseInstruction - Parse one of the many different instructions.
3280///
Chris Lattner77b89dc2009-12-30 05:23:43 +00003281int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3282 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003283 lltok::Kind Token = Lex.getKind();
3284 if (Token == lltok::Eof)
3285 return TokError("found end of file when expecting more instructions");
3286 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00003287 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003288 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003289
Chris Lattnerac161bf2009-01-02 07:01:27 +00003290 switch (Token) {
3291 default: return Error(Loc, "expected instruction opcode");
3292 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00003293 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003294 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3295 case lltok::kw_br: return ParseBr(Inst, PFS);
3296 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003297 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003298 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003299 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003300 // Binary Operators.
3301 case lltok::kw_add:
3302 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003303 case lltok::kw_mul:
3304 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00003305 bool NUW = EatIfPresent(lltok::kw_nuw);
3306 bool NSW = EatIfPresent(lltok::kw_nsw);
3307 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003308
Chris Lattnera676c0f2011-02-07 16:40:21 +00003309 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003310
Chris Lattnera676c0f2011-02-07 16:40:21 +00003311 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3312 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3313 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003314 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003315 case lltok::kw_fadd:
3316 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00003317 case lltok::kw_fmul:
3318 case lltok::kw_fdiv:
3319 case lltok::kw_frem: {
3320 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3321 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3322 if (Res != 0)
3323 return Res;
3324 if (FMF.any())
3325 Inst->setFastMathFlags(FMF);
3326 return 0;
3327 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003328
Chris Lattner35315d02011-02-06 21:44:57 +00003329 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003330 case lltok::kw_udiv:
3331 case lltok::kw_lshr:
3332 case lltok::kw_ashr: {
3333 bool Exact = EatIfPresent(lltok::kw_exact);
3334
3335 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3336 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3337 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003338 }
3339
Chris Lattnerac161bf2009-01-02 07:01:27 +00003340 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00003341 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003342 case lltok::kw_and:
3343 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00003344 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003345 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003346 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003347 // Casts.
3348 case lltok::kw_trunc:
3349 case lltok::kw_zext:
3350 case lltok::kw_sext:
3351 case lltok::kw_fptrunc:
3352 case lltok::kw_fpext:
3353 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003354 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003355 case lltok::kw_uitofp:
3356 case lltok::kw_sitofp:
3357 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003358 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003359 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00003360 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003361 // Other.
3362 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00003363 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003364 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3365 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3366 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3367 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00003368 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003369 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3370 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3371 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00003372 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00003373 case lltok::kw_load: return ParseLoad(Inst, PFS);
3374 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00003375 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3376 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003377 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003378 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3379 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3380 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3381 }
3382}
3383
3384/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3385bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003386 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003387 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003388 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003389 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3390 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3391 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3392 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3393 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3394 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3395 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3396 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3397 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3398 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3399 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3400 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3401 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3402 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3403 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3404 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3405 }
3406 } else {
3407 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003408 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003409 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3410 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3411 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3412 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3413 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3414 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3415 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3416 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3417 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3418 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3419 }
3420 }
3421 Lex.Lex();
3422 return false;
3423}
3424
3425//===----------------------------------------------------------------------===//
3426// Terminator Instructions.
3427//===----------------------------------------------------------------------===//
3428
3429/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00003430/// ::= 'ret' void (',' !dbg, !1)*
3431/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00003432bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003433 PerFunctionState &PFS) {
3434 SMLoc TypeLoc = Lex.getLoc();
3435 Type *Ty = 0;
Chris Lattnerf880ca22009-03-09 04:49:14 +00003436 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003437
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003438 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003439
Chris Lattnerfdd87902009-10-05 05:54:46 +00003440 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003441 if (!ResType->isVoidTy())
3442 return Error(TypeLoc, "value doesn't match function result type '" +
3443 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003444
Owen Anderson55f1c092009-08-13 21:58:54 +00003445 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003446 return false;
3447 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003448
Chris Lattnerac161bf2009-01-02 07:01:27 +00003449 Value *RV;
3450 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003451
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003452 if (ResType != RV->getType())
3453 return Error(TypeLoc, "value doesn't match function result type '" +
3454 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003455
Owen Anderson55f1c092009-08-13 21:58:54 +00003456 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00003457 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003458}
3459
3460
3461/// ParseBr
3462/// ::= 'br' TypeAndValue
3463/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3464bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3465 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003466 Value *Op0;
3467 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003468 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003469
Chris Lattnerac161bf2009-01-02 07:01:27 +00003470 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3471 Inst = BranchInst::Create(BB);
3472 return false;
3473 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003474
Owen Anderson55f1c092009-08-13 21:58:54 +00003475 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003476 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003477
Chris Lattnerac161bf2009-01-02 07:01:27 +00003478 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003479 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003480 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003481 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003482 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003483
Chris Lattner3ed871f2009-10-27 19:13:16 +00003484 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003485 return false;
3486}
3487
3488/// ParseSwitch
3489/// Instruction
3490/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3491/// JumpTable
3492/// ::= (TypeAndValue ',' TypeAndValue)*
3493bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3494 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003495 Value *Cond;
3496 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003497 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3498 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003499 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003500 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3501 return true;
3502
Duncan Sands19d0b472010-02-16 11:11:14 +00003503 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003504 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003505
Chris Lattnerac161bf2009-01-02 07:01:27 +00003506 // Parse the jump table pairs.
3507 SmallPtrSet<Value*, 32> SeenCases;
3508 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3509 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003510 Value *Constant;
3511 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003512
Chris Lattnerac161bf2009-01-02 07:01:27 +00003513 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3514 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003515 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003516 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003517
Chris Lattnerac161bf2009-01-02 07:01:27 +00003518 if (!SeenCases.insert(Constant))
3519 return Error(CondLoc, "duplicate case value in switch");
3520 if (!isa<ConstantInt>(Constant))
3521 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003522
Chris Lattner3ed871f2009-10-27 19:13:16 +00003523 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003524 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003525
Chris Lattnerac161bf2009-01-02 07:01:27 +00003526 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003527
Chris Lattner3ed871f2009-10-27 19:13:16 +00003528 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003529 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3530 SI->addCase(Table[i].first, Table[i].second);
3531 Inst = SI;
3532 return false;
3533}
3534
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003535/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00003536/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003537/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3538bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003539 LocTy AddrLoc;
3540 Value *Address;
3541 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003542 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3543 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00003544 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003545
Duncan Sands19d0b472010-02-16 11:11:14 +00003546 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003547 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003548
Chris Lattner3ed871f2009-10-27 19:13:16 +00003549 // Parse the destination list.
3550 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003551
Chris Lattner3ed871f2009-10-27 19:13:16 +00003552 if (Lex.getKind() != lltok::rsquare) {
3553 BasicBlock *DestBB;
3554 if (ParseTypeAndBasicBlock(DestBB, PFS))
3555 return true;
3556 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003557
Chris Lattner3ed871f2009-10-27 19:13:16 +00003558 while (EatIfPresent(lltok::comma)) {
3559 if (ParseTypeAndBasicBlock(DestBB, PFS))
3560 return true;
3561 DestList.push_back(DestBB);
3562 }
3563 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003564
Chris Lattner3ed871f2009-10-27 19:13:16 +00003565 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3566 return true;
3567
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003568 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00003569 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3570 IBI->addDestination(DestList[i]);
3571 Inst = IBI;
3572 return false;
3573}
3574
3575
Chris Lattnerac161bf2009-01-02 07:01:27 +00003576/// ParseInvoke
3577/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3578/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3579bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3580 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00003581 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003582 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00003583 LocTy NoBuiltinLoc;
Sandeep Patel68c5f472009-09-02 08:44:58 +00003584 CallingConv::ID CC;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003585 Type *RetType = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003586 LocTy RetTypeLoc;
3587 ValID CalleeID;
3588 SmallVector<ParamInfo, 16> ArgList;
3589
Chris Lattner3ed871f2009-10-27 19:13:16 +00003590 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003591 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003592 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003593 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003594 ParseValID(CalleeID) ||
3595 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003596 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3597 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003598 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003599 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003600 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003601 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003602 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003603
Chris Lattnerac161bf2009-01-02 07:01:27 +00003604 // If RetType is a non-function pointer type, then this is the short syntax
3605 // for the call, which means that RetType is just the return type. Infer the
3606 // rest of the function argument types from the arguments that are present.
Chris Lattner229907c2011-07-18 04:54:35 +00003607 PointerType *PFTy = 0;
3608 FunctionType *Ty = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003609 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3610 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3611 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00003612 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003613 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3614 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003615
Chris Lattnerac161bf2009-01-02 07:01:27 +00003616 if (!FunctionType::isValidReturnType(RetType))
3617 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003618
Owen Anderson4056ca92009-07-29 22:17:13 +00003619 Ty = FunctionType::get(RetType, ParamTypes, false);
3620 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003621 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003622
Chris Lattnerac161bf2009-01-02 07:01:27 +00003623 // Look up the callee.
3624 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003625 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003626
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003627 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00003628 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003629 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003630 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3631 AttributeSet::ReturnIndex,
3632 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003633
Chris Lattnerac161bf2009-01-02 07:01:27 +00003634 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003635
Chris Lattnerac161bf2009-01-02 07:01:27 +00003636 // Loop through FunctionType's arguments and ensure they are specified
3637 // correctly. Also, gather any parameter attributes.
3638 FunctionType::param_iterator I = Ty->param_begin();
3639 FunctionType::param_iterator E = Ty->param_end();
3640 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +00003641 Type *ExpectedTy = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003642 if (I != E) {
3643 ExpectedTy = *I++;
3644 } else if (!Ty->isVarArg()) {
3645 return Error(ArgList[i].Loc, "too many arguments specified");
3646 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003647
Chris Lattnerac161bf2009-01-02 07:01:27 +00003648 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3649 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003650 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003651 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003652 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3653 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003654 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3655 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003656 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003657
Chris Lattnerac161bf2009-01-02 07:01:27 +00003658 if (I != E)
3659 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003660
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003661 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003662 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3663 AttributeSet::FunctionIndex,
3664 FnAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003665
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003666 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00003667 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003668
Jay Foad5bd375a2011-07-15 08:37:34 +00003669 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003670 II->setCallingConv(CC);
3671 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003672 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003673 Inst = II;
3674 return false;
3675}
3676
Bill Wendlingf891bf82011-07-31 06:30:59 +00003677/// ParseResume
3678/// ::= 'resume' TypeAndValue
3679bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3680 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00003681 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3682 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003683
Bill Wendlingf891bf82011-07-31 06:30:59 +00003684 ResumeInst *RI = ResumeInst::Create(Exn);
3685 Inst = RI;
3686 return false;
3687}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003688
3689//===----------------------------------------------------------------------===//
3690// Binary Operators.
3691//===----------------------------------------------------------------------===//
3692
3693/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003694/// ::= ArithmeticOps TypeAndValue ',' Value
3695///
3696/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3697/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00003698bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003699 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003700 LocTy Loc; Value *LHS, *RHS;
3701 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3702 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3703 ParseValue(LHS->getType(), RHS, PFS))
3704 return true;
3705
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003706 bool Valid;
3707 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00003708 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003709 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00003710 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3711 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003712 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00003713 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3714 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003715 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003716
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003717 if (!Valid)
3718 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003719
Chris Lattnerac161bf2009-01-02 07:01:27 +00003720 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3721 return false;
3722}
3723
3724/// ParseLogical
3725/// ::= ArithmeticOps TypeAndValue ',' Value {
3726bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3727 unsigned Opc) {
3728 LocTy Loc; Value *LHS, *RHS;
3729 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3730 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3731 ParseValue(LHS->getType(), RHS, PFS))
3732 return true;
3733
Duncan Sands9dff9be2010-02-15 16:12:20 +00003734 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003735 return Error(Loc,"instruction requires integer or integer vector operands");
3736
3737 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3738 return false;
3739}
3740
3741
3742/// ParseCompare
3743/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3744/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00003745bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3746 unsigned Opc) {
3747 // Parse the integer/fp comparison predicate.
3748 LocTy Loc;
3749 unsigned Pred;
3750 Value *LHS, *RHS;
3751 if (ParseCmpPredicate(Pred, Opc) ||
3752 ParseTypeAndValue(LHS, Loc, PFS) ||
3753 ParseToken(lltok::comma, "expected ',' after compare value") ||
3754 ParseValue(LHS->getType(), RHS, PFS))
3755 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003756
Chris Lattnerac161bf2009-01-02 07:01:27 +00003757 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003758 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003759 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003760 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003761 } else {
3762 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003763 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003764 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003765 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003766 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003767 }
3768 return false;
3769}
3770
3771//===----------------------------------------------------------------------===//
3772// Other Instructions.
3773//===----------------------------------------------------------------------===//
3774
3775
3776/// ParseCast
3777/// ::= CastOpc TypeAndValue 'to' Type
3778bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3779 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003780 LocTy Loc;
3781 Value *Op;
3782 Type *DestTy = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003783 if (ParseTypeAndValue(Op, Loc, PFS) ||
3784 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3785 ParseType(DestTy))
3786 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003787
Chris Lattner89d856e2009-03-01 00:53:13 +00003788 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3789 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003790 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003791 getTypeString(Op->getType()) + "' to '" +
3792 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00003793 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003794 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3795 return false;
3796}
3797
3798/// ParseSelect
3799/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3800bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3801 LocTy Loc;
3802 Value *Op0, *Op1, *Op2;
3803 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3804 ParseToken(lltok::comma, "expected ',' after select condition") ||
3805 ParseTypeAndValue(Op1, PFS) ||
3806 ParseToken(lltok::comma, "expected ',' after select value") ||
3807 ParseTypeAndValue(Op2, PFS))
3808 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003809
Chris Lattnerac161bf2009-01-02 07:01:27 +00003810 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3811 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003812
Chris Lattnerac161bf2009-01-02 07:01:27 +00003813 Inst = SelectInst::Create(Op0, Op1, Op2);
3814 return false;
3815}
3816
Chris Lattnerb55ab542009-01-05 08:18:44 +00003817/// ParseVA_Arg
3818/// ::= 'va_arg' TypeAndValue ',' Type
3819bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003820 Value *Op;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003821 Type *EltTy = 0;
Chris Lattnerb55ab542009-01-05 08:18:44 +00003822 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003823 if (ParseTypeAndValue(Op, PFS) ||
3824 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00003825 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003826 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003827
Chris Lattnerb55ab542009-01-05 08:18:44 +00003828 if (!EltTy->isFirstClassType())
3829 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003830
3831 Inst = new VAArgInst(Op, EltTy);
3832 return false;
3833}
3834
3835/// ParseExtractElement
3836/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3837bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3838 LocTy Loc;
3839 Value *Op0, *Op1;
3840 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3841 ParseToken(lltok::comma, "expected ',' after extract value") ||
3842 ParseTypeAndValue(Op1, PFS))
3843 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003844
Chris Lattnerac161bf2009-01-02 07:01:27 +00003845 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3846 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003847
Eric Christopherc9742252009-07-25 02:28:41 +00003848 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003849 return false;
3850}
3851
3852/// ParseInsertElement
3853/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3854bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3855 LocTy Loc;
3856 Value *Op0, *Op1, *Op2;
3857 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3858 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3859 ParseTypeAndValue(Op1, PFS) ||
3860 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3861 ParseTypeAndValue(Op2, PFS))
3862 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003863
Chris Lattnerac161bf2009-01-02 07:01:27 +00003864 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00003865 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003866
Chris Lattnerac161bf2009-01-02 07:01:27 +00003867 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3868 return false;
3869}
3870
3871/// ParseShuffleVector
3872/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3873bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3874 LocTy Loc;
3875 Value *Op0, *Op1, *Op2;
3876 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3877 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3878 ParseTypeAndValue(Op1, PFS) ||
3879 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3880 ParseTypeAndValue(Op2, PFS))
3881 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003882
Chris Lattnerac161bf2009-01-02 07:01:27 +00003883 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00003884 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003885
Chris Lattnerac161bf2009-01-02 07:01:27 +00003886 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3887 return false;
3888}
3889
3890/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00003891/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00003892int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003893 Type *Ty = 0; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003894 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003895
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003896 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003897 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3898 ParseValue(Ty, Op0, PFS) ||
3899 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00003900 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003901 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3902 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003903
Chris Lattnerf4f03422009-12-30 05:27:33 +00003904 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003905 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3906 while (1) {
3907 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003908
Chris Lattner3822f632009-01-02 08:05:26 +00003909 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003910 break;
3911
Chris Lattnerf4f03422009-12-30 05:27:33 +00003912 if (Lex.getKind() == lltok::MetadataVar) {
3913 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00003914 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00003915 }
Devang Patel8f842d32009-10-16 18:45:49 +00003916
Chris Lattner3822f632009-01-02 08:05:26 +00003917 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003918 ParseValue(Ty, Op0, PFS) ||
3919 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00003920 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003921 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3922 return true;
3923 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003924
Chris Lattnerac161bf2009-01-02 07:01:27 +00003925 if (!Ty->isFirstClassType())
3926 return Error(TypeLoc, "phi node must have first class type");
3927
Jay Foad52131342011-03-30 11:28:46 +00003928 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003929 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3930 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3931 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00003932 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003933}
3934
Bill Wendlingfae14752011-08-12 20:24:12 +00003935/// ParseLandingPad
3936/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3937/// Clause
3938/// ::= 'catch' TypeAndValue
3939/// ::= 'filter'
3940/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3941bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3942 Type *Ty = 0; LocTy TyLoc;
3943 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00003944
3945 if (ParseType(Ty, TyLoc) ||
3946 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3947 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3948 return true;
3949
3950 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3951 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3952
3953 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3954 LandingPadInst::ClauseType CT;
3955 if (EatIfPresent(lltok::kw_catch))
3956 CT = LandingPadInst::Catch;
3957 else if (EatIfPresent(lltok::kw_filter))
3958 CT = LandingPadInst::Filter;
3959 else
3960 return TokError("expected 'catch' or 'filter' clause type");
3961
3962 Value *V; LocTy VLoc;
3963 if (ParseTypeAndValue(V, VLoc, PFS)) {
3964 delete LP;
3965 return true;
3966 }
3967
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00003968 // A 'catch' type expects a non-array constant. A filter clause expects an
3969 // array constant.
3970 if (CT == LandingPadInst::Catch) {
3971 if (isa<ArrayType>(V->getType()))
3972 Error(VLoc, "'catch' clause has an invalid type");
3973 } else {
3974 if (!isa<ArrayType>(V->getType()))
3975 Error(VLoc, "'filter' clause has an invalid type");
3976 }
3977
Bill Wendlingfae14752011-08-12 20:24:12 +00003978 LP->addClause(V);
3979 }
3980
3981 Inst = LP;
3982 return false;
3983}
3984
Chris Lattnerac161bf2009-01-02 07:01:27 +00003985/// ParseCall
3986/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3987/// ParameterList OptionalAttrs
3988bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3989 bool isTail) {
Bill Wendling50d27842012-10-15 20:35:56 +00003990 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003991 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003992 LocTy BuiltinLoc;
Sandeep Patel68c5f472009-09-02 08:44:58 +00003993 CallingConv::ID CC;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003994 Type *RetType = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003995 LocTy RetTypeLoc;
3996 ValID CalleeID;
3997 SmallVector<ParamInfo, 16> ArgList;
3998 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003999
Chris Lattnerac161bf2009-01-02 07:01:27 +00004000 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4001 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004002 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004003 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004004 ParseValID(CalleeID) ||
4005 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004006 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004007 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004008 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004009
Chris Lattnerac161bf2009-01-02 07:01:27 +00004010 // If RetType is a non-function pointer type, then this is the short syntax
4011 // for the call, which means that RetType is just the return type. Infer the
4012 // rest of the function argument types from the arguments that are present.
Chris Lattner229907c2011-07-18 04:54:35 +00004013 PointerType *PFTy = 0;
4014 FunctionType *Ty = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004015 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4016 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4017 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004018 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00004019 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4020 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004021
Chris Lattnerac161bf2009-01-02 07:01:27 +00004022 if (!FunctionType::isValidReturnType(RetType))
4023 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004024
Owen Anderson4056ca92009-07-29 22:17:13 +00004025 Ty = FunctionType::get(RetType, ParamTypes, false);
4026 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004027 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004028
Chris Lattnerac161bf2009-01-02 07:01:27 +00004029 // Look up the callee.
4030 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004031 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004032
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004033 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004034 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004035 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004036 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4037 AttributeSet::ReturnIndex,
4038 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004039
Chris Lattnerac161bf2009-01-02 07:01:27 +00004040 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004041
Chris Lattnerac161bf2009-01-02 07:01:27 +00004042 // Loop through FunctionType's arguments and ensure they are specified
4043 // correctly. Also, gather any parameter attributes.
4044 FunctionType::param_iterator I = Ty->param_begin();
4045 FunctionType::param_iterator E = Ty->param_end();
4046 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +00004047 Type *ExpectedTy = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004048 if (I != E) {
4049 ExpectedTy = *I++;
4050 } else if (!Ty->isVarArg()) {
4051 return Error(ArgList[i].Loc, "too many arguments specified");
4052 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004053
Chris Lattnerac161bf2009-01-02 07:01:27 +00004054 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4055 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004056 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004057 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004058 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4059 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004060 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4061 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004062 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004063
Chris Lattnerac161bf2009-01-02 07:01:27 +00004064 if (I != E)
4065 return Error(CallLoc, "not enough parameters specified for call");
4066
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004067 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004068 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4069 AttributeSet::FunctionIndex,
4070 FnAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004071
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004072 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004073 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004074
Jay Foad5bd375a2011-07-15 08:37:34 +00004075 CallInst *CI = CallInst::Create(Callee, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004076 CI->setTailCall(isTail);
4077 CI->setCallingConv(CC);
4078 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004079 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004080 Inst = CI;
4081 return false;
4082}
4083
4084//===----------------------------------------------------------------------===//
4085// Memory Instructions.
4086//===----------------------------------------------------------------------===//
4087
4088/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00004089/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00004090int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004091 Value *Size = 0;
Chris Lattner200e0752009-07-02 23:08:13 +00004092 LocTy SizeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004093 unsigned Alignment = 0;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004094 Type *Ty = 0;
David Majnemerc4ab61c2014-03-09 06:41:58 +00004095
4096 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4097
Chris Lattner3822f632009-01-02 08:05:26 +00004098 if (ParseType(Ty)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004099
Chris Lattnerb2f39502009-12-30 05:44:30 +00004100 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004101 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00004102 if (Lex.getKind() == lltok::kw_align) {
4103 if (ParseOptionalAlignment(Alignment)) return true;
4104 } else if (Lex.getKind() == lltok::MetadataVar) {
4105 AteExtraComma = true;
4106 } else {
4107 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4108 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4109 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004110 }
4111 }
4112
Dan Gohman2140a742010-05-28 01:14:11 +00004113 if (Size && !Size->getType()->isIntegerTy())
4114 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004115
Reid Kleckner436c42e2014-01-17 23:58:17 +00004116 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4117 AI->setUsedWithInAlloca(IsInAlloca);
4118 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00004119 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004120}
4121
4122/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00004123/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004124/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00004125/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004126int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004127 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004128 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004129 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004130 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004131 AtomicOrdering Ordering = NotAtomic;
4132 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004133
4134 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004135 isAtomic = true;
4136 Lex.Lex();
4137 }
4138
Chris Lattnerbc639292011-11-27 06:56:53 +00004139 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004140 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004141 isVolatile = true;
4142 Lex.Lex();
4143 }
4144
Chris Lattnerb2f39502009-12-30 05:44:30 +00004145 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004146 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004147 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4148 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004149
Duncan Sands19d0b472010-02-16 11:11:14 +00004150 if (!Val->getType()->isPointerTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004151 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4152 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00004153 if (isAtomic && !Alignment)
4154 return Error(Loc, "atomic load must have explicit non-zero alignment");
4155 if (Ordering == Release || Ordering == AcquireRelease)
4156 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004157
Eli Friedman59b66882011-08-09 23:02:53 +00004158 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004159 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004160}
4161
4162/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00004163
4164/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4165/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00004166/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004167int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004168 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004169 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004170 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004171 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004172 AtomicOrdering Ordering = NotAtomic;
4173 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004174
4175 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004176 isAtomic = true;
4177 Lex.Lex();
4178 }
4179
Chris Lattnerbc639292011-11-27 06:56:53 +00004180 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004181 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004182 isVolatile = true;
4183 Lex.Lex();
4184 }
4185
Chris Lattnerac161bf2009-01-02 07:01:27 +00004186 if (ParseTypeAndValue(Val, Loc, PFS) ||
4187 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004188 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004189 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004190 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004191 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00004192
Duncan Sands19d0b472010-02-16 11:11:14 +00004193 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004194 return Error(PtrLoc, "store operand must be a pointer");
4195 if (!Val->getType()->isFirstClassType())
4196 return Error(Loc, "store operand must be a first class value");
4197 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4198 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00004199 if (isAtomic && !Alignment)
4200 return Error(Loc, "atomic store must have explicit non-zero alignment");
4201 if (Ordering == Acquire || Ordering == AcquireRelease)
4202 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004203
Eli Friedman59b66882011-08-09 23:02:53 +00004204 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004205 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004206}
4207
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004208/// ParseCmpXchg
Eli Friedman02e737b2011-08-12 22:50:01 +00004209/// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
Tim Northovere94a5182014-03-11 10:48:52 +00004210/// 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00004211int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004212 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4213 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00004214 AtomicOrdering SuccessOrdering = NotAtomic;
4215 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004216 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004217 bool isVolatile = false;
4218
4219 if (EatIfPresent(lltok::kw_volatile))
4220 isVolatile = true;
4221
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004222 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4223 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4224 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4225 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4226 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00004227 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4228 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004229 return true;
4230
Tim Northovere94a5182014-03-11 10:48:52 +00004231 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004232 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00004233 if (SuccessOrdering < FailureOrdering)
4234 return TokError("cmpxchg must be at least as ordered on success as failure");
4235 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4236 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004237 if (!Ptr->getType()->isPointerTy())
4238 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4239 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4240 return Error(CmpLoc, "compare value and pointer type do not match");
4241 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4242 return Error(NewLoc, "new value and pointer type do not match");
4243 if (!New->getType()->isIntegerTy())
4244 return Error(NewLoc, "cmpxchg operand must be an integer");
4245 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4246 if (Size < 8 || (Size & (Size - 1)))
4247 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4248 " integer");
4249
Tim Northovere94a5182014-03-11 10:48:52 +00004250 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
4251 FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004252 CXI->setVolatile(isVolatile);
4253 Inst = CXI;
4254 return AteExtraComma ? InstExtraComma : InstNormal;
4255}
4256
4257/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00004258/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4259/// 'singlethread'? AtomicOrdering
4260int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004261 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4262 bool AteExtraComma = false;
4263 AtomicOrdering Ordering = NotAtomic;
4264 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004265 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004266 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00004267
4268 if (EatIfPresent(lltok::kw_volatile))
4269 isVolatile = true;
4270
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004271 switch (Lex.getKind()) {
4272 default: return TokError("expected binary operation in atomicrmw");
4273 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4274 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4275 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4276 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4277 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4278 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4279 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4280 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4281 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4282 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4283 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4284 }
4285 Lex.Lex(); // Eat the operation.
4286
4287 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4288 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4289 ParseTypeAndValue(Val, ValLoc, PFS) ||
4290 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4291 return true;
4292
4293 if (Ordering == Unordered)
4294 return TokError("atomicrmw cannot be unordered");
4295 if (!Ptr->getType()->isPointerTy())
4296 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4297 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4298 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4299 if (!Val->getType()->isIntegerTy())
4300 return Error(ValLoc, "atomicrmw operand must be an integer");
4301 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4302 if (Size < 8 || (Size & (Size - 1)))
4303 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4304 " integer");
4305
4306 AtomicRMWInst *RMWI =
4307 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4308 RMWI->setVolatile(isVolatile);
4309 Inst = RMWI;
4310 return AteExtraComma ? InstExtraComma : InstNormal;
4311}
4312
Eli Friedmanfee02c62011-07-25 23:16:38 +00004313/// ParseFence
4314/// ::= 'fence' 'singlethread'? AtomicOrdering
4315int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4316 AtomicOrdering Ordering = NotAtomic;
4317 SynchronizationScope Scope = CrossThread;
4318 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4319 return true;
4320
4321 if (Ordering == Unordered)
4322 return TokError("fence cannot be unordered");
4323 if (Ordering == Monotonic)
4324 return TokError("fence cannot be monotonic");
4325
4326 Inst = new FenceInst(Context, Ordering, Scope);
4327 return InstNormal;
4328}
4329
Chris Lattnerac161bf2009-01-02 07:01:27 +00004330/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00004331/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004332int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00004333 Value *Ptr = 0;
4334 Value *Val = 0;
4335 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00004336
Dan Gohman16cbbe42009-07-29 15:58:36 +00004337 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00004338
Chris Lattner3822f632009-01-02 08:05:26 +00004339 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004340
Eli Benderskyd9806682013-04-22 17:03:42 +00004341 Type *BaseType = Ptr->getType();
4342 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4343 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004344 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004345
Chris Lattnerac161bf2009-01-02 07:01:27 +00004346 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004347 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004348 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00004349 if (Lex.getKind() == lltok::MetadataVar) {
4350 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00004351 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004352 }
Chris Lattner3822f632009-01-02 08:05:26 +00004353 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004354 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004355 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00004356 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4357 return Error(EltLoc, "getelementptr index type missmatch");
4358 if (Val->getType()->isVectorTy()) {
4359 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4360 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4361 if (ValNumEl != PtrNumEl)
4362 return Error(EltLoc,
4363 "getelementptr vector index has a wrong number of elements");
4364 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004365 Indices.push_back(Val);
4366 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004367
Eli Benderskyd9806682013-04-22 17:03:42 +00004368 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4369 return Error(Loc, "base element of getelementptr must be sized");
4370
4371 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004372 return Error(Loc, "invalid getelementptr indices");
Jay Foadd1b78492011-07-25 09:48:08 +00004373 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00004374 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004375 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004376 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004377}
4378
4379/// ParseExtractValue
4380/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004381int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004382 Value *Val; LocTy Loc;
4383 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004384 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004385 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004386 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004387 return true;
4388
Chris Lattner392be582010-02-12 20:49:41 +00004389 if (!Val->getType()->isAggregateType())
4390 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004391
Jay Foad57aa6362011-07-13 10:26:04 +00004392 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004393 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004394 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004395 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004396}
4397
4398/// ParseInsertValue
4399/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004400int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004401 Value *Val0, *Val1; LocTy Loc0, Loc1;
4402 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004403 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004404 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4405 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4406 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004407 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004408 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004409
Chris Lattner392be582010-02-12 20:49:41 +00004410 if (!Val0->getType()->isAggregateType())
4411 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004412
Jay Foad57aa6362011-07-13 10:26:04 +00004413 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004414 return Error(Loc0, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004415 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004416 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004417}
Nick Lewycky49f89192009-04-04 07:22:01 +00004418
4419//===----------------------------------------------------------------------===//
4420// Embedded metadata.
4421//===----------------------------------------------------------------------===//
4422
4423/// ParseMDNodeVector
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004424/// ::= Element (',' Element)*
4425/// Element
4426/// ::= 'null' | TypeAndValue
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00004427bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandezb8fd1522010-01-10 07:14:18 +00004428 PerFunctionState *PFS) {
Dan Gohman1e0213a2010-07-13 19:33:27 +00004429 // Check for an empty list.
4430 if (Lex.getKind() == lltok::rbrace)
4431 return false;
4432
Nick Lewycky49f89192009-04-04 07:22:01 +00004433 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004434 // Null is a special case since it is typeless.
4435 if (EatIfPresent(lltok::kw_null)) {
4436 Elts.push_back(0);
4437 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004438 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004439
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004440 Value *V = 0;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004441 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004442 Elts.push_back(V);
Nick Lewycky49f89192009-04-04 07:22:01 +00004443 } while (EatIfPresent(lltok::comma));
4444
4445 return false;
4446}