1 //===- DarwinAsmParser.cpp - Darwin (Mach-O) Assembly Parser --------------===//
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 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/StringRef.h"
13 #include "llvm/ADT/StringSwitch.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCObjectFileInfo.h"
18 #include "llvm/MC/MCParser/MCAsmLexer.h"
19 #include "llvm/MC/MCParser/MCAsmParser.h"
20 #include "llvm/MC/MCSectionMachO.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/MC/MCSymbol.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/SourceMgr.h"
26 using namespace llvm;
27 
28 namespace {
29 
30 /// \brief Implementation of directive handling which is shared across all
31 /// Darwin targets.
32 class DarwinAsmParser : public MCAsmParserExtension {
33   template<bool (DarwinAsmParser::*HandlerMethod)(StringRef, SMLoc)>
34   void addDirectiveHandler(StringRef Directive) {
35     MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair(
36         this, HandleDirective<DarwinAsmParser, HandlerMethod>);
37     getParser().addDirectiveHandler(Directive, Handler);
38   }
39 
40   bool parseSectionSwitch(const char *Segment, const char *Section,
41                           unsigned TAA = 0, unsigned ImplicitAlign = 0,
42                           unsigned StubSize = 0);
43 
44   SMLoc LastVersionMinDirective;
45 
46 public:
47   DarwinAsmParser() {}
48 
49   void Initialize(MCAsmParser &Parser) override {
50     // Call the base implementation.
51     this->MCAsmParserExtension::Initialize(Parser);
52 
53     addDirectiveHandler<&DarwinAsmParser::parseDirectiveAltEntry>(".alt_entry");
54     addDirectiveHandler<&DarwinAsmParser::parseDirectiveDesc>(".desc");
55     addDirectiveHandler<&DarwinAsmParser::parseDirectiveIndirectSymbol>(
56       ".indirect_symbol");
57     addDirectiveHandler<&DarwinAsmParser::parseDirectiveLsym>(".lsym");
58     addDirectiveHandler<&DarwinAsmParser::parseDirectiveSubsectionsViaSymbols>(
59       ".subsections_via_symbols");
60     addDirectiveHandler<&DarwinAsmParser::parseDirectiveDumpOrLoad>(".dump");
61     addDirectiveHandler<&DarwinAsmParser::parseDirectiveDumpOrLoad>(".load");
62     addDirectiveHandler<&DarwinAsmParser::parseDirectiveSection>(".section");
63     addDirectiveHandler<&DarwinAsmParser::parseDirectivePushSection>(
64       ".pushsection");
65     addDirectiveHandler<&DarwinAsmParser::parseDirectivePopSection>(
66       ".popsection");
67     addDirectiveHandler<&DarwinAsmParser::parseDirectivePrevious>(".previous");
68     addDirectiveHandler<&DarwinAsmParser::parseDirectiveSecureLogUnique>(
69       ".secure_log_unique");
70     addDirectiveHandler<&DarwinAsmParser::parseDirectiveSecureLogReset>(
71       ".secure_log_reset");
72     addDirectiveHandler<&DarwinAsmParser::parseDirectiveTBSS>(".tbss");
73     addDirectiveHandler<&DarwinAsmParser::parseDirectiveZerofill>(".zerofill");
74 
75     addDirectiveHandler<&DarwinAsmParser::parseDirectiveDataRegion>(
76       ".data_region");
77     addDirectiveHandler<&DarwinAsmParser::parseDirectiveDataRegionEnd>(
78       ".end_data_region");
79 
80     // Special section directives.
81     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveBss>(".bss");
82     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveConst>(".const");
83     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveConstData>(
84       ".const_data");
85     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveConstructor>(
86       ".constructor");
87     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveCString>(
88       ".cstring");
89     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveData>(".data");
90     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveDestructor>(
91       ".destructor");
92     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveDyld>(".dyld");
93     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveFVMLibInit0>(
94       ".fvmlib_init0");
95     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveFVMLibInit1>(
96       ".fvmlib_init1");
97     addDirectiveHandler<
98       &DarwinAsmParser::parseSectionDirectiveLazySymbolPointers>(
99         ".lazy_symbol_pointer");
100     addDirectiveHandler<&DarwinAsmParser::parseDirectiveLinkerOption>(
101       ".linker_option");
102     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveLiteral16>(
103       ".literal16");
104     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveLiteral4>(
105       ".literal4");
106     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveLiteral8>(
107       ".literal8");
108     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveModInitFunc>(
109       ".mod_init_func");
110     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveModTermFunc>(
111       ".mod_term_func");
112     addDirectiveHandler<
113       &DarwinAsmParser::parseSectionDirectiveNonLazySymbolPointers>(
114         ".non_lazy_symbol_pointer");
115     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCCatClsMeth>(
116       ".objc_cat_cls_meth");
117     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCCatInstMeth>(
118       ".objc_cat_inst_meth");
119     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCCategory>(
120       ".objc_category");
121     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClass>(
122       ".objc_class");
123     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClassNames>(
124       ".objc_class_names");
125     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClassVars>(
126       ".objc_class_vars");
127     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClsMeth>(
128       ".objc_cls_meth");
129     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClsRefs>(
130       ".objc_cls_refs");
131     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCInstMeth>(
132       ".objc_inst_meth");
133     addDirectiveHandler<
134       &DarwinAsmParser::parseSectionDirectiveObjCInstanceVars>(
135         ".objc_instance_vars");
136     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCMessageRefs>(
137       ".objc_message_refs");
138     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCMetaClass>(
139       ".objc_meta_class");
140     addDirectiveHandler<
141       &DarwinAsmParser::parseSectionDirectiveObjCMethVarNames>(
142         ".objc_meth_var_names");
143     addDirectiveHandler<
144       &DarwinAsmParser::parseSectionDirectiveObjCMethVarTypes>(
145         ".objc_meth_var_types");
146     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCModuleInfo>(
147       ".objc_module_info");
148     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCProtocol>(
149       ".objc_protocol");
150     addDirectiveHandler<
151       &DarwinAsmParser::parseSectionDirectiveObjCSelectorStrs>(
152         ".objc_selector_strs");
153     addDirectiveHandler<
154       &DarwinAsmParser::parseSectionDirectiveObjCStringObject>(
155         ".objc_string_object");
156     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCSymbols>(
157       ".objc_symbols");
158     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectivePICSymbolStub>(
159       ".picsymbol_stub");
160     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveStaticConst>(
161       ".static_const");
162     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveStaticData>(
163       ".static_data");
164     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveSymbolStub>(
165       ".symbol_stub");
166     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveTData>(".tdata");
167     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveText>(".text");
168     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveThreadInitFunc>(
169       ".thread_init_func");
170     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveTLV>(".tlv");
171 
172     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveIdent>(".ident");
173     addDirectiveHandler<&DarwinAsmParser::parseVersionMin>(
174       ".watchos_version_min");
175     addDirectiveHandler<&DarwinAsmParser::parseVersionMin>(".tvos_version_min");
176     addDirectiveHandler<&DarwinAsmParser::parseVersionMin>(".ios_version_min");
177     addDirectiveHandler<&DarwinAsmParser::parseVersionMin>(
178       ".macosx_version_min");
179 
180     LastVersionMinDirective = SMLoc();
181   }
182 
183   bool parseDirectiveAltEntry(StringRef, SMLoc);
184   bool parseDirectiveDesc(StringRef, SMLoc);
185   bool parseDirectiveIndirectSymbol(StringRef, SMLoc);
186   bool parseDirectiveDumpOrLoad(StringRef, SMLoc);
187   bool parseDirectiveLsym(StringRef, SMLoc);
188   bool parseDirectiveLinkerOption(StringRef, SMLoc);
189   bool parseDirectiveSection(StringRef, SMLoc);
190   bool parseDirectivePushSection(StringRef, SMLoc);
191   bool parseDirectivePopSection(StringRef, SMLoc);
192   bool parseDirectivePrevious(StringRef, SMLoc);
193   bool parseDirectiveSecureLogReset(StringRef, SMLoc);
194   bool parseDirectiveSecureLogUnique(StringRef, SMLoc);
195   bool parseDirectiveSubsectionsViaSymbols(StringRef, SMLoc);
196   bool parseDirectiveTBSS(StringRef, SMLoc);
197   bool parseDirectiveZerofill(StringRef, SMLoc);
198   bool parseDirectiveDataRegion(StringRef, SMLoc);
199   bool parseDirectiveDataRegionEnd(StringRef, SMLoc);
200 
201   // Named Section Directive
202   bool parseSectionDirectiveBss(StringRef, SMLoc) {
203     return parseSectionSwitch("__DATA", "__bss");
204   }
205 
206   bool parseSectionDirectiveConst(StringRef, SMLoc) {
207     return parseSectionSwitch("__TEXT", "__const");
208   }
209   bool parseSectionDirectiveStaticConst(StringRef, SMLoc) {
210     return parseSectionSwitch("__TEXT", "__static_const");
211   }
212   bool parseSectionDirectiveCString(StringRef, SMLoc) {
213     return parseSectionSwitch("__TEXT","__cstring",
214                               MachO::S_CSTRING_LITERALS);
215   }
216   bool parseSectionDirectiveLiteral4(StringRef, SMLoc) {
217     return parseSectionSwitch("__TEXT", "__literal4",
218                               MachO::S_4BYTE_LITERALS, 4);
219   }
220   bool parseSectionDirectiveLiteral8(StringRef, SMLoc) {
221     return parseSectionSwitch("__TEXT", "__literal8",
222                               MachO::S_8BYTE_LITERALS, 8);
223   }
224   bool parseSectionDirectiveLiteral16(StringRef, SMLoc) {
225     return parseSectionSwitch("__TEXT","__literal16",
226                               MachO::S_16BYTE_LITERALS, 16);
227   }
228   bool parseSectionDirectiveConstructor(StringRef, SMLoc) {
229     return parseSectionSwitch("__TEXT","__constructor");
230   }
231   bool parseSectionDirectiveDestructor(StringRef, SMLoc) {
232     return parseSectionSwitch("__TEXT","__destructor");
233   }
234   bool parseSectionDirectiveFVMLibInit0(StringRef, SMLoc) {
235     return parseSectionSwitch("__TEXT","__fvmlib_init0");
236   }
237   bool parseSectionDirectiveFVMLibInit1(StringRef, SMLoc) {
238     return parseSectionSwitch("__TEXT","__fvmlib_init1");
239   }
240   bool parseSectionDirectiveSymbolStub(StringRef, SMLoc) {
241     return parseSectionSwitch("__TEXT","__symbol_stub",
242                               MachO::S_SYMBOL_STUBS |
243                               MachO::S_ATTR_PURE_INSTRUCTIONS,
244                               // FIXME: Different on PPC and ARM.
245                               0, 16);
246   }
247   bool parseSectionDirectivePICSymbolStub(StringRef, SMLoc) {
248     return parseSectionSwitch("__TEXT","__picsymbol_stub",
249                               MachO::S_SYMBOL_STUBS |
250                               MachO::S_ATTR_PURE_INSTRUCTIONS, 0, 26);
251   }
252   bool parseSectionDirectiveData(StringRef, SMLoc) {
253     return parseSectionSwitch("__DATA", "__data");
254   }
255   bool parseSectionDirectiveStaticData(StringRef, SMLoc) {
256     return parseSectionSwitch("__DATA", "__static_data");
257   }
258   bool parseSectionDirectiveNonLazySymbolPointers(StringRef, SMLoc) {
259     return parseSectionSwitch("__DATA", "__nl_symbol_ptr",
260                               MachO::S_NON_LAZY_SYMBOL_POINTERS, 4);
261   }
262   bool parseSectionDirectiveLazySymbolPointers(StringRef, SMLoc) {
263     return parseSectionSwitch("__DATA", "__la_symbol_ptr",
264                               MachO::S_LAZY_SYMBOL_POINTERS, 4);
265   }
266   bool parseSectionDirectiveDyld(StringRef, SMLoc) {
267     return parseSectionSwitch("__DATA", "__dyld");
268   }
269   bool parseSectionDirectiveModInitFunc(StringRef, SMLoc) {
270     return parseSectionSwitch("__DATA", "__mod_init_func",
271                               MachO::S_MOD_INIT_FUNC_POINTERS, 4);
272   }
273   bool parseSectionDirectiveModTermFunc(StringRef, SMLoc) {
274     return parseSectionSwitch("__DATA", "__mod_term_func",
275                               MachO::S_MOD_TERM_FUNC_POINTERS, 4);
276   }
277   bool parseSectionDirectiveConstData(StringRef, SMLoc) {
278     return parseSectionSwitch("__DATA", "__const");
279   }
280   bool parseSectionDirectiveObjCClass(StringRef, SMLoc) {
281     return parseSectionSwitch("__OBJC", "__class",
282                               MachO::S_ATTR_NO_DEAD_STRIP);
283   }
284   bool parseSectionDirectiveObjCMetaClass(StringRef, SMLoc) {
285     return parseSectionSwitch("__OBJC", "__meta_class",
286                               MachO::S_ATTR_NO_DEAD_STRIP);
287   }
288   bool parseSectionDirectiveObjCCatClsMeth(StringRef, SMLoc) {
289     return parseSectionSwitch("__OBJC", "__cat_cls_meth",
290                               MachO::S_ATTR_NO_DEAD_STRIP);
291   }
292   bool parseSectionDirectiveObjCCatInstMeth(StringRef, SMLoc) {
293     return parseSectionSwitch("__OBJC", "__cat_inst_meth",
294                               MachO::S_ATTR_NO_DEAD_STRIP);
295   }
296   bool parseSectionDirectiveObjCProtocol(StringRef, SMLoc) {
297     return parseSectionSwitch("__OBJC", "__protocol",
298                               MachO::S_ATTR_NO_DEAD_STRIP);
299   }
300   bool parseSectionDirectiveObjCStringObject(StringRef, SMLoc) {
301     return parseSectionSwitch("__OBJC", "__string_object",
302                               MachO::S_ATTR_NO_DEAD_STRIP);
303   }
304   bool parseSectionDirectiveObjCClsMeth(StringRef, SMLoc) {
305     return parseSectionSwitch("__OBJC", "__cls_meth",
306                               MachO::S_ATTR_NO_DEAD_STRIP);
307   }
308   bool parseSectionDirectiveObjCInstMeth(StringRef, SMLoc) {
309     return parseSectionSwitch("__OBJC", "__inst_meth",
310                               MachO::S_ATTR_NO_DEAD_STRIP);
311   }
312   bool parseSectionDirectiveObjCClsRefs(StringRef, SMLoc) {
313     return parseSectionSwitch("__OBJC", "__cls_refs",
314                               MachO::S_ATTR_NO_DEAD_STRIP |
315                               MachO::S_LITERAL_POINTERS, 4);
316   }
317   bool parseSectionDirectiveObjCMessageRefs(StringRef, SMLoc) {
318     return parseSectionSwitch("__OBJC", "__message_refs",
319                               MachO::S_ATTR_NO_DEAD_STRIP |
320                               MachO::S_LITERAL_POINTERS, 4);
321   }
322   bool parseSectionDirectiveObjCSymbols(StringRef, SMLoc) {
323     return parseSectionSwitch("__OBJC", "__symbols",
324                               MachO::S_ATTR_NO_DEAD_STRIP);
325   }
326   bool parseSectionDirectiveObjCCategory(StringRef, SMLoc) {
327     return parseSectionSwitch("__OBJC", "__category",
328                               MachO::S_ATTR_NO_DEAD_STRIP);
329   }
330   bool parseSectionDirectiveObjCClassVars(StringRef, SMLoc) {
331     return parseSectionSwitch("__OBJC", "__class_vars",
332                               MachO::S_ATTR_NO_DEAD_STRIP);
333   }
334   bool parseSectionDirectiveObjCInstanceVars(StringRef, SMLoc) {
335     return parseSectionSwitch("__OBJC", "__instance_vars",
336                               MachO::S_ATTR_NO_DEAD_STRIP);
337   }
338   bool parseSectionDirectiveObjCModuleInfo(StringRef, SMLoc) {
339     return parseSectionSwitch("__OBJC", "__module_info",
340                               MachO::S_ATTR_NO_DEAD_STRIP);
341   }
342   bool parseSectionDirectiveObjCClassNames(StringRef, SMLoc) {
343     return parseSectionSwitch("__TEXT", "__cstring",
344                               MachO::S_CSTRING_LITERALS);
345   }
346   bool parseSectionDirectiveObjCMethVarTypes(StringRef, SMLoc) {
347     return parseSectionSwitch("__TEXT", "__cstring",
348                               MachO::S_CSTRING_LITERALS);
349   }
350   bool parseSectionDirectiveObjCMethVarNames(StringRef, SMLoc) {
351     return parseSectionSwitch("__TEXT", "__cstring",
352                               MachO::S_CSTRING_LITERALS);
353   }
354   bool parseSectionDirectiveObjCSelectorStrs(StringRef, SMLoc) {
355     return parseSectionSwitch("__OBJC", "__selector_strs",
356                               MachO::S_CSTRING_LITERALS);
357   }
358   bool parseSectionDirectiveTData(StringRef, SMLoc) {
359     return parseSectionSwitch("__DATA", "__thread_data",
360                               MachO::S_THREAD_LOCAL_REGULAR);
361   }
362   bool parseSectionDirectiveText(StringRef, SMLoc) {
363     return parseSectionSwitch("__TEXT", "__text",
364                               MachO::S_ATTR_PURE_INSTRUCTIONS);
365   }
366   bool parseSectionDirectiveTLV(StringRef, SMLoc) {
367     return parseSectionSwitch("__DATA", "__thread_vars",
368                               MachO::S_THREAD_LOCAL_VARIABLES);
369   }
370   bool parseSectionDirectiveIdent(StringRef, SMLoc) {
371     // Darwin silently ignores the .ident directive.
372     getParser().eatToEndOfStatement();
373     return false;
374   }
375   bool parseSectionDirectiveThreadInitFunc(StringRef, SMLoc) {
376     return parseSectionSwitch("__DATA", "__thread_init",
377                          MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS);
378   }
379   bool parseVersionMin(StringRef, SMLoc);
380 
381 };
382 
383 } // end anonymous namespace
384 
385 bool DarwinAsmParser::parseSectionSwitch(const char *Segment,
386                                          const char *Section,
387                                          unsigned TAA, unsigned Align,
388                                          unsigned StubSize) {
389   if (getLexer().isNot(AsmToken::EndOfStatement))
390     return TokError("unexpected token in section switching directive");
391   Lex();
392 
393   // FIXME: Arch specific.
394   bool isText = TAA & MachO::S_ATTR_PURE_INSTRUCTIONS;
395   getStreamer().SwitchSection(getContext().getMachOSection(
396       Segment, Section, TAA, StubSize,
397       isText ? SectionKind::getText() : SectionKind::getData()));
398 
399   // Set the implicit alignment, if any.
400   //
401   // FIXME: This isn't really what 'as' does; I think it just uses the implicit
402   // alignment on the section (e.g., if one manually inserts bytes into the
403   // section, then just issuing the section switch directive will not realign
404   // the section. However, this is arguably more reasonable behavior, and there
405   // is no good reason for someone to intentionally emit incorrectly sized
406   // values into the implicitly aligned sections.
407   if (Align)
408     getStreamer().EmitValueToAlignment(Align);
409 
410   return false;
411 }
412 
413 /// parseDirectiveAltEntry
414 ///  ::= .alt_entry identifier
415 bool DarwinAsmParser::parseDirectiveAltEntry(StringRef, SMLoc) {
416   StringRef Name;
417   if (getParser().parseIdentifier(Name))
418     return TokError("expected identifier in directive");
419 
420   // Look up symbol.
421   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
422 
423   if (Sym->isDefined())
424     return TokError(".alt_entry must preceed symbol definition");
425 
426   if (!getStreamer().EmitSymbolAttribute(Sym, MCSA_AltEntry))
427     return TokError("unable to emit symbol attribute");
428 
429   Lex();
430   return false;
431 }
432 
433 /// parseDirectiveDesc
434 ///  ::= .desc identifier , expression
435 bool DarwinAsmParser::parseDirectiveDesc(StringRef, SMLoc) {
436   StringRef Name;
437   if (getParser().parseIdentifier(Name))
438     return TokError("expected identifier in directive");
439 
440   // Handle the identifier as the key symbol.
441   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
442 
443   if (getLexer().isNot(AsmToken::Comma))
444     return TokError("unexpected token in '.desc' directive");
445   Lex();
446 
447   int64_t DescValue;
448   if (getParser().parseAbsoluteExpression(DescValue))
449     return true;
450 
451   if (getLexer().isNot(AsmToken::EndOfStatement))
452     return TokError("unexpected token in '.desc' directive");
453 
454   Lex();
455 
456   // Set the n_desc field of this Symbol to this DescValue
457   getStreamer().EmitSymbolDesc(Sym, DescValue);
458 
459   return false;
460 }
461 
462 /// parseDirectiveIndirectSymbol
463 ///  ::= .indirect_symbol identifier
464 bool DarwinAsmParser::parseDirectiveIndirectSymbol(StringRef, SMLoc Loc) {
465   const MCSectionMachO *Current = static_cast<const MCSectionMachO*>(
466                                        getStreamer().getCurrentSection().first);
467   MachO::SectionType SectionType = Current->getType();
468   if (SectionType != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
469       SectionType != MachO::S_LAZY_SYMBOL_POINTERS &&
470       SectionType != MachO::S_SYMBOL_STUBS)
471     return Error(Loc, "indirect symbol not in a symbol pointer or stub "
472                       "section");
473 
474   StringRef Name;
475   if (getParser().parseIdentifier(Name))
476     return TokError("expected identifier in .indirect_symbol directive");
477 
478   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
479 
480   // Assembler local symbols don't make any sense here. Complain loudly.
481   if (Sym->isTemporary())
482     return TokError("non-local symbol required in directive");
483 
484   if (!getStreamer().EmitSymbolAttribute(Sym, MCSA_IndirectSymbol))
485     return TokError("unable to emit indirect symbol attribute for: " + Name);
486 
487   if (getLexer().isNot(AsmToken::EndOfStatement))
488     return TokError("unexpected token in '.indirect_symbol' directive");
489 
490   Lex();
491 
492   return false;
493 }
494 
495 /// parseDirectiveDumpOrLoad
496 ///  ::= ( .dump | .load ) "filename"
497 bool DarwinAsmParser::parseDirectiveDumpOrLoad(StringRef Directive,
498                                                SMLoc IDLoc) {
499   bool IsDump = Directive == ".dump";
500   if (getLexer().isNot(AsmToken::String))
501     return TokError("expected string in '.dump' or '.load' directive");
502 
503   Lex();
504 
505   if (getLexer().isNot(AsmToken::EndOfStatement))
506     return TokError("unexpected token in '.dump' or '.load' directive");
507 
508   Lex();
509 
510   // FIXME: If/when .dump and .load are implemented they will be done in the
511   // the assembly parser and not have any need for an MCStreamer API.
512   if (IsDump)
513     return Warning(IDLoc, "ignoring directive .dump for now");
514   else
515     return Warning(IDLoc, "ignoring directive .load for now");
516 }
517 
518 /// ParseDirectiveLinkerOption
519 ///  ::= .linker_option "string" ( , "string" )*
520 bool DarwinAsmParser::parseDirectiveLinkerOption(StringRef IDVal, SMLoc) {
521   SmallVector<std::string, 4> Args;
522   for (;;) {
523     if (getLexer().isNot(AsmToken::String))
524       return TokError("expected string in '" + Twine(IDVal) + "' directive");
525 
526     std::string Data;
527     if (getParser().parseEscapedString(Data))
528       return true;
529 
530     Args.push_back(Data);
531 
532     Lex();
533     if (getLexer().is(AsmToken::EndOfStatement))
534       break;
535 
536     if (getLexer().isNot(AsmToken::Comma))
537       return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
538     Lex();
539   }
540 
541   getStreamer().EmitLinkerOptions(Args);
542   return false;
543 }
544 
545 /// parseDirectiveLsym
546 ///  ::= .lsym identifier , expression
547 bool DarwinAsmParser::parseDirectiveLsym(StringRef, SMLoc) {
548   StringRef Name;
549   if (getParser().parseIdentifier(Name))
550     return TokError("expected identifier in directive");
551 
552   // Handle the identifier as the key symbol.
553   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
554 
555   if (getLexer().isNot(AsmToken::Comma))
556     return TokError("unexpected token in '.lsym' directive");
557   Lex();
558 
559   const MCExpr *Value;
560   if (getParser().parseExpression(Value))
561     return true;
562 
563   if (getLexer().isNot(AsmToken::EndOfStatement))
564     return TokError("unexpected token in '.lsym' directive");
565 
566   Lex();
567 
568   // We don't currently support this directive.
569   //
570   // FIXME: Diagnostic location!
571   (void) Sym;
572   return TokError("directive '.lsym' is unsupported");
573 }
574 
575 /// parseDirectiveSection:
576 ///   ::= .section identifier (',' identifier)*
577 bool DarwinAsmParser::parseDirectiveSection(StringRef, SMLoc) {
578   SMLoc Loc = getLexer().getLoc();
579 
580   StringRef SectionName;
581   if (getParser().parseIdentifier(SectionName))
582     return Error(Loc, "expected identifier after '.section' directive");
583 
584   // Verify there is a following comma.
585   if (!getLexer().is(AsmToken::Comma))
586     return TokError("unexpected token in '.section' directive");
587 
588   std::string SectionSpec = SectionName;
589   SectionSpec += ",";
590 
591   // Add all the tokens until the end of the line, ParseSectionSpecifier will
592   // handle this.
593   StringRef EOL = getLexer().LexUntilEndOfStatement();
594   SectionSpec.append(EOL.begin(), EOL.end());
595 
596   Lex();
597   if (getLexer().isNot(AsmToken::EndOfStatement))
598     return TokError("unexpected token in '.section' directive");
599   Lex();
600 
601 
602   StringRef Segment, Section;
603   unsigned StubSize;
604   unsigned TAA;
605   bool TAAParsed;
606   std::string ErrorStr =
607     MCSectionMachO::ParseSectionSpecifier(SectionSpec, Segment, Section,
608                                           TAA, TAAParsed, StubSize);
609 
610   if (!ErrorStr.empty())
611     return Error(Loc, ErrorStr.c_str());
612 
613   // Issue a warning if the target is not powerpc and Section is a *coal* section.
614   Triple TT = getParser().getContext().getObjectFileInfo()->getTargetTriple();
615   Triple::ArchType ArchTy = TT.getArch();
616 
617   if (ArchTy != Triple::ppc && ArchTy != Triple::ppc64) {
618     StringRef NonCoalSection = StringSwitch<StringRef>(Section)
619                                    .Case("__textcoal_nt", "__text")
620                                    .Case("__const_coal", "__const")
621                                    .Case("__datacoal_nt", "__data")
622                                    .Default(Section);
623 
624     if (!Section.equals(NonCoalSection)) {
625       StringRef SectionVal(Loc.getPointer());
626       size_t B = SectionVal.find(',') + 1, E = SectionVal.find(',', B);
627       SMLoc BLoc = SMLoc::getFromPointer(SectionVal.data() + B);
628       SMLoc ELoc = SMLoc::getFromPointer(SectionVal.data() + E);
629       getParser().Warning(Loc, "section \"" + Section + "\" is deprecated",
630                           SMRange(BLoc, ELoc));
631       getParser().Note(Loc, "change section name to \"" + NonCoalSection +
632                        "\"", SMRange(BLoc, ELoc));
633     }
634   }
635 
636   // FIXME: Arch specific.
637   bool isText = Segment == "__TEXT";  // FIXME: Hack.
638   getStreamer().SwitchSection(getContext().getMachOSection(
639       Segment, Section, TAA, StubSize,
640       isText ? SectionKind::getText() : SectionKind::getData()));
641   return false;
642 }
643 
644 /// ParseDirectivePushSection:
645 ///   ::= .pushsection identifier (',' identifier)*
646 bool DarwinAsmParser::parseDirectivePushSection(StringRef S, SMLoc Loc) {
647   getStreamer().PushSection();
648 
649   if (parseDirectiveSection(S, Loc)) {
650     getStreamer().PopSection();
651     return true;
652   }
653 
654   return false;
655 }
656 
657 /// ParseDirectivePopSection:
658 ///   ::= .popsection
659 bool DarwinAsmParser::parseDirectivePopSection(StringRef, SMLoc) {
660   if (!getStreamer().PopSection())
661     return TokError(".popsection without corresponding .pushsection");
662   return false;
663 }
664 
665 /// ParseDirectivePrevious:
666 ///   ::= .previous
667 bool DarwinAsmParser::parseDirectivePrevious(StringRef DirName, SMLoc) {
668   MCSectionSubPair PreviousSection = getStreamer().getPreviousSection();
669   if (!PreviousSection.first)
670     return TokError(".previous without corresponding .section");
671   getStreamer().SwitchSection(PreviousSection.first, PreviousSection.second);
672   return false;
673 }
674 
675 /// ParseDirectiveSecureLogUnique
676 ///  ::= .secure_log_unique ... message ...
677 bool DarwinAsmParser::parseDirectiveSecureLogUnique(StringRef, SMLoc IDLoc) {
678   StringRef LogMessage = getParser().parseStringToEndOfStatement();
679   if (getLexer().isNot(AsmToken::EndOfStatement))
680     return TokError("unexpected token in '.secure_log_unique' directive");
681 
682   if (getContext().getSecureLogUsed())
683     return Error(IDLoc, ".secure_log_unique specified multiple times");
684 
685   // Get the secure log path.
686   const char *SecureLogFile = getContext().getSecureLogFile();
687   if (!SecureLogFile)
688     return Error(IDLoc, ".secure_log_unique used but AS_SECURE_LOG_FILE "
689                  "environment variable unset.");
690 
691   // Open the secure log file if we haven't already.
692   raw_fd_ostream *OS = getContext().getSecureLog();
693   if (!OS) {
694     std::error_code EC;
695     auto NewOS = llvm::make_unique<raw_fd_ostream>(
696         SecureLogFile, EC, sys::fs::F_Append | sys::fs::F_Text);
697     if (EC)
698        return Error(IDLoc, Twine("can't open secure log file: ") +
699                                SecureLogFile + " (" + EC.message() + ")");
700     OS = NewOS.get();
701     getContext().setSecureLog(std::move(NewOS));
702   }
703 
704   // Write the message.
705   unsigned CurBuf = getSourceManager().FindBufferContainingLoc(IDLoc);
706   *OS << getSourceManager().getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
707       << ":" << getSourceManager().FindLineNumber(IDLoc, CurBuf) << ":"
708       << LogMessage + "\n";
709 
710   getContext().setSecureLogUsed(true);
711 
712   return false;
713 }
714 
715 /// ParseDirectiveSecureLogReset
716 ///  ::= .secure_log_reset
717 bool DarwinAsmParser::parseDirectiveSecureLogReset(StringRef, SMLoc IDLoc) {
718   if (getLexer().isNot(AsmToken::EndOfStatement))
719     return TokError("unexpected token in '.secure_log_reset' directive");
720 
721   Lex();
722 
723   getContext().setSecureLogUsed(false);
724 
725   return false;
726 }
727 
728 /// parseDirectiveSubsectionsViaSymbols
729 ///  ::= .subsections_via_symbols
730 bool DarwinAsmParser::parseDirectiveSubsectionsViaSymbols(StringRef, SMLoc) {
731   if (getLexer().isNot(AsmToken::EndOfStatement))
732     return TokError("unexpected token in '.subsections_via_symbols' directive");
733 
734   Lex();
735 
736   getStreamer().EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
737 
738   return false;
739 }
740 
741 /// ParseDirectiveTBSS
742 ///  ::= .tbss identifier, size, align
743 bool DarwinAsmParser::parseDirectiveTBSS(StringRef, SMLoc) {
744   SMLoc IDLoc = getLexer().getLoc();
745   StringRef Name;
746   if (getParser().parseIdentifier(Name))
747     return TokError("expected identifier in directive");
748 
749   // Handle the identifier as the key symbol.
750   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
751 
752   if (getLexer().isNot(AsmToken::Comma))
753     return TokError("unexpected token in directive");
754   Lex();
755 
756   int64_t Size;
757   SMLoc SizeLoc = getLexer().getLoc();
758   if (getParser().parseAbsoluteExpression(Size))
759     return true;
760 
761   int64_t Pow2Alignment = 0;
762   SMLoc Pow2AlignmentLoc;
763   if (getLexer().is(AsmToken::Comma)) {
764     Lex();
765     Pow2AlignmentLoc = getLexer().getLoc();
766     if (getParser().parseAbsoluteExpression(Pow2Alignment))
767       return true;
768   }
769 
770   if (getLexer().isNot(AsmToken::EndOfStatement))
771     return TokError("unexpected token in '.tbss' directive");
772 
773   Lex();
774 
775   if (Size < 0)
776     return Error(SizeLoc, "invalid '.tbss' directive size, can't be less than"
777                  "zero");
778 
779   // FIXME: Diagnose overflow.
780   if (Pow2Alignment < 0)
781     return Error(Pow2AlignmentLoc, "invalid '.tbss' alignment, can't be less"
782                  "than zero");
783 
784   if (!Sym->isUndefined())
785     return Error(IDLoc, "invalid symbol redefinition");
786 
787   getStreamer().EmitTBSSSymbol(getContext().getMachOSection(
788                                  "__DATA", "__thread_bss",
789                                  MachO::S_THREAD_LOCAL_ZEROFILL,
790                                  0, SectionKind::getThreadBSS()),
791                                Sym, Size, 1 << Pow2Alignment);
792 
793   return false;
794 }
795 
796 /// ParseDirectiveZerofill
797 ///  ::= .zerofill segname , sectname [, identifier , size_expression [
798 ///      , align_expression ]]
799 bool DarwinAsmParser::parseDirectiveZerofill(StringRef, SMLoc) {
800   StringRef Segment;
801   if (getParser().parseIdentifier(Segment))
802     return TokError("expected segment name after '.zerofill' directive");
803 
804   if (getLexer().isNot(AsmToken::Comma))
805     return TokError("unexpected token in directive");
806   Lex();
807 
808   StringRef Section;
809   if (getParser().parseIdentifier(Section))
810     return TokError("expected section name after comma in '.zerofill' "
811                     "directive");
812 
813   // If this is the end of the line all that was wanted was to create the
814   // the section but with no symbol.
815   if (getLexer().is(AsmToken::EndOfStatement)) {
816     // Create the zerofill section but no symbol
817     getStreamer().EmitZerofill(getContext().getMachOSection(
818                                  Segment, Section, MachO::S_ZEROFILL,
819                                  0, SectionKind::getBSS()));
820     return false;
821   }
822 
823   if (getLexer().isNot(AsmToken::Comma))
824     return TokError("unexpected token in directive");
825   Lex();
826 
827   SMLoc IDLoc = getLexer().getLoc();
828   StringRef IDStr;
829   if (getParser().parseIdentifier(IDStr))
830     return TokError("expected identifier in directive");
831 
832   // handle the identifier as the key symbol.
833   MCSymbol *Sym = getContext().getOrCreateSymbol(IDStr);
834 
835   if (getLexer().isNot(AsmToken::Comma))
836     return TokError("unexpected token in directive");
837   Lex();
838 
839   int64_t Size;
840   SMLoc SizeLoc = getLexer().getLoc();
841   if (getParser().parseAbsoluteExpression(Size))
842     return true;
843 
844   int64_t Pow2Alignment = 0;
845   SMLoc Pow2AlignmentLoc;
846   if (getLexer().is(AsmToken::Comma)) {
847     Lex();
848     Pow2AlignmentLoc = getLexer().getLoc();
849     if (getParser().parseAbsoluteExpression(Pow2Alignment))
850       return true;
851   }
852 
853   if (getLexer().isNot(AsmToken::EndOfStatement))
854     return TokError("unexpected token in '.zerofill' directive");
855 
856   Lex();
857 
858   if (Size < 0)
859     return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
860                  "than zero");
861 
862   // NOTE: The alignment in the directive is a power of 2 value, the assembler
863   // may internally end up wanting an alignment in bytes.
864   // FIXME: Diagnose overflow.
865   if (Pow2Alignment < 0)
866     return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
867                  "can't be less than zero");
868 
869   if (!Sym->isUndefined())
870     return Error(IDLoc, "invalid symbol redefinition");
871 
872   // Create the zerofill Symbol with Size and Pow2Alignment
873   //
874   // FIXME: Arch specific.
875   getStreamer().EmitZerofill(getContext().getMachOSection(
876                                Segment, Section, MachO::S_ZEROFILL,
877                                0, SectionKind::getBSS()),
878                              Sym, Size, 1 << Pow2Alignment);
879 
880   return false;
881 }
882 
883 /// ParseDirectiveDataRegion
884 ///  ::= .data_region [ ( jt8 | jt16 | jt32 ) ]
885 bool DarwinAsmParser::parseDirectiveDataRegion(StringRef, SMLoc) {
886   if (getLexer().is(AsmToken::EndOfStatement)) {
887     Lex();
888     getStreamer().EmitDataRegion(MCDR_DataRegion);
889     return false;
890   }
891   StringRef RegionType;
892   SMLoc Loc = getParser().getTok().getLoc();
893   if (getParser().parseIdentifier(RegionType))
894     return TokError("expected region type after '.data_region' directive");
895   int Kind = StringSwitch<int>(RegionType)
896     .Case("jt8", MCDR_DataRegionJT8)
897     .Case("jt16", MCDR_DataRegionJT16)
898     .Case("jt32", MCDR_DataRegionJT32)
899     .Default(-1);
900   if (Kind == -1)
901     return Error(Loc, "unknown region type in '.data_region' directive");
902   Lex();
903 
904   getStreamer().EmitDataRegion((MCDataRegionType)Kind);
905   return false;
906 }
907 
908 /// ParseDirectiveDataRegionEnd
909 ///  ::= .end_data_region
910 bool DarwinAsmParser::parseDirectiveDataRegionEnd(StringRef, SMLoc) {
911   if (getLexer().isNot(AsmToken::EndOfStatement))
912     return TokError("unexpected token in '.end_data_region' directive");
913 
914   Lex();
915   getStreamer().EmitDataRegion(MCDR_DataRegionEnd);
916   return false;
917 }
918 
919 /// parseVersionMin
920 ///  ::= .ios_version_min major,minor[,update]
921 ///  ::= .macosx_version_min major,minor[,update]
922 bool DarwinAsmParser::parseVersionMin(StringRef Directive, SMLoc Loc) {
923   int64_t Major = 0, Minor = 0, Update = 0;
924   int Kind = StringSwitch<int>(Directive)
925     .Case(".watchos_version_min", MCVM_WatchOSVersionMin)
926     .Case(".tvos_version_min", MCVM_TvOSVersionMin)
927     .Case(".ios_version_min", MCVM_IOSVersionMin)
928     .Case(".macosx_version_min", MCVM_OSXVersionMin);
929   // Get the major version number.
930   if (getLexer().isNot(AsmToken::Integer))
931     return TokError("invalid OS major version number");
932   Major = getLexer().getTok().getIntVal();
933   if (Major > 65535 || Major <= 0)
934     return TokError("invalid OS major version number");
935   Lex();
936   if (getLexer().isNot(AsmToken::Comma))
937     return TokError("minor OS version number required, comma expected");
938   Lex();
939   // Get the minor version number.
940   if (getLexer().isNot(AsmToken::Integer))
941     return TokError("invalid OS minor version number");
942   Minor = getLexer().getTok().getIntVal();
943   if (Minor > 255 || Minor < 0)
944     return TokError("invalid OS minor version number");
945   Lex();
946   // Get the update level, if specified
947   if (getLexer().isNot(AsmToken::EndOfStatement)) {
948     if (getLexer().isNot(AsmToken::Comma))
949       return TokError("invalid update specifier, comma expected");
950     Lex();
951     if (getLexer().isNot(AsmToken::Integer))
952       return TokError("invalid OS update number");
953     Update = getLexer().getTok().getIntVal();
954   if (Update > 255 || Update < 0)
955     return TokError("invalid OS update number");
956     Lex();
957   }
958 
959   const Triple &T = getContext().getObjectFileInfo()->getTargetTriple();
960   Triple::OSType ExpectedOS = Triple::UnknownOS;
961   switch ((MCVersionMinType)Kind) {
962   case MCVM_WatchOSVersionMin: ExpectedOS = Triple::WatchOS; break;
963   case MCVM_TvOSVersionMin:    ExpectedOS = Triple::TvOS;    break;
964   case MCVM_IOSVersionMin:     ExpectedOS = Triple::IOS;     break;
965   case MCVM_OSXVersionMin:     ExpectedOS = Triple::MacOSX;  break;
966   }
967   if (T.getOS() != ExpectedOS)
968     Warning(Loc, Directive + " should only be used for " +
969             Triple::getOSTypeName(ExpectedOS) + " targets");
970 
971   if (LastVersionMinDirective.isValid()) {
972     Warning(Loc, "overriding previous version_min directive");
973     Note(LastVersionMinDirective, "previous definition is here");
974   }
975   LastVersionMinDirective = Loc;
976 
977   // We've parsed a correct version specifier, so send it to the streamer.
978   getStreamer().EmitVersionMin((MCVersionMinType)Kind, Major, Minor, Update);
979 
980   return false;
981 }
982 
983 namespace llvm {
984 
985 MCAsmParserExtension *createDarwinAsmParser() {
986   return new DarwinAsmParser;
987 }
988 
989 } // end llvm namespace
990