blob: b53b4ce7c0e0b238f254add1f56538927f38aeb3 [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:
1315 Lex.Lex();
1316 // treat linker_private and linker_private_weak as PrivateLinkage
1317 Res = GlobalValue::PrivateLinkage;
1318 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001319 }
1320 Lex.Lex();
1321 HasLinkage = true;
1322 return false;
1323}
1324
1325/// ParseOptionalVisibility
1326/// ::= /*empty*/
1327/// ::= 'default'
1328/// ::= 'hidden'
1329/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001330///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001331bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1332 switch (Lex.getKind()) {
1333 default: Res = GlobalValue::DefaultVisibility; return false;
1334 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1335 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1336 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1337 }
1338 Lex.Lex();
1339 return false;
1340}
1341
Nico Rieck7157bb72014-01-14 15:22:47 +00001342/// ParseOptionalDLLStorageClass
1343/// ::= /*empty*/
1344/// ::= 'dllimport'
1345/// ::= 'dllexport'
1346///
1347bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1348 switch (Lex.getKind()) {
1349 default: Res = GlobalValue::DefaultStorageClass; return false;
1350 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1351 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1352 }
1353 Lex.Lex();
1354 return false;
1355}
1356
Chris Lattnerac161bf2009-01-02 07:01:27 +00001357/// ParseOptionalCallingConv
1358/// ::= /*empty*/
1359/// ::= 'ccc'
1360/// ::= 'fastcc'
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001361/// ::= 'kw_intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001362/// ::= 'coldcc'
1363/// ::= 'x86_stdcallcc'
1364/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001365/// ::= 'x86_thiscallcc'
Reid Kleckner1c843222014-01-31 17:41:22 +00001366/// ::= 'x86_cdeclmethodcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001367/// ::= 'arm_apcscc'
1368/// ::= 'arm_aapcscc'
1369/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001370/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001371/// ::= 'ptx_kernel'
1372/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001373/// ::= 'spir_func'
1374/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001375/// ::= 'x86_64_sysvcc'
1376/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001377/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001378/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001379/// ::= 'preserve_mostcc'
1380/// ::= 'preserve_allcc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001381/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001382///
Sandeep Patel68c5f472009-09-02 08:44:58 +00001383bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001384 switch (Lex.getKind()) {
1385 default: CC = CallingConv::C; return false;
1386 case lltok::kw_ccc: CC = CallingConv::C; break;
1387 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1388 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1389 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1390 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001391 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner1c843222014-01-31 17:41:22 +00001392 case lltok::kw_x86_cdeclmethodcc:CC = CallingConv::X86_CDeclMethod; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001393 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1394 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1395 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001396 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001397 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1398 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001399 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1400 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001401 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001402 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1403 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001404 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001405 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001406 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1407 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001408 case lltok::kw_cc: {
1409 unsigned ArbitraryCC;
1410 Lex.Lex();
David Blaikie46a9f012012-01-20 21:51:11 +00001411 if (ParseUInt32(ArbitraryCC))
Sandeep Patel68c5f472009-09-02 08:44:58 +00001412 return true;
David Blaikie46a9f012012-01-20 21:51:11 +00001413 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1414 return false;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001415 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001416 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001417
Chris Lattnerac161bf2009-01-02 07:01:27 +00001418 Lex.Lex();
1419 return false;
1420}
1421
Chris Lattner5c427632009-12-30 05:31:19 +00001422/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001423/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001424bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1425 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001426 do {
1427 if (Lex.getKind() != lltok::MetadataVar)
1428 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001429
Chris Lattner596760d2009-12-29 21:25:40 +00001430 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001431 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001432 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001433
Chris Lattner1797fc72009-12-29 21:53:55 +00001434 MDNode *Node;
Chris Lattner8eff0152010-04-01 05:14:45 +00001435 SMLoc Loc = Lex.getLoc();
Dan Gohmanc828c542010-08-24 02:24:03 +00001436
1437 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001438 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001439
Dan Gohmanf0715b12010-08-24 14:35:45 +00001440 // This code is similar to that of ParseMetadataValue, however it needs to
1441 // have special-case code for a forward reference; see the comments on
1442 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1443 // at the top level here.
Dan Gohmanc828c542010-08-24 02:24:03 +00001444 if (Lex.getKind() == lltok::lbrace) {
1445 ValID ID;
1446 if (ParseMetadataListValue(ID, PFS))
1447 return true;
1448 assert(ID.Kind == ValID::t_MDNode);
1449 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner8eff0152010-04-01 05:14:45 +00001450 } else {
Nick Lewycky912888f2010-09-30 21:04:13 +00001451 unsigned NodeID = 0;
Dan Gohmanc828c542010-08-24 02:24:03 +00001452 if (ParseMDNodeID(Node, NodeID))
1453 return true;
1454 if (Node) {
1455 // If we got the node, add it to the instruction.
1456 Inst->setMetadata(MDK, Node);
1457 } else {
1458 MDRef R = { Loc, MDK, NodeID };
1459 // Otherwise, remember that this should be resolved later.
1460 ForwardRefInstMetadata[Inst].push_back(R);
1461 }
Chris Lattner8eff0152010-04-01 05:14:45 +00001462 }
Chris Lattner596760d2009-12-29 21:25:40 +00001463
Manman Ren209b17c2013-09-28 00:22:27 +00001464 if (MDK == LLVMContext::MD_tbaa)
1465 InstsWithTBAATag.push_back(Inst);
1466
Chris Lattner596760d2009-12-29 21:25:40 +00001467 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001468 } while (EatIfPresent(lltok::comma));
1469 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001470}
1471
Chris Lattnerac161bf2009-01-02 07:01:27 +00001472/// ParseOptionalAlignment
1473/// ::= /* empty */
1474/// ::= 'align' 4
1475bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1476 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001477 if (!EatIfPresent(lltok::kw_align))
1478 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001479 LocTy AlignLoc = Lex.getLoc();
1480 if (ParseUInt32(Alignment)) return true;
1481 if (!isPowerOf2_32(Alignment))
1482 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001483 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001484 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001485 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001486}
1487
Chris Lattnerb2f39502009-12-30 05:44:30 +00001488/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001489/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001490/// ::= ',' align 4
1491///
1492/// This returns with AteExtraComma set to true if it ate an excess comma at the
1493/// end.
1494bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1495 bool &AteExtraComma) {
1496 AteExtraComma = false;
1497 while (EatIfPresent(lltok::comma)) {
1498 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001499 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001500 AteExtraComma = true;
1501 return false;
1502 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001503
Chris Lattner95b0ff42010-04-23 00:50:50 +00001504 if (Lex.getKind() != lltok::kw_align)
1505 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001506
Chris Lattner95b0ff42010-04-23 00:50:50 +00001507 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001508 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001509
Devang Patelea8a4b92009-09-17 23:04:48 +00001510 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001511}
1512
Eli Friedmanfee02c62011-07-25 23:16:38 +00001513/// ParseScopeAndOrdering
1514/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1515/// else: ::=
1516///
1517/// This sets Scope and Ordering to the parsed values.
1518bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1519 AtomicOrdering &Ordering) {
1520 if (!isAtomic)
1521 return false;
1522
1523 Scope = CrossThread;
1524 if (EatIfPresent(lltok::kw_singlethread))
1525 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001526
1527 return ParseOrdering(Ordering);
1528}
1529
1530/// ParseOrdering
1531/// ::= AtomicOrdering
1532///
1533/// This sets Ordering to the parsed value.
1534bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001535 switch (Lex.getKind()) {
1536 default: return TokError("Expected ordering on atomic instruction");
1537 case lltok::kw_unordered: Ordering = Unordered; break;
1538 case lltok::kw_monotonic: Ordering = Monotonic; break;
1539 case lltok::kw_acquire: Ordering = Acquire; break;
1540 case lltok::kw_release: Ordering = Release; break;
1541 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1542 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1543 }
1544 Lex.Lex();
1545 return false;
1546}
1547
Charles Davisbe5557e2010-02-12 00:31:15 +00001548/// ParseOptionalStackAlignment
1549/// ::= /* empty */
1550/// ::= 'alignstack' '(' 4 ')'
1551bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1552 Alignment = 0;
1553 if (!EatIfPresent(lltok::kw_alignstack))
1554 return false;
1555 LocTy ParenLoc = Lex.getLoc();
1556 if (!EatIfPresent(lltok::lparen))
1557 return Error(ParenLoc, "expected '('");
1558 LocTy AlignLoc = Lex.getLoc();
1559 if (ParseUInt32(Alignment)) return true;
1560 ParenLoc = Lex.getLoc();
1561 if (!EatIfPresent(lltok::rparen))
1562 return Error(ParenLoc, "expected ')'");
1563 if (!isPowerOf2_32(Alignment))
1564 return Error(AlignLoc, "stack alignment is not a power of two");
1565 return false;
1566}
Devang Patelea8a4b92009-09-17 23:04:48 +00001567
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001568/// ParseIndexList - This parses the index list for an insert/extractvalue
1569/// instruction. This sets AteExtraComma in the case where we eat an extra
1570/// comma at the end of the line and find that it is followed by metadata.
1571/// Clients that don't allow metadata can call the version of this function that
1572/// only takes one argument.
1573///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001574/// ParseIndexList
1575/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001576///
1577bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1578 bool &AteExtraComma) {
1579 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001580
Chris Lattnerac161bf2009-01-02 07:01:27 +00001581 if (Lex.getKind() != lltok::comma)
1582 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001583
Chris Lattner3822f632009-01-02 08:05:26 +00001584 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001585 if (Lex.getKind() == lltok::MetadataVar) {
1586 AteExtraComma = true;
1587 return false;
1588 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001589 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001590 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001591 Indices.push_back(Idx);
1592 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001593
Chris Lattnerac161bf2009-01-02 07:01:27 +00001594 return false;
1595}
1596
1597//===----------------------------------------------------------------------===//
1598// Type Parsing.
1599//===----------------------------------------------------------------------===//
1600
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001601/// ParseType - Parse a type.
1602bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1603 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001604 switch (Lex.getKind()) {
1605 default:
1606 return TokError("expected type");
1607 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001608 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001609 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001610 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001611 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001612 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001613 // Type ::= StructType
1614 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001615 return true;
1616 break;
1617 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001618 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001619 Lex.Lex(); // eat the lsquare.
1620 if (ParseArrayVectorType(Result, false))
1621 return true;
1622 break;
1623 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001624 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001625 Lex.Lex();
1626 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001627 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001628 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001629 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001630 } else if (ParseArrayVectorType(Result, true))
1631 return true;
1632 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001633 case lltok::LocalVar: {
1634 // Type ::= %foo
1635 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001636
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001637 // If the type hasn't been defined yet, create a forward definition and
1638 // remember where that forward def'n was seen (in case it never is defined).
1639 if (Entry.first == 0) {
Chris Lattner335d3992011-08-12 18:06:37 +00001640 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001641 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001642 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001643 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001644 Lex.Lex();
1645 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001646 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001647
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001648 case lltok::LocalVarID: {
1649 // Type ::= %4
1650 if (Lex.getUIntVal() >= NumberedTypes.size())
1651 NumberedTypes.resize(Lex.getUIntVal()+1);
1652 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001653
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001654 // If the type hasn't been defined yet, create a forward definition and
1655 // remember where that forward def'n was seen (in case it never is defined).
1656 if (Entry.first == 0) {
Chris Lattner335d3992011-08-12 18:06:37 +00001657 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001658 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001659 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001660 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001661 Lex.Lex();
1662 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001663 }
1664 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001665
1666 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001667 while (1) {
1668 switch (Lex.getKind()) {
1669 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001670 default:
1671 if (!AllowVoid && Result->isVoidTy())
1672 return Error(TypeLoc, "void type only allowed for function results");
1673 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001674
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001675 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001676 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001677 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001678 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001679 if (Result->isVoidTy())
1680 return TokError("pointers to void are invalid - use i8* instead");
1681 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001682 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001683 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001684 Lex.Lex();
1685 break;
1686
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001687 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001688 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001689 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001690 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001691 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001692 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001693 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001694 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001695 unsigned AddrSpace;
1696 if (ParseOptionalAddrSpace(AddrSpace) ||
1697 ParseToken(lltok::star, "expected '*' in address space"))
1698 return true;
1699
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001700 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001701 break;
1702 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001703
Chris Lattnerac161bf2009-01-02 07:01:27 +00001704 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1705 case lltok::lparen:
1706 if (ParseFunctionType(Result))
1707 return true;
1708 break;
1709 }
1710 }
1711}
1712
1713/// ParseParameterList
1714/// ::= '(' ')'
1715/// ::= '(' Arg (',' Arg)* ')'
1716/// Arg
1717/// ::= Type OptionalAttributes Value OptionalAttributes
1718bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1719 PerFunctionState &PFS) {
1720 if (ParseToken(lltok::lparen, "expected '(' in call"))
1721 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001722
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001723 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001724 while (Lex.getKind() != lltok::rparen) {
1725 // If this isn't the first argument, we need a comma.
1726 if (!ArgList.empty() &&
1727 ParseToken(lltok::comma, "expected ',' in argument list"))
1728 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001729
Chris Lattnerac161bf2009-01-02 07:01:27 +00001730 // Parse the argument.
1731 LocTy ArgLoc;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001732 Type *ArgTy = 0;
Bill Wendling50d27842012-10-15 20:35:56 +00001733 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001734 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001735 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001736 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001737
Chris Lattner5b4a9622009-12-30 02:11:14 +00001738 // Otherwise, handle normal operands.
Bill Wendling34c2eb22012-12-04 23:40:58 +00001739 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
Chris Lattner5b4a9622009-12-30 02:11:14 +00001740 return true;
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001741 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1742 AttrIndex++,
1743 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001744 }
1745
1746 Lex.Lex(); // Lex the ')'.
1747 return false;
1748}
1749
1750
1751
Chris Lattner2ed06b42009-01-05 18:34:07 +00001752/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001753/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001754/// ::= '(' ArgTypeListI ')'
1755/// ArgTypeListI
1756/// ::= /*empty*/
1757/// ::= '...'
1758/// ::= ArgTypeList ',' '...'
1759/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001760///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001761bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1762 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001763 isVarArg = false;
1764 assert(Lex.getKind() == lltok::lparen);
1765 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001766
Chris Lattnerac161bf2009-01-02 07:01:27 +00001767 if (Lex.getKind() == lltok::rparen) {
1768 // empty
1769 } else if (Lex.getKind() == lltok::dotdotdot) {
1770 isVarArg = true;
1771 Lex.Lex();
1772 } else {
1773 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001774 Type *ArgTy = 0;
Bill Wendling50d27842012-10-15 20:35:56 +00001775 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001776 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001777
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001778 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001779 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001780
Chris Lattnerfdd87902009-10-05 05:54:46 +00001781 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001782 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001783
Chris Lattnerdef19492011-06-17 06:36:20 +00001784 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001785 Name = Lex.getStrVal();
1786 Lex.Lex();
1787 }
Chris Lattner3822f632009-01-02 08:05:26 +00001788
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001789 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001790 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001791
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001792 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001793 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001794 AttributeSet::get(ArgTy->getContext(),
1795 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001796
Chris Lattner3822f632009-01-02 08:05:26 +00001797 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001798 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001799 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001800 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001801 break;
1802 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001803
Chris Lattnerac161bf2009-01-02 07:01:27 +00001804 // Otherwise must be an argument type.
1805 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001806 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001807
Chris Lattnerfdd87902009-10-05 05:54:46 +00001808 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001809 return Error(TypeLoc, "argument can not have void type");
1810
Chris Lattnerdef19492011-06-17 06:36:20 +00001811 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001812 Name = Lex.getStrVal();
1813 Lex.Lex();
1814 } else {
1815 Name = "";
1816 }
Chris Lattner3822f632009-01-02 08:05:26 +00001817
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001818 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001819 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001820
Bill Wendlingd079a442012-10-15 04:46:55 +00001821 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001822 AttributeSet::get(ArgTy->getContext(),
1823 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001824 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001825 }
1826 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001827
Chris Lattner3822f632009-01-02 08:05:26 +00001828 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001829}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001830
Chris Lattnerac161bf2009-01-02 07:01:27 +00001831/// ParseFunctionType
1832/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001833bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001834 assert(Lex.getKind() == lltok::lparen);
1835
Chris Lattnerce473c72009-01-05 08:04:33 +00001836 if (!FunctionType::isValidReturnType(Result))
1837 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001838
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001839 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001840 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001841 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001842 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001843
Chris Lattnerac161bf2009-01-02 07:01:27 +00001844 // Reject names on the arguments lists.
1845 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1846 if (!ArgList[i].Name.empty())
1847 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001848 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001849 return Error(ArgList[i].Loc,
1850 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001851 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001852
Jay Foadb804a2b2011-07-12 14:06:48 +00001853 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001854 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001855 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001856
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001857 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001858 return false;
1859}
1860
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001861/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1862/// other structs.
1863bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1864 SmallVector<Type*, 8> Elts;
1865 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001866
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001867 Result = StructType::get(Context, Elts, Packed);
1868 return false;
1869}
1870
1871/// ParseStructDefinition - Parse a struct in a 'type' definition.
1872bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1873 std::pair<Type*, LocTy> &Entry,
1874 Type *&ResultTy) {
1875 // If the type was already defined, diagnose the redefinition.
1876 if (Entry.first && !Entry.second.isValid())
1877 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001878
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001879 // If we have opaque, just return without filling in the definition for the
1880 // struct. This counts as a definition as far as the .ll file goes.
1881 if (EatIfPresent(lltok::kw_opaque)) {
1882 // This type is being defined, so clear the location to indicate this.
1883 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001884
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001885 // If this type number has never been uttered, create it.
1886 if (Entry.first == 0)
Chris Lattner335d3992011-08-12 18:06:37 +00001887 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001888 ResultTy = Entry.first;
1889 return false;
1890 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001891
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001892 // If the type starts with '<', then it is either a packed struct or a vector.
1893 bool isPacked = EatIfPresent(lltok::less);
1894
1895 // If we don't have a struct, then we have a random type alias, which we
1896 // accept for compatibility with old files. These types are not allowed to be
1897 // forward referenced and not allowed to be recursive.
1898 if (Lex.getKind() != lltok::lbrace) {
1899 if (Entry.first)
1900 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001901
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001902 ResultTy = 0;
1903 if (isPacked)
1904 return ParseArrayVectorType(ResultTy, true);
1905 return ParseType(ResultTy);
1906 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001907
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001908 // This type is being defined, so clear the location to indicate this.
1909 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001910
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001911 // If this type number has never been uttered, create it.
1912 if (Entry.first == 0)
Chris Lattner335d3992011-08-12 18:06:37 +00001913 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001914
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001915 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001916
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001917 SmallVector<Type*, 8> Body;
1918 if (ParseStructBody(Body) ||
1919 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1920 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001921
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001922 STy->setBody(Body, isPacked);
1923 ResultTy = STy;
1924 return false;
1925}
1926
1927
Chris Lattnerac161bf2009-01-02 07:01:27 +00001928/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001929/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00001930/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001931/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001932/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001933/// ::= '<' '{' Type (',' Type)* '}' '>'
1934bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001935 assert(Lex.getKind() == lltok::lbrace);
1936 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001937
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001938 // Handle the empty struct.
1939 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001940 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001941
Chris Lattnerf880ca22009-03-09 04:49:14 +00001942 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001943 Type *Ty = 0;
1944 if (ParseType(Ty)) return true;
1945 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001946
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001947 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001948 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001949
Chris Lattner3822f632009-01-02 08:05:26 +00001950 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00001951 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001952 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001953
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001954 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001955 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001956
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001957 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001958 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001959
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001960 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001961}
1962
1963/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1964/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001965/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00001966/// ::= '[' APSINTVAL 'x' Types ']'
1967/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001968bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001969 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1970 Lex.getAPSIntVal().getBitWidth() > 64)
1971 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001972
Chris Lattnerac161bf2009-01-02 07:01:27 +00001973 LocTy SizeLoc = Lex.getLoc();
1974 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00001975 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001976
Chris Lattner3822f632009-01-02 08:05:26 +00001977 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1978 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001979
1980 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001981 Type *EltTy = 0;
1982 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00001983
Chris Lattner3822f632009-01-02 08:05:26 +00001984 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1985 "expected end of sequential type"))
1986 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001987
Chris Lattnerac161bf2009-01-02 07:01:27 +00001988 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00001989 if (Size == 0)
1990 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001991 if ((unsigned)Size != Size)
1992 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001993 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00001994 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00001995 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001996 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001997 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001998 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001999 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002000 }
2001 return false;
2002}
2003
2004//===----------------------------------------------------------------------===//
2005// Function Semantic Analysis.
2006//===----------------------------------------------------------------------===//
2007
Chris Lattner3432c622009-10-28 03:39:23 +00002008LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2009 int functionNumber)
2010 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002011
2012 // Insert unnamed arguments into the NumberedVals list.
2013 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2014 AI != E; ++AI)
2015 if (!AI->hasName())
2016 NumberedVals.push_back(AI);
2017}
2018
2019LLParser::PerFunctionState::~PerFunctionState() {
2020 // If there were any forward referenced non-basicblock values, delete them.
2021 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2022 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2023 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002024 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002025 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002026 delete I->second.first;
2027 I->second.first = 0;
2028 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002029
Chris Lattnerac161bf2009-01-02 07:01:27 +00002030 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2031 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2032 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002033 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002034 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002035 delete I->second.first;
2036 I->second.first = 0;
2037 }
2038}
2039
Chris Lattner3432c622009-10-28 03:39:23 +00002040bool LLParser::PerFunctionState::FinishFunction() {
2041 // Check to see if someone took the address of labels in this block.
2042 if (!P.ForwardRefBlockAddresses.empty()) {
2043 ValID FunctionID;
2044 if (!F.getName().empty()) {
2045 FunctionID.Kind = ValID::t_GlobalName;
2046 FunctionID.StrVal = F.getName();
2047 } else {
2048 FunctionID.Kind = ValID::t_GlobalID;
2049 FunctionID.UIntVal = FunctionNumber;
2050 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002051
Chris Lattner3432c622009-10-28 03:39:23 +00002052 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2053 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2054 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2055 // Resolve all these references.
2056 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2057 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002058
Chris Lattner3432c622009-10-28 03:39:23 +00002059 P.ForwardRefBlockAddresses.erase(FRBAI);
2060 }
2061 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002062
Chris Lattnerac161bf2009-01-02 07:01:27 +00002063 if (!ForwardRefVals.empty())
2064 return P.Error(ForwardRefVals.begin()->second.second,
2065 "use of undefined value '%" + ForwardRefVals.begin()->first +
2066 "'");
2067 if (!ForwardRefValIDs.empty())
2068 return P.Error(ForwardRefValIDs.begin()->second.second,
2069 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002070 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002071 return false;
2072}
2073
2074
2075/// GetVal - Get a value with the specified name or ID, creating a
2076/// forward reference record if needed. This can return null if the value
2077/// exists but does not have the right type.
2078Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002079 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002080 // Look this name up in the normal function symbol table.
2081 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002082
Chris Lattnerac161bf2009-01-02 07:01:27 +00002083 // If this is a forward reference for the value, see if we already created a
2084 // forward ref record.
2085 if (Val == 0) {
2086 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2087 I = ForwardRefVals.find(Name);
2088 if (I != ForwardRefVals.end())
2089 Val = I->second.first;
2090 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002091
Chris Lattnerac161bf2009-01-02 07:01:27 +00002092 // If we have the value in the symbol table or fwd-ref table, return it.
2093 if (Val) {
2094 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002095 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002096 P.Error(Loc, "'%" + Name + "' is not a basic block");
2097 else
2098 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002099 getTypeString(Val->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002100 return 0;
2101 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002102
Chris Lattnerac161bf2009-01-02 07:01:27 +00002103 // Don't make placeholders with invalid type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002104 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002105 P.Error(Loc, "invalid use of a non-first-class type");
2106 return 0;
2107 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002108
Chris Lattnerac161bf2009-01-02 07:01:27 +00002109 // Otherwise, create a new forward reference for this value and remember it.
2110 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002111 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002112 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002113 else
2114 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002115
Chris Lattnerac161bf2009-01-02 07:01:27 +00002116 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2117 return FwdVal;
2118}
2119
Chris Lattner229907c2011-07-18 04:54:35 +00002120Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002121 LocTy Loc) {
2122 // Look this name up in the normal function symbol table.
2123 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002124
Chris Lattnerac161bf2009-01-02 07:01:27 +00002125 // If this is a forward reference for the value, see if we already created a
2126 // forward ref record.
2127 if (Val == 0) {
2128 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2129 I = ForwardRefValIDs.find(ID);
2130 if (I != ForwardRefValIDs.end())
2131 Val = I->second.first;
2132 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002133
Chris Lattnerac161bf2009-01-02 07:01:27 +00002134 // If we have the value in the symbol table or fwd-ref table, return it.
2135 if (Val) {
2136 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002137 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002138 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002139 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002140 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002141 getTypeString(Val->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002142 return 0;
2143 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002144
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002145 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002146 P.Error(Loc, "invalid use of a non-first-class type");
2147 return 0;
2148 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002149
Chris Lattnerac161bf2009-01-02 07:01:27 +00002150 // Otherwise, create a new forward reference for this value and remember it.
2151 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002152 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002153 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002154 else
2155 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002156
Chris Lattnerac161bf2009-01-02 07:01:27 +00002157 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2158 return FwdVal;
2159}
2160
2161/// SetInstName - After an instruction is parsed and inserted into its
2162/// basic block, this installs its name.
2163bool LLParser::PerFunctionState::SetInstName(int NameID,
2164 const std::string &NameStr,
2165 LocTy NameLoc, Instruction *Inst) {
2166 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002167 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002168 if (NameID != -1 || !NameStr.empty())
2169 return P.Error(NameLoc, "instructions returning void cannot have a name");
2170 return false;
2171 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002172
Chris Lattnerac161bf2009-01-02 07:01:27 +00002173 // If this was a numbered instruction, verify that the instruction is the
2174 // expected value and resolve any forward references.
2175 if (NameStr.empty()) {
2176 // If neither a name nor an ID was specified, just use the next ID.
2177 if (NameID == -1)
2178 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002179
Chris Lattnerac161bf2009-01-02 07:01:27 +00002180 if (unsigned(NameID) != NumberedVals.size())
2181 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002182 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002183
Chris Lattnerac161bf2009-01-02 07:01:27 +00002184 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2185 ForwardRefValIDs.find(NameID);
2186 if (FI != ForwardRefValIDs.end()) {
2187 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002188 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002189 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002190 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002191 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002192 ForwardRefValIDs.erase(FI);
2193 }
2194
2195 NumberedVals.push_back(Inst);
2196 return false;
2197 }
2198
2199 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2200 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2201 FI = ForwardRefVals.find(NameStr);
2202 if (FI != ForwardRefVals.end()) {
2203 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002204 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002205 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002206 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002207 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002208 ForwardRefVals.erase(FI);
2209 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002210
Chris Lattnerac161bf2009-01-02 07:01:27 +00002211 // Set the name on the instruction.
2212 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002213
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002214 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002215 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002216 NameStr + "'");
2217 return false;
2218}
2219
2220/// GetBB - Get a basic block with the specified name or ID, creating a
2221/// forward reference record if needed.
2222BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2223 LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002224 return cast_or_null<BasicBlock>(GetVal(Name,
2225 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002226}
2227
2228BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002229 return cast_or_null<BasicBlock>(GetVal(ID,
2230 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002231}
2232
2233/// DefineBB - Define the specified basic block, which is either named or
2234/// unnamed. If there is an error, this returns null otherwise it returns
2235/// the block being defined.
2236BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2237 LocTy Loc) {
2238 BasicBlock *BB;
2239 if (Name.empty())
2240 BB = GetBB(NumberedVals.size(), Loc);
2241 else
2242 BB = GetBB(Name, Loc);
2243 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002244
Chris Lattnerac161bf2009-01-02 07:01:27 +00002245 // Move the block to the end of the function. Forward ref'd blocks are
2246 // inserted wherever they happen to be referenced.
2247 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002248
Chris Lattnerac161bf2009-01-02 07:01:27 +00002249 // Remove the block from forward ref sets.
2250 if (Name.empty()) {
2251 ForwardRefValIDs.erase(NumberedVals.size());
2252 NumberedVals.push_back(BB);
2253 } else {
2254 // BB forward references are already in the function symbol table.
2255 ForwardRefVals.erase(Name);
2256 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002257
Chris Lattnerac161bf2009-01-02 07:01:27 +00002258 return BB;
2259}
2260
2261//===----------------------------------------------------------------------===//
2262// Constants.
2263//===----------------------------------------------------------------------===//
2264
2265/// ParseValID - Parse an abstract value that doesn't necessarily have a
2266/// type implied. For example, if we parse "4" we don't know what integer type
2267/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002268/// sanity. PFS is used to convert function-local operands of metadata (since
2269/// metadata operands are not just parsed here but also converted to values).
2270/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002271bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002272 ID.Loc = Lex.getLoc();
2273 switch (Lex.getKind()) {
2274 default: return TokError("expected value token");
2275 case lltok::GlobalID: // @42
2276 ID.UIntVal = Lex.getUIntVal();
2277 ID.Kind = ValID::t_GlobalID;
2278 break;
2279 case lltok::GlobalVar: // @foo
2280 ID.StrVal = Lex.getStrVal();
2281 ID.Kind = ValID::t_GlobalName;
2282 break;
2283 case lltok::LocalVarID: // %42
2284 ID.UIntVal = Lex.getUIntVal();
2285 ID.Kind = ValID::t_LocalID;
2286 break;
2287 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002288 ID.StrVal = Lex.getStrVal();
2289 ID.Kind = ValID::t_LocalName;
2290 break;
Dan Gohman8939ba332010-07-14 18:26:50 +00002291 case lltok::exclaim: // !42, !{...}, or !"foo"
2292 return ParseMetadataValue(ID, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002293 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002294 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002295 ID.Kind = ValID::t_APSInt;
2296 break;
2297 case lltok::APFloat:
2298 ID.APFloatVal = Lex.getAPFloatVal();
2299 ID.Kind = ValID::t_APFloat;
2300 break;
2301 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002302 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002303 ID.Kind = ValID::t_Constant;
2304 break;
2305 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002306 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002307 ID.Kind = ValID::t_Constant;
2308 break;
2309 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2310 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2311 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002312
Chris Lattnerac161bf2009-01-02 07:01:27 +00002313 case lltok::lbrace: {
2314 // ValID ::= '{' ConstVector '}'
2315 Lex.Lex();
2316 SmallVector<Constant*, 16> Elts;
2317 if (ParseGlobalValueVector(Elts) ||
2318 ParseToken(lltok::rbrace, "expected end of struct constant"))
2319 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002320
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002321 ID.ConstantStructElts = new Constant*[Elts.size()];
2322 ID.UIntVal = Elts.size();
2323 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2324 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002325 return false;
2326 }
2327 case lltok::less: {
2328 // ValID ::= '<' ConstVector '>' --> Vector.
2329 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2330 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002331 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002332
Chris Lattnerac161bf2009-01-02 07:01:27 +00002333 SmallVector<Constant*, 16> Elts;
2334 LocTy FirstEltLoc = Lex.getLoc();
2335 if (ParseGlobalValueVector(Elts) ||
2336 (isPackedStruct &&
2337 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2338 ParseToken(lltok::greater, "expected end of constant"))
2339 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002340
Chris Lattnerac161bf2009-01-02 07:01:27 +00002341 if (isPackedStruct) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002342 ID.ConstantStructElts = new Constant*[Elts.size()];
2343 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2344 ID.UIntVal = Elts.size();
2345 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002346 return false;
2347 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002348
Chris Lattnerac161bf2009-01-02 07:01:27 +00002349 if (Elts.empty())
2350 return Error(ID.Loc, "constant vector must not be empty");
2351
Duncan Sands9dff9be2010-02-15 16:12:20 +00002352 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002353 !Elts[0]->getType()->isFloatingPointTy() &&
2354 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002355 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002356 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002357
Chris Lattnerac161bf2009-01-02 07:01:27 +00002358 // Verify that all the vector elements have the same type.
2359 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2360 if (Elts[i]->getType() != Elts[0]->getType())
2361 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002362 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002363 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002364
Chris Lattner69229312011-02-15 00:14:00 +00002365 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002366 ID.Kind = ValID::t_Constant;
2367 return false;
2368 }
2369 case lltok::lsquare: { // Array Constant
2370 Lex.Lex();
2371 SmallVector<Constant*, 16> Elts;
2372 LocTy FirstEltLoc = Lex.getLoc();
2373 if (ParseGlobalValueVector(Elts) ||
2374 ParseToken(lltok::rsquare, "expected end of array constant"))
2375 return true;
2376
2377 // Handle empty element.
2378 if (Elts.empty()) {
2379 // Use undef instead of an array because it's inconvenient to determine
2380 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002381 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002382 return false;
2383 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002384
Chris Lattnerac161bf2009-01-02 07:01:27 +00002385 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002386 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002387 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002388
Owen Anderson4056ca92009-07-29 22:17:13 +00002389 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002390
Chris Lattnerac161bf2009-01-02 07:01:27 +00002391 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002392 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002393 if (Elts[i]->getType() != Elts[0]->getType())
2394 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002395 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002396 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002397 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002398
Jay Foad83be3612011-06-22 09:24:39 +00002399 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002400 ID.Kind = ValID::t_Constant;
2401 return false;
2402 }
2403 case lltok::kw_c: // c "foo"
2404 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002405 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2406 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002407 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2408 ID.Kind = ValID::t_Constant;
2409 return false;
2410
2411 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002412 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2413 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002414 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002415 Lex.Lex();
2416 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002417 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002418 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002419 ParseStringConstant(ID.StrVal) ||
2420 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002421 ParseToken(lltok::StringConstant, "expected constraint string"))
2422 return true;
2423 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002424 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002425 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002426 ID.Kind = ValID::t_InlineAsm;
2427 return false;
2428 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002429
Chris Lattner3432c622009-10-28 03:39:23 +00002430 case lltok::kw_blockaddress: {
2431 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2432 Lex.Lex();
2433
2434 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002435
Chris Lattner3432c622009-10-28 03:39:23 +00002436 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2437 ParseValID(Fn) ||
2438 ParseToken(lltok::comma, "expected comma in block address expression")||
2439 ParseValID(Label) ||
2440 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2441 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002442
Chris Lattner3432c622009-10-28 03:39:23 +00002443 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2444 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002445 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002446 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002447
Chris Lattner3432c622009-10-28 03:39:23 +00002448 // Make a global variable as a placeholder for this reference.
2449 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2450 false, GlobalValue::InternalLinkage,
2451 0, "");
2452 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2453 ID.ConstantVal = FwdRef;
2454 ID.Kind = ValID::t_Constant;
2455 return false;
2456 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002457
Chris Lattnerac161bf2009-01-02 07:01:27 +00002458 case lltok::kw_trunc:
2459 case lltok::kw_zext:
2460 case lltok::kw_sext:
2461 case lltok::kw_fptrunc:
2462 case lltok::kw_fpext:
2463 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002464 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002465 case lltok::kw_uitofp:
2466 case lltok::kw_sitofp:
2467 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002468 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002469 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002470 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002471 unsigned Opc = Lex.getUIntVal();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002472 Type *DestTy = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002473 Constant *SrcVal;
2474 Lex.Lex();
2475 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2476 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002477 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002478 ParseType(DestTy) ||
2479 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2480 return true;
2481 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2482 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002483 getTypeString(SrcVal->getType()) + "' to '" +
2484 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002485 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002486 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002487 ID.Kind = ValID::t_Constant;
2488 return false;
2489 }
2490 case lltok::kw_extractvalue: {
2491 Lex.Lex();
2492 Constant *Val;
2493 SmallVector<unsigned, 4> Indices;
2494 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2495 ParseGlobalTypeAndValue(Val) ||
2496 ParseIndexList(Indices) ||
2497 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2498 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002499
Chris Lattner392be582010-02-12 20:49:41 +00002500 if (!Val->getType()->isAggregateType())
2501 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002502 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002503 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002504 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002505 ID.Kind = ValID::t_Constant;
2506 return false;
2507 }
2508 case lltok::kw_insertvalue: {
2509 Lex.Lex();
2510 Constant *Val0, *Val1;
2511 SmallVector<unsigned, 4> Indices;
2512 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2513 ParseGlobalTypeAndValue(Val0) ||
2514 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2515 ParseGlobalTypeAndValue(Val1) ||
2516 ParseIndexList(Indices) ||
2517 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2518 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002519 if (!Val0->getType()->isAggregateType())
2520 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002521 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002522 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002523 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002524 ID.Kind = ValID::t_Constant;
2525 return false;
2526 }
2527 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002528 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002529 unsigned PredVal, Opc = Lex.getUIntVal();
2530 Constant *Val0, *Val1;
2531 Lex.Lex();
2532 if (ParseCmpPredicate(PredVal, Opc) ||
2533 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2534 ParseGlobalTypeAndValue(Val0) ||
2535 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2536 ParseGlobalTypeAndValue(Val1) ||
2537 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2538 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002539
Chris Lattnerac161bf2009-01-02 07:01:27 +00002540 if (Val0->getType() != Val1->getType())
2541 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002542
Chris Lattnerac161bf2009-01-02 07:01:27 +00002543 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002544
Chris Lattnerac161bf2009-01-02 07:01:27 +00002545 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002546 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002547 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002548 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002549 } else {
2550 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002551 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002552 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002553 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002554 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002555 }
2556 ID.Kind = ValID::t_Constant;
2557 return false;
2558 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002559
Chris Lattnerac161bf2009-01-02 07:01:27 +00002560 // Binary Operators.
2561 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002562 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002563 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002564 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002565 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002566 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002567 case lltok::kw_udiv:
2568 case lltok::kw_sdiv:
2569 case lltok::kw_fdiv:
2570 case lltok::kw_urem:
2571 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002572 case lltok::kw_frem:
2573 case lltok::kw_shl:
2574 case lltok::kw_lshr:
2575 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002576 bool NUW = false;
2577 bool NSW = false;
2578 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002579 unsigned Opc = Lex.getUIntVal();
2580 Constant *Val0, *Val1;
2581 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002582 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002583 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2584 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002585 if (EatIfPresent(lltok::kw_nuw))
2586 NUW = true;
2587 if (EatIfPresent(lltok::kw_nsw)) {
2588 NSW = true;
2589 if (EatIfPresent(lltok::kw_nuw))
2590 NUW = true;
2591 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002592 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2593 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002594 if (EatIfPresent(lltok::kw_exact))
2595 Exact = true;
2596 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002597 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2598 ParseGlobalTypeAndValue(Val0) ||
2599 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2600 ParseGlobalTypeAndValue(Val1) ||
2601 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2602 return true;
2603 if (Val0->getType() != Val1->getType())
2604 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002605 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002606 if (NUW)
2607 return Error(ModifierLoc, "nuw only applies to integer operations");
2608 if (NSW)
2609 return Error(ModifierLoc, "nsw only applies to integer operations");
2610 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002611 // Check that the type is valid for the operator.
2612 switch (Opc) {
2613 case Instruction::Add:
2614 case Instruction::Sub:
2615 case Instruction::Mul:
2616 case Instruction::UDiv:
2617 case Instruction::SDiv:
2618 case Instruction::URem:
2619 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002620 case Instruction::Shl:
2621 case Instruction::AShr:
2622 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002623 if (!Val0->getType()->isIntOrIntVectorTy())
2624 return Error(ID.Loc, "constexpr requires integer operands");
2625 break;
2626 case Instruction::FAdd:
2627 case Instruction::FSub:
2628 case Instruction::FMul:
2629 case Instruction::FDiv:
2630 case Instruction::FRem:
2631 if (!Val0->getType()->isFPOrFPVectorTy())
2632 return Error(ID.Loc, "constexpr requires fp operands");
2633 break;
2634 default: llvm_unreachable("Unknown binary operator!");
2635 }
Dan Gohman1b849082009-09-07 23:54:19 +00002636 unsigned Flags = 0;
2637 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2638 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002639 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002640 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002641 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002642 ID.Kind = ValID::t_Constant;
2643 return false;
2644 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002645
Chris Lattnerac161bf2009-01-02 07:01:27 +00002646 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002647 case lltok::kw_and:
2648 case lltok::kw_or:
2649 case lltok::kw_xor: {
2650 unsigned Opc = Lex.getUIntVal();
2651 Constant *Val0, *Val1;
2652 Lex.Lex();
2653 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2654 ParseGlobalTypeAndValue(Val0) ||
2655 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2656 ParseGlobalTypeAndValue(Val1) ||
2657 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2658 return true;
2659 if (Val0->getType() != Val1->getType())
2660 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002661 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002662 return Error(ID.Loc,
2663 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002664 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002665 ID.Kind = ValID::t_Constant;
2666 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002667 }
2668
Chris Lattnerac161bf2009-01-02 07:01:27 +00002669 case lltok::kw_getelementptr:
2670 case lltok::kw_shufflevector:
2671 case lltok::kw_insertelement:
2672 case lltok::kw_extractelement:
2673 case lltok::kw_select: {
2674 unsigned Opc = Lex.getUIntVal();
2675 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002676 bool InBounds = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002677 Lex.Lex();
Dan Gohman1639c392009-07-27 21:53:46 +00002678 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002679 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002680 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2681 ParseGlobalValueVector(Elts) ||
2682 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2683 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002684
Chris Lattnerac161bf2009-01-02 07:01:27 +00002685 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002686 if (Elts.size() == 0 ||
2687 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002688 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002689
Jay Foaded8db7d2011-07-21 14:31:17 +00002690 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foadd1b78492011-07-25 09:48:08 +00002691 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002692 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002693 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2694 InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002695 } else if (Opc == Instruction::Select) {
2696 if (Elts.size() != 3)
2697 return Error(ID.Loc, "expected three operands to select");
2698 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2699 Elts[2]))
2700 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002701 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002702 } else if (Opc == Instruction::ShuffleVector) {
2703 if (Elts.size() != 3)
2704 return Error(ID.Loc, "expected three operands to shufflevector");
2705 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2706 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002707 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002708 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002709 } else if (Opc == Instruction::ExtractElement) {
2710 if (Elts.size() != 2)
2711 return Error(ID.Loc, "expected two operands to extractelement");
2712 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2713 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002714 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002715 } else {
2716 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2717 if (Elts.size() != 3)
2718 return Error(ID.Loc, "expected three operands to insertelement");
2719 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2720 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002721 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002722 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002723 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002724
Chris Lattnerac161bf2009-01-02 07:01:27 +00002725 ID.Kind = ValID::t_Constant;
2726 return false;
2727 }
2728 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002729
Chris Lattnerac161bf2009-01-02 07:01:27 +00002730 Lex.Lex();
2731 return false;
2732}
2733
2734/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002735bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002736 C = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002737 ValID ID;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002738 Value *V = NULL;
2739 bool Parsed = ParseValID(ID) ||
2740 ConvertValIDToValue(Ty, ID, V, NULL);
2741 if (V && !(C = dyn_cast<Constant>(V)))
2742 return Error(ID.Loc, "global values must be constants");
2743 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002744}
2745
Victor Hernandez9d75c962010-01-11 22:31:58 +00002746bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002747 Type *Ty = 0;
2748 return ParseType(Ty) ||
2749 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002750}
2751
2752/// ParseGlobalValueVector
2753/// ::= /*empty*/
2754/// ::= TypeAndValue (',' TypeAndValue)*
2755bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2756 // Empty list.
2757 if (Lex.getKind() == lltok::rbrace ||
2758 Lex.getKind() == lltok::rsquare ||
2759 Lex.getKind() == lltok::greater ||
2760 Lex.getKind() == lltok::rparen)
2761 return false;
2762
2763 Constant *C;
2764 if (ParseGlobalTypeAndValue(C)) return true;
2765 Elts.push_back(C);
2766
2767 while (EatIfPresent(lltok::comma)) {
2768 if (ParseGlobalTypeAndValue(C)) return true;
2769 Elts.push_back(C);
2770 }
2771
2772 return false;
2773}
2774
Dan Gohmanc828c542010-08-24 02:24:03 +00002775bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2776 assert(Lex.getKind() == lltok::lbrace);
2777 Lex.Lex();
2778
2779 SmallVector<Value*, 16> Elts;
2780 if (ParseMDNodeVector(Elts, PFS) ||
2781 ParseToken(lltok::rbrace, "expected end of metadata node"))
2782 return true;
2783
Jay Foad5514afe2011-04-21 19:59:31 +00002784 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002785 ID.Kind = ValID::t_MDNode;
2786 return false;
2787}
2788
Dan Gohman8939ba332010-07-14 18:26:50 +00002789/// ParseMetadataValue
2790/// ::= !42
2791/// ::= !{...}
2792/// ::= !"string"
2793bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2794 assert(Lex.getKind() == lltok::exclaim);
2795 Lex.Lex();
2796
2797 // MDNode:
2798 // !{ ... }
Dan Gohmanc828c542010-08-24 02:24:03 +00002799 if (Lex.getKind() == lltok::lbrace)
2800 return ParseMetadataListValue(ID, PFS);
Dan Gohman8939ba332010-07-14 18:26:50 +00002801
2802 // Standalone metadata reference
2803 // !42
2804 if (Lex.getKind() == lltok::APSInt) {
2805 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2806 ID.Kind = ValID::t_MDNode;
2807 return false;
2808 }
2809
2810 // MDString:
2811 // ::= '!' STRINGCONSTANT
2812 if (ParseMDString(ID.MDStringVal)) return true;
2813 ID.Kind = ValID::t_MDString;
2814 return false;
2815}
2816
Victor Hernandez9d75c962010-01-11 22:31:58 +00002817
2818//===----------------------------------------------------------------------===//
2819// Function Parsing.
2820//===----------------------------------------------------------------------===//
2821
Chris Lattner229907c2011-07-18 04:54:35 +00002822bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00002823 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002824 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002825 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002826
Chris Lattnerac161bf2009-01-02 07:01:27 +00002827 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002828 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00002829 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2830 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2831 return (V == 0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002832 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00002833 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2834 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2835 return (V == 0);
2836 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00002837 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002838 FunctionType *FTy =
Victor Hernandez9d75c962010-01-11 22:31:58 +00002839 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2840 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2841 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00002842 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00002843 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00002844 return false;
2845 }
2846 case ValID::t_MDNode:
2847 if (!Ty->isMetadataTy())
2848 return Error(ID.Loc, "metadata value must have metadata type");
2849 V = ID.MDNodeVal;
2850 return false;
2851 case ValID::t_MDString:
2852 if (!Ty->isMetadataTy())
2853 return Error(ID.Loc, "metadata value must have metadata type");
2854 V = ID.MDStringVal;
2855 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002856 case ValID::t_GlobalName:
2857 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2858 return V == 0;
2859 case ValID::t_GlobalID:
2860 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2861 return V == 0;
2862 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00002863 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002864 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00002865 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00002866 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002867 return false;
2868 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00002869 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002870 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2871 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002872
Dan Gohman518cda42011-12-17 00:04:22 +00002873 // The lexer has no type info, so builds all half, float, and double FP
2874 // constants as double. Fix this here. Long double does not need this.
2875 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002876 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00002877 if (Ty->isHalfTy())
2878 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2879 &Ignored);
2880 else if (Ty->isFloatTy())
2881 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2882 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002883 }
Owen Anderson69c464d2009-07-27 20:59:43 +00002884 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002885
Chris Lattner8f57d29e2009-01-05 18:24:23 +00002886 if (V->getType() != Ty)
2887 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002888 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002889
Chris Lattnerac161bf2009-01-02 07:01:27 +00002890 return false;
2891 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00002892 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002893 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00002894 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002895 return false;
2896 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00002897 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002898 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00002899 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00002900 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002901 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00002902 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00002903 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00002904 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00002905 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00002906 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002907 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00002908 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002909 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002910 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00002911 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002912 return false;
2913 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00002914 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002915 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00002916
Chris Lattnerac161bf2009-01-02 07:01:27 +00002917 V = ID.ConstantVal;
2918 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002919 case ValID::t_ConstantStruct:
2920 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00002921 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002922 if (ST->getNumElements() != ID.UIntVal)
2923 return Error(ID.Loc,
2924 "initializer with struct type has wrong # elements");
2925 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2926 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002927
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002928 // Verify that the elements are compatible with the structtype.
2929 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2930 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2931 return Error(ID.Loc, "element " + Twine(i) +
2932 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002933
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002934 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2935 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002936 } else
2937 return Error(ID.Loc, "constant expression type mismatch");
2938 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002939 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00002940 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002941}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002942
Chris Lattner229907c2011-07-18 04:54:35 +00002943bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002944 V = 0;
2945 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002946 return ParseValID(ID, PFS) ||
2947 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002948}
2949
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002950bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2951 Type *Ty = 0;
2952 return ParseType(Ty) ||
2953 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002954}
2955
Chris Lattner3ed871f2009-10-27 19:13:16 +00002956bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2957 PerFunctionState &PFS) {
2958 Value *V;
2959 Loc = Lex.getLoc();
2960 if (ParseTypeAndValue(V, PFS)) return true;
2961 if (!isa<BasicBlock>(V))
2962 return Error(Loc, "expected a basic block");
2963 BB = cast<BasicBlock>(V);
2964 return false;
2965}
2966
2967
Chris Lattnerac161bf2009-01-02 07:01:27 +00002968/// FunctionHeader
2969/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00002970/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002971/// OptionalAlign OptGC OptionalPrefix
Chris Lattnerac161bf2009-01-02 07:01:27 +00002972bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2973 // Parse the linkage.
2974 LocTy LinkageLoc = Lex.getLoc();
2975 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002976
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00002977 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00002978 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00002979 AttrBuilder RetAttrs;
Sandeep Patel68c5f472009-09-02 08:44:58 +00002980 CallingConv::ID CC;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002981 Type *RetType = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002982 LocTy RetTypeLoc = Lex.getLoc();
2983 if (ParseOptionalLinkage(Linkage) ||
2984 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00002985 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002986 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002987 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00002988 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002989 return true;
2990
2991 // Verify that the linkage is ok.
2992 switch ((GlobalValue::LinkageTypes)Linkage) {
2993 case GlobalValue::ExternalLinkage:
2994 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00002995 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002996 if (isDefine)
2997 return Error(LinkageLoc, "invalid linkage for function definition");
2998 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00002999 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003000 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00003001 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00003002 case GlobalValue::LinkOnceAnyLinkage:
3003 case GlobalValue::LinkOnceODRLinkage:
3004 case GlobalValue::WeakAnyLinkage:
3005 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003006 if (!isDefine)
3007 return Error(LinkageLoc, "invalid linkage for function declaration");
3008 break;
3009 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00003010 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003011 return Error(LinkageLoc, "invalid function linkage type");
3012 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003013
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003014 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003015 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003016
Chris Lattnerac161bf2009-01-02 07:01:27 +00003017 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00003018
3019 std::string FunctionName;
3020 if (Lex.getKind() == lltok::GlobalVar) {
3021 FunctionName = Lex.getStrVal();
3022 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3023 unsigned NameID = Lex.getUIntVal();
3024
3025 if (NameID != NumberedVals.size())
3026 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003027 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00003028 } else {
3029 return TokError("expected function name");
3030 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003031
Chris Lattner3822f632009-01-02 08:05:26 +00003032 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003033
Chris Lattner3822f632009-01-02 08:05:26 +00003034 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003035 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003036
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003037 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003038 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00003039 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003040 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003041 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003042 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003043 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00003044 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003045 bool UnnamedAddr;
3046 LocTy UnnamedAddrLoc;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003047 Constant *Prefix = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00003048
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003049 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003050 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3051 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003052 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00003053 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003054 (EatIfPresent(lltok::kw_section) &&
3055 ParseStringConstant(Section)) ||
3056 ParseOptionalAlignment(Alignment) ||
3057 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003058 ParseStringConstant(GC)) ||
3059 (EatIfPresent(lltok::kw_prefix) &&
3060 ParseGlobalTypeAndValue(Prefix)))
Chris Lattner3822f632009-01-02 08:05:26 +00003061 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003062
Michael Gottesman41748d72013-06-27 00:25:01 +00003063 if (FuncAttrs.contains(Attribute::Builtin))
3064 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00003065
Chris Lattnerac161bf2009-01-02 07:01:27 +00003066 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00003067 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00003068 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003069 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003070 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003071
Chris Lattnerac161bf2009-01-02 07:01:27 +00003072 // Okay, if we got here, the function is syntactically valid. Convert types
3073 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00003074 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00003075 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003076
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003077 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003078 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3079 AttributeSet::ReturnIndex,
3080 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003081
Chris Lattnerac161bf2009-01-02 07:01:27 +00003082 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003083 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003084 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3085 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003086 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3087 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003088 }
3089
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003090 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003091 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3092 AttributeSet::FunctionIndex,
3093 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003094
Bill Wendlinge94d8432012-12-07 23:16:57 +00003095 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003096
Bill Wendling749a43d2012-12-30 13:50:49 +00003097 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003098 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3099
Chris Lattner229907c2011-07-18 04:54:35 +00003100 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00003101 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00003102 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003103
3104 Fn = 0;
3105 if (!FunctionName.empty()) {
3106 // If this was a definition of a forward reference, remove the definition
3107 // from the forward reference table and fill in the forward ref.
3108 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3109 ForwardRefVals.find(FunctionName);
3110 if (FRVI != ForwardRefVals.end()) {
3111 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00003112 if (!Fn)
3113 return Error(FRVI->second.second, "invalid forward reference to "
3114 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00003115 if (Fn->getType() != PFT)
3116 return Error(FRVI->second.second, "invalid forward reference to "
3117 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003118
Chris Lattnerac161bf2009-01-02 07:01:27 +00003119 ForwardRefVals.erase(FRVI);
3120 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00003121 // Reject redefinitions.
3122 return Error(NameLoc, "invalid redefinition of function '" +
3123 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00003124 } else if (M->getNamedValue(FunctionName)) {
3125 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003126 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003127
Dan Gohman399d6ae2009-08-29 23:37:49 +00003128 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003129 // If this is a definition of a forward referenced function, make sure the
3130 // types agree.
3131 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3132 = ForwardRefValIDs.find(NumberedVals.size());
3133 if (I != ForwardRefValIDs.end()) {
3134 Fn = cast<Function>(I->second.first);
3135 if (Fn->getType() != PFT)
3136 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003137 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003138 ForwardRefValIDs.erase(I);
3139 }
3140 }
3141
3142 if (Fn == 0)
3143 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3144 else // Move the forward-reference to the correct spot in the module.
3145 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3146
3147 if (FunctionName.empty())
3148 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003149
Chris Lattnerac161bf2009-01-02 07:01:27 +00003150 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3151 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00003152 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003153 Fn->setCallingConv(CC);
3154 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003155 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003156 Fn->setAlignment(Alignment);
3157 Fn->setSection(Section);
3158 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003159 Fn->setPrefixData(Prefix);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003160 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003161
Chris Lattnerac161bf2009-01-02 07:01:27 +00003162 // Add all of the arguments we parsed to the function.
3163 Function::arg_iterator ArgIt = Fn->arg_begin();
3164 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3165 // If the argument has a name, insert it into the argument symbol table.
3166 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003167
Chris Lattnerac161bf2009-01-02 07:01:27 +00003168 // Set the name, if it conflicted, it will be auto-renamed.
3169 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003170
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00003171 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003172 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3173 ArgList[i].Name + "'");
3174 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003175
Chris Lattnerac161bf2009-01-02 07:01:27 +00003176 return false;
3177}
3178
3179
3180/// ParseFunctionBody
3181/// ::= '{' BasicBlock+ '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00003182///
3183bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00003184 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003185 return TokError("expected '{' in function body");
3186 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003187
Chris Lattner3432c622009-10-28 03:39:23 +00003188 int FunctionNumber = -1;
3189 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003190
Chris Lattner3432c622009-10-28 03:39:23 +00003191 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003192
Chris Lattnerbbddd962010-01-09 19:20:07 +00003193 // We need at least one basic block.
Chris Lattner4649a732011-06-17 06:42:57 +00003194 if (Lex.getKind() == lltok::rbrace)
Chris Lattnerbbddd962010-01-09 19:20:07 +00003195 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003196
Chris Lattner4649a732011-06-17 06:42:57 +00003197 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003198 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003199
Chris Lattnerac161bf2009-01-02 07:01:27 +00003200 // Eat the }.
3201 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003202
Chris Lattnerac161bf2009-01-02 07:01:27 +00003203 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00003204 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003205}
3206
3207/// ParseBasicBlock
3208/// ::= LabelStr? Instruction*
3209bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3210 // If this basic block starts out with a name, remember it.
3211 std::string Name;
3212 LocTy NameLoc = Lex.getLoc();
3213 if (Lex.getKind() == lltok::LabelStr) {
3214 Name = Lex.getStrVal();
3215 Lex.Lex();
3216 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003217
Chris Lattnerac161bf2009-01-02 07:01:27 +00003218 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3219 if (BB == 0) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003220
Chris Lattnerac161bf2009-01-02 07:01:27 +00003221 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003222
Chris Lattnerac161bf2009-01-02 07:01:27 +00003223 // Parse the instructions in this block until we get a terminator.
3224 Instruction *Inst;
3225 do {
3226 // This instruction may have three possibilities for a name: a) none
3227 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3228 LocTy NameLoc = Lex.getLoc();
3229 int NameID = -1;
3230 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003231
Chris Lattnerac161bf2009-01-02 07:01:27 +00003232 if (Lex.getKind() == lltok::LocalVarID) {
3233 NameID = Lex.getUIntVal();
3234 Lex.Lex();
3235 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3236 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00003237 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003238 NameStr = Lex.getStrVal();
3239 Lex.Lex();
3240 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3241 return true;
3242 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003243
Chris Lattner77b89dc2009-12-30 05:23:43 +00003244 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00003245 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00003246 case InstError: return true;
3247 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003248 BB->getInstList().push_back(Inst);
3249
Chris Lattner77b89dc2009-12-30 05:23:43 +00003250 // With a normal result, we check to see if the instruction is followed by
3251 // a comma and metadata.
3252 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00003253 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003254 return true;
3255 break;
3256 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003257 BB->getInstList().push_back(Inst);
3258
Chris Lattner77b89dc2009-12-30 05:23:43 +00003259 // If the instruction parser ate an extra comma at the end of it, it
3260 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00003261 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003262 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003263 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00003264 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003265
Chris Lattnerac161bf2009-01-02 07:01:27 +00003266 // Set the name on the instruction.
3267 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3268 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003269
Chris Lattnerac161bf2009-01-02 07:01:27 +00003270 return false;
3271}
3272
3273//===----------------------------------------------------------------------===//
3274// Instruction Parsing.
3275//===----------------------------------------------------------------------===//
3276
3277/// ParseInstruction - Parse one of the many different instructions.
3278///
Chris Lattner77b89dc2009-12-30 05:23:43 +00003279int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3280 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003281 lltok::Kind Token = Lex.getKind();
3282 if (Token == lltok::Eof)
3283 return TokError("found end of file when expecting more instructions");
3284 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00003285 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003286 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003287
Chris Lattnerac161bf2009-01-02 07:01:27 +00003288 switch (Token) {
3289 default: return Error(Loc, "expected instruction opcode");
3290 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00003291 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003292 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3293 case lltok::kw_br: return ParseBr(Inst, PFS);
3294 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003295 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003296 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003297 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003298 // Binary Operators.
3299 case lltok::kw_add:
3300 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003301 case lltok::kw_mul:
3302 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00003303 bool NUW = EatIfPresent(lltok::kw_nuw);
3304 bool NSW = EatIfPresent(lltok::kw_nsw);
3305 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003306
Chris Lattnera676c0f2011-02-07 16:40:21 +00003307 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003308
Chris Lattnera676c0f2011-02-07 16:40:21 +00003309 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3310 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3311 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003312 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003313 case lltok::kw_fadd:
3314 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00003315 case lltok::kw_fmul:
3316 case lltok::kw_fdiv:
3317 case lltok::kw_frem: {
3318 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3319 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3320 if (Res != 0)
3321 return Res;
3322 if (FMF.any())
3323 Inst->setFastMathFlags(FMF);
3324 return 0;
3325 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003326
Chris Lattner35315d02011-02-06 21:44:57 +00003327 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003328 case lltok::kw_udiv:
3329 case lltok::kw_lshr:
3330 case lltok::kw_ashr: {
3331 bool Exact = EatIfPresent(lltok::kw_exact);
3332
3333 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3334 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3335 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003336 }
3337
Chris Lattnerac161bf2009-01-02 07:01:27 +00003338 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00003339 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003340 case lltok::kw_and:
3341 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00003342 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003343 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003344 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003345 // Casts.
3346 case lltok::kw_trunc:
3347 case lltok::kw_zext:
3348 case lltok::kw_sext:
3349 case lltok::kw_fptrunc:
3350 case lltok::kw_fpext:
3351 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003352 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003353 case lltok::kw_uitofp:
3354 case lltok::kw_sitofp:
3355 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003356 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003357 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00003358 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003359 // Other.
3360 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00003361 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003362 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3363 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3364 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3365 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00003366 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003367 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3368 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3369 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00003370 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00003371 case lltok::kw_load: return ParseLoad(Inst, PFS);
3372 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00003373 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3374 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003375 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003376 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3377 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3378 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3379 }
3380}
3381
3382/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3383bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003384 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003385 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003386 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003387 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3388 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3389 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3390 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3391 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3392 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3393 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3394 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3395 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3396 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3397 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3398 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3399 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3400 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3401 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3402 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3403 }
3404 } else {
3405 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003406 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003407 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3408 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3409 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3410 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3411 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3412 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3413 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3414 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3415 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3416 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3417 }
3418 }
3419 Lex.Lex();
3420 return false;
3421}
3422
3423//===----------------------------------------------------------------------===//
3424// Terminator Instructions.
3425//===----------------------------------------------------------------------===//
3426
3427/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00003428/// ::= 'ret' void (',' !dbg, !1)*
3429/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00003430bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003431 PerFunctionState &PFS) {
3432 SMLoc TypeLoc = Lex.getLoc();
3433 Type *Ty = 0;
Chris Lattnerf880ca22009-03-09 04:49:14 +00003434 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003435
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003436 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003437
Chris Lattnerfdd87902009-10-05 05:54:46 +00003438 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003439 if (!ResType->isVoidTy())
3440 return Error(TypeLoc, "value doesn't match function result type '" +
3441 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003442
Owen Anderson55f1c092009-08-13 21:58:54 +00003443 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003444 return false;
3445 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003446
Chris Lattnerac161bf2009-01-02 07:01:27 +00003447 Value *RV;
3448 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003449
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003450 if (ResType != RV->getType())
3451 return Error(TypeLoc, "value doesn't match function result type '" +
3452 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003453
Owen Anderson55f1c092009-08-13 21:58:54 +00003454 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00003455 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003456}
3457
3458
3459/// ParseBr
3460/// ::= 'br' TypeAndValue
3461/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3462bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3463 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003464 Value *Op0;
3465 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003466 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003467
Chris Lattnerac161bf2009-01-02 07:01:27 +00003468 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3469 Inst = BranchInst::Create(BB);
3470 return false;
3471 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003472
Owen Anderson55f1c092009-08-13 21:58:54 +00003473 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003474 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003475
Chris Lattnerac161bf2009-01-02 07:01:27 +00003476 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003477 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003478 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003479 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003480 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003481
Chris Lattner3ed871f2009-10-27 19:13:16 +00003482 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003483 return false;
3484}
3485
3486/// ParseSwitch
3487/// Instruction
3488/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3489/// JumpTable
3490/// ::= (TypeAndValue ',' TypeAndValue)*
3491bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3492 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003493 Value *Cond;
3494 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003495 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3496 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003497 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003498 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3499 return true;
3500
Duncan Sands19d0b472010-02-16 11:11:14 +00003501 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003502 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003503
Chris Lattnerac161bf2009-01-02 07:01:27 +00003504 // Parse the jump table pairs.
3505 SmallPtrSet<Value*, 32> SeenCases;
3506 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3507 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003508 Value *Constant;
3509 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003510
Chris Lattnerac161bf2009-01-02 07:01:27 +00003511 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3512 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003513 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003514 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003515
Chris Lattnerac161bf2009-01-02 07:01:27 +00003516 if (!SeenCases.insert(Constant))
3517 return Error(CondLoc, "duplicate case value in switch");
3518 if (!isa<ConstantInt>(Constant))
3519 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003520
Chris Lattner3ed871f2009-10-27 19:13:16 +00003521 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003522 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003523
Chris Lattnerac161bf2009-01-02 07:01:27 +00003524 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003525
Chris Lattner3ed871f2009-10-27 19:13:16 +00003526 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003527 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3528 SI->addCase(Table[i].first, Table[i].second);
3529 Inst = SI;
3530 return false;
3531}
3532
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003533/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00003534/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003535/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3536bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003537 LocTy AddrLoc;
3538 Value *Address;
3539 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003540 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3541 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00003542 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003543
Duncan Sands19d0b472010-02-16 11:11:14 +00003544 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003545 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003546
Chris Lattner3ed871f2009-10-27 19:13:16 +00003547 // Parse the destination list.
3548 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003549
Chris Lattner3ed871f2009-10-27 19:13:16 +00003550 if (Lex.getKind() != lltok::rsquare) {
3551 BasicBlock *DestBB;
3552 if (ParseTypeAndBasicBlock(DestBB, PFS))
3553 return true;
3554 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003555
Chris Lattner3ed871f2009-10-27 19:13:16 +00003556 while (EatIfPresent(lltok::comma)) {
3557 if (ParseTypeAndBasicBlock(DestBB, PFS))
3558 return true;
3559 DestList.push_back(DestBB);
3560 }
3561 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003562
Chris Lattner3ed871f2009-10-27 19:13:16 +00003563 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3564 return true;
3565
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003566 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00003567 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3568 IBI->addDestination(DestList[i]);
3569 Inst = IBI;
3570 return false;
3571}
3572
3573
Chris Lattnerac161bf2009-01-02 07:01:27 +00003574/// ParseInvoke
3575/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3576/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3577bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3578 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00003579 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003580 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00003581 LocTy NoBuiltinLoc;
Sandeep Patel68c5f472009-09-02 08:44:58 +00003582 CallingConv::ID CC;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003583 Type *RetType = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003584 LocTy RetTypeLoc;
3585 ValID CalleeID;
3586 SmallVector<ParamInfo, 16> ArgList;
3587
Chris Lattner3ed871f2009-10-27 19:13:16 +00003588 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003589 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003590 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003591 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003592 ParseValID(CalleeID) ||
3593 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003594 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3595 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003596 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003597 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003598 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003599 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003600 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003601
Chris Lattnerac161bf2009-01-02 07:01:27 +00003602 // If RetType is a non-function pointer type, then this is the short syntax
3603 // for the call, which means that RetType is just the return type. Infer the
3604 // rest of the function argument types from the arguments that are present.
Chris Lattner229907c2011-07-18 04:54:35 +00003605 PointerType *PFTy = 0;
3606 FunctionType *Ty = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003607 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3608 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3609 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00003610 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003611 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3612 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003613
Chris Lattnerac161bf2009-01-02 07:01:27 +00003614 if (!FunctionType::isValidReturnType(RetType))
3615 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003616
Owen Anderson4056ca92009-07-29 22:17:13 +00003617 Ty = FunctionType::get(RetType, ParamTypes, false);
3618 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003619 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003620
Chris Lattnerac161bf2009-01-02 07:01:27 +00003621 // Look up the callee.
3622 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003623 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003624
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003625 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00003626 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003627 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003628 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3629 AttributeSet::ReturnIndex,
3630 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003631
Chris Lattnerac161bf2009-01-02 07:01:27 +00003632 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003633
Chris Lattnerac161bf2009-01-02 07:01:27 +00003634 // Loop through FunctionType's arguments and ensure they are specified
3635 // correctly. Also, gather any parameter attributes.
3636 FunctionType::param_iterator I = Ty->param_begin();
3637 FunctionType::param_iterator E = Ty->param_end();
3638 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +00003639 Type *ExpectedTy = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003640 if (I != E) {
3641 ExpectedTy = *I++;
3642 } else if (!Ty->isVarArg()) {
3643 return Error(ArgList[i].Loc, "too many arguments specified");
3644 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003645
Chris Lattnerac161bf2009-01-02 07:01:27 +00003646 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3647 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003648 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003649 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003650 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3651 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003652 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3653 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003654 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003655
Chris Lattnerac161bf2009-01-02 07:01:27 +00003656 if (I != E)
3657 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003658
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003659 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003660 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3661 AttributeSet::FunctionIndex,
3662 FnAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003663
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003664 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00003665 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003666
Jay Foad5bd375a2011-07-15 08:37:34 +00003667 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003668 II->setCallingConv(CC);
3669 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003670 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003671 Inst = II;
3672 return false;
3673}
3674
Bill Wendlingf891bf82011-07-31 06:30:59 +00003675/// ParseResume
3676/// ::= 'resume' TypeAndValue
3677bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3678 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00003679 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3680 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003681
Bill Wendlingf891bf82011-07-31 06:30:59 +00003682 ResumeInst *RI = ResumeInst::Create(Exn);
3683 Inst = RI;
3684 return false;
3685}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003686
3687//===----------------------------------------------------------------------===//
3688// Binary Operators.
3689//===----------------------------------------------------------------------===//
3690
3691/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003692/// ::= ArithmeticOps TypeAndValue ',' Value
3693///
3694/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3695/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00003696bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003697 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003698 LocTy Loc; Value *LHS, *RHS;
3699 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3700 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3701 ParseValue(LHS->getType(), RHS, PFS))
3702 return true;
3703
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003704 bool Valid;
3705 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00003706 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003707 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00003708 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3709 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003710 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00003711 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3712 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003713 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003714
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003715 if (!Valid)
3716 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003717
Chris Lattnerac161bf2009-01-02 07:01:27 +00003718 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3719 return false;
3720}
3721
3722/// ParseLogical
3723/// ::= ArithmeticOps TypeAndValue ',' Value {
3724bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3725 unsigned Opc) {
3726 LocTy Loc; Value *LHS, *RHS;
3727 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3728 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3729 ParseValue(LHS->getType(), RHS, PFS))
3730 return true;
3731
Duncan Sands9dff9be2010-02-15 16:12:20 +00003732 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003733 return Error(Loc,"instruction requires integer or integer vector operands");
3734
3735 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3736 return false;
3737}
3738
3739
3740/// ParseCompare
3741/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3742/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00003743bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3744 unsigned Opc) {
3745 // Parse the integer/fp comparison predicate.
3746 LocTy Loc;
3747 unsigned Pred;
3748 Value *LHS, *RHS;
3749 if (ParseCmpPredicate(Pred, Opc) ||
3750 ParseTypeAndValue(LHS, Loc, PFS) ||
3751 ParseToken(lltok::comma, "expected ',' after compare value") ||
3752 ParseValue(LHS->getType(), RHS, PFS))
3753 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003754
Chris Lattnerac161bf2009-01-02 07:01:27 +00003755 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003756 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003757 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003758 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003759 } else {
3760 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003761 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003762 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003763 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003764 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003765 }
3766 return false;
3767}
3768
3769//===----------------------------------------------------------------------===//
3770// Other Instructions.
3771//===----------------------------------------------------------------------===//
3772
3773
3774/// ParseCast
3775/// ::= CastOpc TypeAndValue 'to' Type
3776bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3777 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003778 LocTy Loc;
3779 Value *Op;
3780 Type *DestTy = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003781 if (ParseTypeAndValue(Op, Loc, PFS) ||
3782 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3783 ParseType(DestTy))
3784 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003785
Chris Lattner89d856e2009-03-01 00:53:13 +00003786 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3787 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003788 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003789 getTypeString(Op->getType()) + "' to '" +
3790 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00003791 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003792 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3793 return false;
3794}
3795
3796/// ParseSelect
3797/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3798bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3799 LocTy Loc;
3800 Value *Op0, *Op1, *Op2;
3801 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3802 ParseToken(lltok::comma, "expected ',' after select condition") ||
3803 ParseTypeAndValue(Op1, PFS) ||
3804 ParseToken(lltok::comma, "expected ',' after select value") ||
3805 ParseTypeAndValue(Op2, PFS))
3806 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003807
Chris Lattnerac161bf2009-01-02 07:01:27 +00003808 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3809 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003810
Chris Lattnerac161bf2009-01-02 07:01:27 +00003811 Inst = SelectInst::Create(Op0, Op1, Op2);
3812 return false;
3813}
3814
Chris Lattnerb55ab542009-01-05 08:18:44 +00003815/// ParseVA_Arg
3816/// ::= 'va_arg' TypeAndValue ',' Type
3817bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003818 Value *Op;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003819 Type *EltTy = 0;
Chris Lattnerb55ab542009-01-05 08:18:44 +00003820 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003821 if (ParseTypeAndValue(Op, PFS) ||
3822 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00003823 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003824 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003825
Chris Lattnerb55ab542009-01-05 08:18:44 +00003826 if (!EltTy->isFirstClassType())
3827 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003828
3829 Inst = new VAArgInst(Op, EltTy);
3830 return false;
3831}
3832
3833/// ParseExtractElement
3834/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3835bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3836 LocTy Loc;
3837 Value *Op0, *Op1;
3838 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3839 ParseToken(lltok::comma, "expected ',' after extract value") ||
3840 ParseTypeAndValue(Op1, PFS))
3841 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003842
Chris Lattnerac161bf2009-01-02 07:01:27 +00003843 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3844 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003845
Eric Christopherc9742252009-07-25 02:28:41 +00003846 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003847 return false;
3848}
3849
3850/// ParseInsertElement
3851/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3852bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3853 LocTy Loc;
3854 Value *Op0, *Op1, *Op2;
3855 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3856 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3857 ParseTypeAndValue(Op1, PFS) ||
3858 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3859 ParseTypeAndValue(Op2, PFS))
3860 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003861
Chris Lattnerac161bf2009-01-02 07:01:27 +00003862 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00003863 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003864
Chris Lattnerac161bf2009-01-02 07:01:27 +00003865 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3866 return false;
3867}
3868
3869/// ParseShuffleVector
3870/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3871bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3872 LocTy Loc;
3873 Value *Op0, *Op1, *Op2;
3874 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3875 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3876 ParseTypeAndValue(Op1, PFS) ||
3877 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3878 ParseTypeAndValue(Op2, PFS))
3879 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003880
Chris Lattnerac161bf2009-01-02 07:01:27 +00003881 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00003882 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003883
Chris Lattnerac161bf2009-01-02 07:01:27 +00003884 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3885 return false;
3886}
3887
3888/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00003889/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00003890int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003891 Type *Ty = 0; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003892 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003893
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003894 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003895 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3896 ParseValue(Ty, Op0, PFS) ||
3897 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00003898 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003899 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3900 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003901
Chris Lattnerf4f03422009-12-30 05:27:33 +00003902 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003903 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3904 while (1) {
3905 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003906
Chris Lattner3822f632009-01-02 08:05:26 +00003907 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003908 break;
3909
Chris Lattnerf4f03422009-12-30 05:27:33 +00003910 if (Lex.getKind() == lltok::MetadataVar) {
3911 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00003912 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00003913 }
Devang Patel8f842d32009-10-16 18:45:49 +00003914
Chris Lattner3822f632009-01-02 08:05:26 +00003915 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003916 ParseValue(Ty, Op0, PFS) ||
3917 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00003918 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003919 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3920 return true;
3921 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003922
Chris Lattnerac161bf2009-01-02 07:01:27 +00003923 if (!Ty->isFirstClassType())
3924 return Error(TypeLoc, "phi node must have first class type");
3925
Jay Foad52131342011-03-30 11:28:46 +00003926 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003927 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3928 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3929 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00003930 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003931}
3932
Bill Wendlingfae14752011-08-12 20:24:12 +00003933/// ParseLandingPad
3934/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3935/// Clause
3936/// ::= 'catch' TypeAndValue
3937/// ::= 'filter'
3938/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3939bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3940 Type *Ty = 0; LocTy TyLoc;
3941 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00003942
3943 if (ParseType(Ty, TyLoc) ||
3944 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3945 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3946 return true;
3947
3948 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3949 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3950
3951 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3952 LandingPadInst::ClauseType CT;
3953 if (EatIfPresent(lltok::kw_catch))
3954 CT = LandingPadInst::Catch;
3955 else if (EatIfPresent(lltok::kw_filter))
3956 CT = LandingPadInst::Filter;
3957 else
3958 return TokError("expected 'catch' or 'filter' clause type");
3959
3960 Value *V; LocTy VLoc;
3961 if (ParseTypeAndValue(V, VLoc, PFS)) {
3962 delete LP;
3963 return true;
3964 }
3965
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00003966 // A 'catch' type expects a non-array constant. A filter clause expects an
3967 // array constant.
3968 if (CT == LandingPadInst::Catch) {
3969 if (isa<ArrayType>(V->getType()))
3970 Error(VLoc, "'catch' clause has an invalid type");
3971 } else {
3972 if (!isa<ArrayType>(V->getType()))
3973 Error(VLoc, "'filter' clause has an invalid type");
3974 }
3975
Bill Wendlingfae14752011-08-12 20:24:12 +00003976 LP->addClause(V);
3977 }
3978
3979 Inst = LP;
3980 return false;
3981}
3982
Chris Lattnerac161bf2009-01-02 07:01:27 +00003983/// ParseCall
3984/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3985/// ParameterList OptionalAttrs
3986bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3987 bool isTail) {
Bill Wendling50d27842012-10-15 20:35:56 +00003988 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003989 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003990 LocTy BuiltinLoc;
Sandeep Patel68c5f472009-09-02 08:44:58 +00003991 CallingConv::ID CC;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003992 Type *RetType = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003993 LocTy RetTypeLoc;
3994 ValID CalleeID;
3995 SmallVector<ParamInfo, 16> ArgList;
3996 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003997
Chris Lattnerac161bf2009-01-02 07:01:27 +00003998 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3999 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004000 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004001 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004002 ParseValID(CalleeID) ||
4003 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004004 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004005 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004006 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004007
Chris Lattnerac161bf2009-01-02 07:01:27 +00004008 // If RetType is a non-function pointer type, then this is the short syntax
4009 // for the call, which means that RetType is just the return type. Infer the
4010 // rest of the function argument types from the arguments that are present.
Chris Lattner229907c2011-07-18 04:54:35 +00004011 PointerType *PFTy = 0;
4012 FunctionType *Ty = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004013 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4014 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4015 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004016 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00004017 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4018 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004019
Chris Lattnerac161bf2009-01-02 07:01:27 +00004020 if (!FunctionType::isValidReturnType(RetType))
4021 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004022
Owen Anderson4056ca92009-07-29 22:17:13 +00004023 Ty = FunctionType::get(RetType, ParamTypes, false);
4024 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004025 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004026
Chris Lattnerac161bf2009-01-02 07:01:27 +00004027 // Look up the callee.
4028 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004029 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004030
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004031 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004032 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004033 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004034 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4035 AttributeSet::ReturnIndex,
4036 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004037
Chris Lattnerac161bf2009-01-02 07:01:27 +00004038 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004039
Chris Lattnerac161bf2009-01-02 07:01:27 +00004040 // Loop through FunctionType's arguments and ensure they are specified
4041 // correctly. Also, gather any parameter attributes.
4042 FunctionType::param_iterator I = Ty->param_begin();
4043 FunctionType::param_iterator E = Ty->param_end();
4044 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +00004045 Type *ExpectedTy = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004046 if (I != E) {
4047 ExpectedTy = *I++;
4048 } else if (!Ty->isVarArg()) {
4049 return Error(ArgList[i].Loc, "too many arguments specified");
4050 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004051
Chris Lattnerac161bf2009-01-02 07:01:27 +00004052 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4053 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004054 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004055 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004056 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4057 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004058 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4059 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004060 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004061
Chris Lattnerac161bf2009-01-02 07:01:27 +00004062 if (I != E)
4063 return Error(CallLoc, "not enough parameters specified for call");
4064
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004065 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004066 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4067 AttributeSet::FunctionIndex,
4068 FnAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004069
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004070 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004071 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004072
Jay Foad5bd375a2011-07-15 08:37:34 +00004073 CallInst *CI = CallInst::Create(Callee, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004074 CI->setTailCall(isTail);
4075 CI->setCallingConv(CC);
4076 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004077 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004078 Inst = CI;
4079 return false;
4080}
4081
4082//===----------------------------------------------------------------------===//
4083// Memory Instructions.
4084//===----------------------------------------------------------------------===//
4085
4086/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00004087/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00004088int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004089 Value *Size = 0;
Chris Lattner200e0752009-07-02 23:08:13 +00004090 LocTy SizeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004091 unsigned Alignment = 0;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004092 Type *Ty = 0;
David Majnemerc4ab61c2014-03-09 06:41:58 +00004093
4094 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4095
Chris Lattner3822f632009-01-02 08:05:26 +00004096 if (ParseType(Ty)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004097
Chris Lattnerb2f39502009-12-30 05:44:30 +00004098 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004099 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00004100 if (Lex.getKind() == lltok::kw_align) {
4101 if (ParseOptionalAlignment(Alignment)) return true;
4102 } else if (Lex.getKind() == lltok::MetadataVar) {
4103 AteExtraComma = true;
4104 } else {
4105 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4106 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4107 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004108 }
4109 }
4110
Dan Gohman2140a742010-05-28 01:14:11 +00004111 if (Size && !Size->getType()->isIntegerTy())
4112 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004113
Reid Kleckner436c42e2014-01-17 23:58:17 +00004114 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4115 AI->setUsedWithInAlloca(IsInAlloca);
4116 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00004117 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004118}
4119
4120/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00004121/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004122/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00004123/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004124int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004125 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004126 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004127 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004128 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004129 AtomicOrdering Ordering = NotAtomic;
4130 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004131
4132 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004133 isAtomic = true;
4134 Lex.Lex();
4135 }
4136
Chris Lattnerbc639292011-11-27 06:56:53 +00004137 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004138 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004139 isVolatile = true;
4140 Lex.Lex();
4141 }
4142
Chris Lattnerb2f39502009-12-30 05:44:30 +00004143 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004144 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004145 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4146 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004147
Duncan Sands19d0b472010-02-16 11:11:14 +00004148 if (!Val->getType()->isPointerTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004149 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4150 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00004151 if (isAtomic && !Alignment)
4152 return Error(Loc, "atomic load must have explicit non-zero alignment");
4153 if (Ordering == Release || Ordering == AcquireRelease)
4154 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004155
Eli Friedman59b66882011-08-09 23:02:53 +00004156 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004157 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004158}
4159
4160/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00004161
4162/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4163/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00004164/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004165int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004166 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004167 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004168 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004169 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004170 AtomicOrdering Ordering = NotAtomic;
4171 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004172
4173 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004174 isAtomic = true;
4175 Lex.Lex();
4176 }
4177
Chris Lattnerbc639292011-11-27 06:56:53 +00004178 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004179 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004180 isVolatile = true;
4181 Lex.Lex();
4182 }
4183
Chris Lattnerac161bf2009-01-02 07:01:27 +00004184 if (ParseTypeAndValue(Val, Loc, PFS) ||
4185 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004186 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004187 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004188 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004189 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00004190
Duncan Sands19d0b472010-02-16 11:11:14 +00004191 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004192 return Error(PtrLoc, "store operand must be a pointer");
4193 if (!Val->getType()->isFirstClassType())
4194 return Error(Loc, "store operand must be a first class value");
4195 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4196 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00004197 if (isAtomic && !Alignment)
4198 return Error(Loc, "atomic store must have explicit non-zero alignment");
4199 if (Ordering == Acquire || Ordering == AcquireRelease)
4200 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004201
Eli Friedman59b66882011-08-09 23:02:53 +00004202 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004203 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004204}
4205
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004206/// ParseCmpXchg
Eli Friedman02e737b2011-08-12 22:50:01 +00004207/// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
Tim Northovere94a5182014-03-11 10:48:52 +00004208/// 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00004209int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004210 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4211 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00004212 AtomicOrdering SuccessOrdering = NotAtomic;
4213 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004214 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004215 bool isVolatile = false;
4216
4217 if (EatIfPresent(lltok::kw_volatile))
4218 isVolatile = true;
4219
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004220 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4221 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4222 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4223 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4224 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00004225 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4226 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004227 return true;
4228
Tim Northovere94a5182014-03-11 10:48:52 +00004229 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004230 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00004231 if (SuccessOrdering < FailureOrdering)
4232 return TokError("cmpxchg must be at least as ordered on success as failure");
4233 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4234 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004235 if (!Ptr->getType()->isPointerTy())
4236 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4237 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4238 return Error(CmpLoc, "compare value and pointer type do not match");
4239 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4240 return Error(NewLoc, "new value and pointer type do not match");
4241 if (!New->getType()->isIntegerTy())
4242 return Error(NewLoc, "cmpxchg operand must be an integer");
4243 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4244 if (Size < 8 || (Size & (Size - 1)))
4245 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4246 " integer");
4247
Tim Northovere94a5182014-03-11 10:48:52 +00004248 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
4249 FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004250 CXI->setVolatile(isVolatile);
4251 Inst = CXI;
4252 return AteExtraComma ? InstExtraComma : InstNormal;
4253}
4254
4255/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00004256/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4257/// 'singlethread'? AtomicOrdering
4258int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004259 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4260 bool AteExtraComma = false;
4261 AtomicOrdering Ordering = NotAtomic;
4262 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004263 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004264 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00004265
4266 if (EatIfPresent(lltok::kw_volatile))
4267 isVolatile = true;
4268
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004269 switch (Lex.getKind()) {
4270 default: return TokError("expected binary operation in atomicrmw");
4271 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4272 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4273 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4274 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4275 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4276 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4277 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4278 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4279 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4280 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4281 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4282 }
4283 Lex.Lex(); // Eat the operation.
4284
4285 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4286 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4287 ParseTypeAndValue(Val, ValLoc, PFS) ||
4288 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4289 return true;
4290
4291 if (Ordering == Unordered)
4292 return TokError("atomicrmw cannot be unordered");
4293 if (!Ptr->getType()->isPointerTy())
4294 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4295 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4296 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4297 if (!Val->getType()->isIntegerTy())
4298 return Error(ValLoc, "atomicrmw operand must be an integer");
4299 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4300 if (Size < 8 || (Size & (Size - 1)))
4301 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4302 " integer");
4303
4304 AtomicRMWInst *RMWI =
4305 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4306 RMWI->setVolatile(isVolatile);
4307 Inst = RMWI;
4308 return AteExtraComma ? InstExtraComma : InstNormal;
4309}
4310
Eli Friedmanfee02c62011-07-25 23:16:38 +00004311/// ParseFence
4312/// ::= 'fence' 'singlethread'? AtomicOrdering
4313int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4314 AtomicOrdering Ordering = NotAtomic;
4315 SynchronizationScope Scope = CrossThread;
4316 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4317 return true;
4318
4319 if (Ordering == Unordered)
4320 return TokError("fence cannot be unordered");
4321 if (Ordering == Monotonic)
4322 return TokError("fence cannot be monotonic");
4323
4324 Inst = new FenceInst(Context, Ordering, Scope);
4325 return InstNormal;
4326}
4327
Chris Lattnerac161bf2009-01-02 07:01:27 +00004328/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00004329/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004330int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00004331 Value *Ptr = 0;
4332 Value *Val = 0;
4333 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00004334
Dan Gohman16cbbe42009-07-29 15:58:36 +00004335 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00004336
Chris Lattner3822f632009-01-02 08:05:26 +00004337 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004338
Eli Benderskyd9806682013-04-22 17:03:42 +00004339 Type *BaseType = Ptr->getType();
4340 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4341 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004342 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004343
Chris Lattnerac161bf2009-01-02 07:01:27 +00004344 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004345 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004346 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00004347 if (Lex.getKind() == lltok::MetadataVar) {
4348 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00004349 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004350 }
Chris Lattner3822f632009-01-02 08:05:26 +00004351 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004352 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004353 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00004354 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4355 return Error(EltLoc, "getelementptr index type missmatch");
4356 if (Val->getType()->isVectorTy()) {
4357 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4358 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4359 if (ValNumEl != PtrNumEl)
4360 return Error(EltLoc,
4361 "getelementptr vector index has a wrong number of elements");
4362 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004363 Indices.push_back(Val);
4364 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004365
Eli Benderskyd9806682013-04-22 17:03:42 +00004366 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4367 return Error(Loc, "base element of getelementptr must be sized");
4368
4369 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004370 return Error(Loc, "invalid getelementptr indices");
Jay Foadd1b78492011-07-25 09:48:08 +00004371 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00004372 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004373 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004374 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004375}
4376
4377/// ParseExtractValue
4378/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004379int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004380 Value *Val; LocTy Loc;
4381 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004382 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004383 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004384 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004385 return true;
4386
Chris Lattner392be582010-02-12 20:49:41 +00004387 if (!Val->getType()->isAggregateType())
4388 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004389
Jay Foad57aa6362011-07-13 10:26:04 +00004390 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004391 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004392 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004393 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004394}
4395
4396/// ParseInsertValue
4397/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004398int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004399 Value *Val0, *Val1; LocTy Loc0, Loc1;
4400 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004401 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004402 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4403 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4404 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004405 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004406 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004407
Chris Lattner392be582010-02-12 20:49:41 +00004408 if (!Val0->getType()->isAggregateType())
4409 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004410
Jay Foad57aa6362011-07-13 10:26:04 +00004411 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004412 return Error(Loc0, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004413 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004414 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004415}
Nick Lewycky49f89192009-04-04 07:22:01 +00004416
4417//===----------------------------------------------------------------------===//
4418// Embedded metadata.
4419//===----------------------------------------------------------------------===//
4420
4421/// ParseMDNodeVector
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004422/// ::= Element (',' Element)*
4423/// Element
4424/// ::= 'null' | TypeAndValue
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00004425bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandezb8fd1522010-01-10 07:14:18 +00004426 PerFunctionState *PFS) {
Dan Gohman1e0213a2010-07-13 19:33:27 +00004427 // Check for an empty list.
4428 if (Lex.getKind() == lltok::rbrace)
4429 return false;
4430
Nick Lewycky49f89192009-04-04 07:22:01 +00004431 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004432 // Null is a special case since it is typeless.
4433 if (EatIfPresent(lltok::kw_null)) {
4434 Elts.push_back(0);
4435 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004436 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004437
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004438 Value *V = 0;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004439 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004440 Elts.push_back(V);
Nick Lewycky49f89192009-04-04 07:22:01 +00004441 } while (EatIfPresent(lltok::comma));
4442
4443 return false;
4444}