Bug Summary

File:lib/MC/MCParser/DarwinAsmParser.cpp
Warning:line 1134, column 3
2nd function call argument is an uninitialized value

Annotated Source Code

[?] Use j/k keys for keyboard navigation

/build/llvm-toolchain-snapshot-6.0~svn321639/lib/MC/MCParser/DarwinAsmParser.cpp

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

/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/MC/MCParser/MCAsmParserExtension.h

1//===- llvm/MC/MCAsmParserExtension.h - Asm Parser Hooks --------*- C++ -*-===//
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#ifndef LLVM_MC_MCPARSER_MCASMPARSEREXTENSION_H
11#define LLVM_MC_MCPARSER_MCASMPARSEREXTENSION_H
12
13#include "llvm/ADT/STLExtras.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/MC/MCParser/MCAsmLexer.h"
16#include "llvm/MC/MCParser/MCAsmParser.h"
17#include "llvm/Support/SMLoc.h"
18
19namespace llvm {
20
21class Twine;
22
23/// \brief Generic interface for extending the MCAsmParser,
24/// which is implemented by target and object file assembly parser
25/// implementations.
26class MCAsmParserExtension {
27 MCAsmParser *Parser;
28
29protected:
30 MCAsmParserExtension();
31
32 // Helper template for implementing static dispatch functions.
33 template<typename T, bool (T::*Handler)(StringRef, SMLoc)>
34 static bool HandleDirective(MCAsmParserExtension *Target,
35 StringRef Directive,
36 SMLoc DirectiveLoc) {
37 T *Obj = static_cast<T*>(Target);
38 return (Obj->*Handler)(Directive, DirectiveLoc);
39 }
40
41 bool BracketExpressionsSupported = false;
42
43public:
44 MCAsmParserExtension(const MCAsmParserExtension &) = delete;
45 MCAsmParserExtension &operator=(const MCAsmParserExtension &) = delete;
46 virtual ~MCAsmParserExtension();
47
48 /// \brief Initialize the extension for parsing using the given \p Parser.
49 /// The extension should use the AsmParser interfaces to register its
50 /// parsing routines.
51 virtual void Initialize(MCAsmParser &Parser);
52
53 /// \name MCAsmParser Proxy Interfaces
54 /// @{
55
56 MCContext &getContext() { return getParser().getContext(); }
57
58 MCAsmLexer &getLexer() { return getParser().getLexer(); }
8
Calling 'MCAsmParserExtension::getParser'
9
Returning from 'MCAsmParserExtension::getParser'
59 const MCAsmLexer &getLexer() const {
60 return const_cast<MCAsmParserExtension *>(this)->getLexer();
61 }
62
63 MCAsmParser &getParser() { return *Parser; }
64 const MCAsmParser &getParser() const {
65 return const_cast<MCAsmParserExtension*>(this)->getParser();
66 }
67
68 SourceMgr &getSourceManager() { return getParser().getSourceManager(); }
69 MCStreamer &getStreamer() { return getParser().getStreamer(); }
70
71 bool Warning(SMLoc L, const Twine &Msg) {
72 return getParser().Warning(L, Msg);
73 }
74
75 bool Error(SMLoc L, const Twine &Msg, SMRange Range = SMRange()) {
76 return getParser().Error(L, Msg, Range);
77 }
78
79 void Note(SMLoc L, const Twine &Msg) {
80 getParser().Note(L, Msg);
81 }
82
83 bool TokError(const Twine &Msg) {
84 return getParser().TokError(Msg);
28
Calling 'MCAsmParserExtension::getParser'
29
Returning from 'MCAsmParserExtension::getParser'
85 }
86
87 const AsmToken &Lex() { return getParser().Lex(); }
88 const AsmToken &getTok() { return getParser().getTok(); }
89 bool parseToken(AsmToken::TokenKind T,
90 const Twine &Msg = "unexpected token") {
91 return getParser().parseToken(T, Msg);
92 }
93
94 bool parseMany(function_ref<bool()> parseOne, bool hasComma = true) {
95 return getParser().parseMany(parseOne, hasComma);
96 }
97
98 bool parseOptionalToken(AsmToken::TokenKind T) {
99 return getParser().parseOptionalToken(T);
100 }
101
102 bool check(bool P, const Twine &Msg) {
103 return getParser().check(P, Msg);
104 }
105
106 bool check(bool P, SMLoc Loc, const Twine &Msg) {
107 return getParser().check(P, Loc, Msg);
108 }
109
110 bool addErrorSuffix(const Twine &Suffix) {
111 return getParser().addErrorSuffix(Suffix);
112 }
113
114 bool HasBracketExpressions() const { return BracketExpressionsSupported; }
115
116 /// @}
117};
118
119} // end namespace llvm
120
121#endif // LLVM_MC_MCPARSER_MCASMPARSEREXTENSION_H

/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/MC/MCParser/MCAsmLexer.h

1//===- llvm/MC/MCAsmLexer.h - Abstract Asm Lexer Interface ------*- C++ -*-===//
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#ifndef LLVM_MC_MCPARSER_MCASMLEXER_H
11#define LLVM_MC_MCPARSER_MCASMLEXER_H
12
13#include "llvm/ADT/APInt.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/SmallVector.h"
16#include "llvm/ADT/StringRef.h"
17#include "llvm/Support/SMLoc.h"
18#include <algorithm>
19#include <cassert>
20#include <cstddef>
21#include <cstdint>
22#include <string>
23
24namespace llvm {
25
26/// Target independent representation for an assembler token.
27class AsmToken {
28public:
29 enum TokenKind {
30 // Markers
31 Eof, Error,
32
33 // String values.
34 Identifier,
35 String,
36
37 // Integer values.
38 Integer,
39 BigNum, // larger than 64 bits
40
41 // Real values.
42 Real,
43
44 // Comments
45 Comment,
46 HashDirective,
47 // No-value.
48 EndOfStatement,
49 Colon,
50 Space,
51 Plus, Minus, Tilde,
52 Slash, // '/'
53 BackSlash, // '\'
54 LParen, RParen, LBrac, RBrac, LCurly, RCurly,
55 Star, Dot, Comma, Dollar, Equal, EqualEqual,
56
57 Pipe, PipePipe, Caret,
58 Amp, AmpAmp, Exclaim, ExclaimEqual, Percent, Hash,
59 Less, LessEqual, LessLess, LessGreater,
60 Greater, GreaterEqual, GreaterGreater, At,
61
62 // MIPS unary expression operators such as %neg.
63 PercentCall16, PercentCall_Hi, PercentCall_Lo, PercentDtprel_Hi,
64 PercentDtprel_Lo, PercentGot, PercentGot_Disp, PercentGot_Hi, PercentGot_Lo,
65 PercentGot_Ofst, PercentGot_Page, PercentGottprel, PercentGp_Rel, PercentHi,
66 PercentHigher, PercentHighest, PercentLo, PercentNeg, PercentPcrel_Hi,
67 PercentPcrel_Lo, PercentTlsgd, PercentTlsldm, PercentTprel_Hi,
68 PercentTprel_Lo
69 };
70
71private:
72 TokenKind Kind;
73
74 /// A reference to the entire token contents; this is always a pointer into
75 /// a memory buffer owned by the source manager.
76 StringRef Str;
77
78 APInt IntVal;
79
80public:
81 AsmToken() = default;
82 AsmToken(TokenKind Kind, StringRef Str, APInt IntVal)
83 : Kind(Kind), Str(Str), IntVal(std::move(IntVal)) {}
84 AsmToken(TokenKind Kind, StringRef Str, int64_t IntVal = 0)
85 : Kind(Kind), Str(Str), IntVal(64, IntVal, true) {}
86
87 TokenKind getKind() const { return Kind; }
88 bool is(TokenKind K) const { return Kind == K; }
89 bool isNot(TokenKind K) const { return Kind != K; }
15
Assuming the condition is true
90
91 SMLoc getLoc() const;
92 SMLoc getEndLoc() const;
93 SMRange getLocRange() const;
94
95 /// Get the contents of a string token (without quotes).
96 StringRef getStringContents() const {
97 assert(Kind == String && "This token isn't a string!")(static_cast <bool> (Kind == String && "This token isn't a string!"
) ? void (0) : __assert_fail ("Kind == String && \"This token isn't a string!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/MC/MCParser/MCAsmLexer.h"
, 97, __extension__ __PRETTY_FUNCTION__))
;
98 return Str.slice(1, Str.size() - 1);
99 }
100
101 /// Get the identifier string for the current token, which should be an
102 /// identifier or a string. This gets the portion of the string which should
103 /// be used as the identifier, e.g., it does not include the quotes on
104 /// strings.
105 StringRef getIdentifier() const {
106 if (Kind == Identifier)
107 return getString();
108 return getStringContents();
109 }
110
111 /// Get the string for the current token, this includes all characters (for
112 /// example, the quotes on strings) in the token.
113 ///
114 /// The returned StringRef points into the source manager's memory buffer, and
115 /// is safe to store across calls to Lex().
116 StringRef getString() const { return Str; }
117
118 // FIXME: Don't compute this in advance, it makes every token larger, and is
119 // also not generally what we want (it is nicer for recovery etc. to lex 123br
120 // as a single token, then diagnose as an invalid number).
121 int64_t getIntVal() const {
122 assert(Kind == Integer && "This token isn't an integer!")(static_cast <bool> (Kind == Integer && "This token isn't an integer!"
) ? void (0) : __assert_fail ("Kind == Integer && \"This token isn't an integer!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/MC/MCParser/MCAsmLexer.h"
, 122, __extension__ __PRETTY_FUNCTION__))
;
123 return IntVal.getZExtValue();
124 }
125
126 APInt getAPIntVal() const {
127 assert((Kind == Integer || Kind == BigNum) &&(static_cast <bool> ((Kind == Integer || Kind == BigNum
) && "This token isn't an integer!") ? void (0) : __assert_fail
("(Kind == Integer || Kind == BigNum) && \"This token isn't an integer!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/MC/MCParser/MCAsmLexer.h"
, 128, __extension__ __PRETTY_FUNCTION__))
128 "This token isn't an integer!")(static_cast <bool> ((Kind == Integer || Kind == BigNum
) && "This token isn't an integer!") ? void (0) : __assert_fail
("(Kind == Integer || Kind == BigNum) && \"This token isn't an integer!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/MC/MCParser/MCAsmLexer.h"
, 128, __extension__ __PRETTY_FUNCTION__))
;
129 return IntVal;
130 }
131};
132
133/// A callback class which is notified of each comment in an assembly file as
134/// it is lexed.
135class AsmCommentConsumer {
136public:
137 virtual ~AsmCommentConsumer() = default;
138
139 /// Callback function for when a comment is lexed. Loc is the start of the
140 /// comment text (excluding the comment-start marker). CommentText is the text
141 /// of the comment, excluding the comment start and end markers, and the
142 /// newline for single-line comments.
143 virtual void HandleComment(SMLoc Loc, StringRef CommentText) = 0;
144};
145
146
147/// Generic assembler lexer interface, for use by target specific assembly
148/// lexers.
149class MCAsmLexer {
150 /// The current token, stored in the base class for faster access.
151 SmallVector<AsmToken, 1> CurTok;
152
153 /// The location and description of the current error
154 SMLoc ErrLoc;
155 std::string Err;
156
157protected: // Can only create subclasses.
158 const char *TokStart = nullptr;
159 bool SkipSpace = true;
160 bool AllowAtInIdentifier;
161 bool IsAtStartOfStatement = true;
162 AsmCommentConsumer *CommentConsumer = nullptr;
163
164 bool AltMacroMode;
165 MCAsmLexer();
166
167 virtual AsmToken LexToken() = 0;
168
169 void SetError(SMLoc errLoc, const std::string &err) {
170 ErrLoc = errLoc;
171 Err = err;
172 }
173
174public:
175 MCAsmLexer(const MCAsmLexer &) = delete;
176 MCAsmLexer &operator=(const MCAsmLexer &) = delete;
177 virtual ~MCAsmLexer();
178
179 bool IsaAltMacroMode() {
180 return AltMacroMode;
181 }
182
183 void SetAltMacroMode(bool AltMacroSet) {
184 AltMacroMode = AltMacroSet;
185 }
186
187 /// Consume the next token from the input stream and return it.
188 ///
189 /// The lexer will continuosly return the end-of-file token once the end of
190 /// the main input file has been reached.
191 const AsmToken &Lex() {
192 assert(!CurTok.empty())(static_cast <bool> (!CurTok.empty()) ? void (0) : __assert_fail
("!CurTok.empty()", "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/MC/MCParser/MCAsmLexer.h"
, 192, __extension__ __PRETTY_FUNCTION__))
;
193 // Mark if we parsing out a EndOfStatement.
194 IsAtStartOfStatement = CurTok.front().getKind() == AsmToken::EndOfStatement;
195 CurTok.erase(CurTok.begin());
196 // LexToken may generate multiple tokens via UnLex but will always return
197 // the first one. Place returned value at head of CurTok vector.
198 if (CurTok.empty()) {
199 AsmToken T = LexToken();
200 CurTok.insert(CurTok.begin(), T);
201 }
202 return CurTok.front();
203 }
204
205 void UnLex(AsmToken const &Token) {
206 IsAtStartOfStatement = false;
207 CurTok.insert(CurTok.begin(), Token);
208 }
209
210 bool isAtStartOfStatement() { return IsAtStartOfStatement; }
211
212 virtual StringRef LexUntilEndOfStatement() = 0;
213
214 /// Get the current source location.
215 SMLoc getLoc() const;
216
217 /// Get the current (last) lexed token.
218 const AsmToken &getTok() const {
219 return CurTok[0];
220 }
221
222 /// Look ahead at the next token to be lexed.
223 const AsmToken peekTok(bool ShouldSkipSpace = true) {
224 AsmToken Tok;
225
226 MutableArrayRef<AsmToken> Buf(Tok);
227 size_t ReadCount = peekTokens(Buf, ShouldSkipSpace);
228
229 assert(ReadCount == 1)(static_cast <bool> (ReadCount == 1) ? void (0) : __assert_fail
("ReadCount == 1", "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/MC/MCParser/MCAsmLexer.h"
, 229, __extension__ __PRETTY_FUNCTION__))
;
230 (void)ReadCount;
231
232 return Tok;
233 }
234
235 /// Look ahead an arbitrary number of tokens.
236 virtual size_t peekTokens(MutableArrayRef<AsmToken> Buf,
237 bool ShouldSkipSpace = true) = 0;
238
239 /// Get the current error location
240 SMLoc getErrLoc() {
241 return ErrLoc;
242 }
243
244 /// Get the current error string
245 const std::string &getErr() {
246 return Err;
247 }
248
249 /// Get the kind of current token.
250 AsmToken::TokenKind getKind() const { return getTok().getKind(); }
251
252 /// Check if the current token has kind \p K.
253 bool is(AsmToken::TokenKind K) const { return getTok().is(K); }
254
255 /// Check if the current token has kind \p K.
256 bool isNot(AsmToken::TokenKind K) const { return getTok().isNot(K); }
12
Calling 'MCAsmLexer::getTok'
13
Returning from 'MCAsmLexer::getTok'
14
Calling 'AsmToken::isNot'
16
Returning from 'AsmToken::isNot'
257
258 /// Set whether spaces should be ignored by the lexer
259 void setSkipSpace(bool val) { SkipSpace = val; }
260
261 bool getAllowAtInIdentifier() { return AllowAtInIdentifier; }
262 void setAllowAtInIdentifier(bool v) { AllowAtInIdentifier = v; }
263
264 void setCommentConsumer(AsmCommentConsumer *CommentConsumer) {
265 this->CommentConsumer = CommentConsumer;
266 }
267};
268
269} // end namespace llvm
270
271#endif // LLVM_MC_MCPARSER_MCASMLEXER_H

/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/ADT/Twine.h

1//===- Twine.h - Fast Temporary String Concatenation ------------*- C++ -*-===//
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#ifndef LLVM_ADT_TWINE_H
11#define LLVM_ADT_TWINE_H
12
13#include "llvm/ADT/SmallVector.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/Support/ErrorHandling.h"
16#include <cassert>
17#include <cstdint>
18#include <string>
19
20namespace llvm {
21
22 class formatv_object_base;
23 class raw_ostream;
24
25 /// Twine - A lightweight data structure for efficiently representing the
26 /// concatenation of temporary values as strings.
27 ///
28 /// A Twine is a kind of rope, it represents a concatenated string using a
29 /// binary-tree, where the string is the preorder of the nodes. Since the
30 /// Twine can be efficiently rendered into a buffer when its result is used,
31 /// it avoids the cost of generating temporary values for intermediate string
32 /// results -- particularly in cases when the Twine result is never
33 /// required. By explicitly tracking the type of leaf nodes, we can also avoid
34 /// the creation of temporary strings for conversions operations (such as
35 /// appending an integer to a string).
36 ///
37 /// A Twine is not intended for use directly and should not be stored, its
38 /// implementation relies on the ability to store pointers to temporary stack
39 /// objects which may be deallocated at the end of a statement. Twines should
40 /// only be used accepted as const references in arguments, when an API wishes
41 /// to accept possibly-concatenated strings.
42 ///
43 /// Twines support a special 'null' value, which always concatenates to form
44 /// itself, and renders as an empty string. This can be returned from APIs to
45 /// effectively nullify any concatenations performed on the result.
46 ///
47 /// \b Implementation
48 ///
49 /// Given the nature of a Twine, it is not possible for the Twine's
50 /// concatenation method to construct interior nodes; the result must be
51 /// represented inside the returned value. For this reason a Twine object
52 /// actually holds two values, the left- and right-hand sides of a
53 /// concatenation. We also have nullary Twine objects, which are effectively
54 /// sentinel values that represent empty strings.
55 ///
56 /// Thus, a Twine can effectively have zero, one, or two children. The \see
57 /// isNullary(), \see isUnary(), and \see isBinary() predicates exist for
58 /// testing the number of children.
59 ///
60 /// We maintain a number of invariants on Twine objects (FIXME: Why):
61 /// - Nullary twines are always represented with their Kind on the left-hand
62 /// side, and the Empty kind on the right-hand side.
63 /// - Unary twines are always represented with the value on the left-hand
64 /// side, and the Empty kind on the right-hand side.
65 /// - If a Twine has another Twine as a child, that child should always be
66 /// binary (otherwise it could have been folded into the parent).
67 ///
68 /// These invariants are check by \see isValid().
69 ///
70 /// \b Efficiency Considerations
71 ///
72 /// The Twine is designed to yield efficient and small code for common
73 /// situations. For this reason, the concat() method is inlined so that
74 /// concatenations of leaf nodes can be optimized into stores directly into a
75 /// single stack allocated object.
76 ///
77 /// In practice, not all compilers can be trusted to optimize concat() fully,
78 /// so we provide two additional methods (and accompanying operator+
79 /// overloads) to guarantee that particularly important cases (cstring plus
80 /// StringRef) codegen as desired.
81 class Twine {
82 /// NodeKind - Represent the type of an argument.
83 enum NodeKind : unsigned char {
84 /// An empty string; the result of concatenating anything with it is also
85 /// empty.
86 NullKind,
87
88 /// The empty string.
89 EmptyKind,
90
91 /// A pointer to a Twine instance.
92 TwineKind,
93
94 /// A pointer to a C string instance.
95 CStringKind,
96
97 /// A pointer to an std::string instance.
98 StdStringKind,
99
100 /// A pointer to a StringRef instance.
101 StringRefKind,
102
103 /// A pointer to a SmallString instance.
104 SmallStringKind,
105
106 /// A pointer to a formatv_object_base instance.
107 FormatvObjectKind,
108
109 /// A char value, to render as a character.
110 CharKind,
111
112 /// An unsigned int value, to render as an unsigned decimal integer.
113 DecUIKind,
114
115 /// An int value, to render as a signed decimal integer.
116 DecIKind,
117
118 /// A pointer to an unsigned long value, to render as an unsigned decimal
119 /// integer.
120 DecULKind,
121
122 /// A pointer to a long value, to render as a signed decimal integer.
123 DecLKind,
124
125 /// A pointer to an unsigned long long value, to render as an unsigned
126 /// decimal integer.
127 DecULLKind,
128
129 /// A pointer to a long long value, to render as a signed decimal integer.
130 DecLLKind,
131
132 /// A pointer to a uint64_t value, to render as an unsigned hexadecimal
133 /// integer.
134 UHexKind
135 };
136
137 union Child
138 {
139 const Twine *twine;
140 const char *cString;
141 const std::string *stdString;
142 const StringRef *stringRef;
143 const SmallVectorImpl<char> *smallString;
144 const formatv_object_base *formatvObject;
145 char character;
146 unsigned int decUI;
147 int decI;
148 const unsigned long *decUL;
149 const long *decL;
150 const unsigned long long *decULL;
151 const long long *decLL;
152 const uint64_t *uHex;
153 };
154
155 /// LHS - The prefix in the concatenation, which may be uninitialized for
156 /// Null or Empty kinds.
157 Child LHS;
158
159 /// RHS - The suffix in the concatenation, which may be uninitialized for
160 /// Null or Empty kinds.
161 Child RHS;
162
163 /// LHSKind - The NodeKind of the left hand side, \see getLHSKind().
164 NodeKind LHSKind = EmptyKind;
165
166 /// RHSKind - The NodeKind of the right hand side, \see getRHSKind().
167 NodeKind RHSKind = EmptyKind;
168
169 /// Construct a nullary twine; the kind must be NullKind or EmptyKind.
170 explicit Twine(NodeKind Kind) : LHSKind(Kind) {
171 assert(isNullary() && "Invalid kind!")(static_cast <bool> (isNullary() && "Invalid kind!"
) ? void (0) : __assert_fail ("isNullary() && \"Invalid kind!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/ADT/Twine.h"
, 171, __extension__ __PRETTY_FUNCTION__))
;
172 }
173
174 /// Construct a binary twine.
175 explicit Twine(const Twine &LHS, const Twine &RHS)
176 : LHSKind(TwineKind), RHSKind(TwineKind) {
177 this->LHS.twine = &LHS;
178 this->RHS.twine = &RHS;
179 assert(isValid() && "Invalid twine!")(static_cast <bool> (isValid() && "Invalid twine!"
) ? void (0) : __assert_fail ("isValid() && \"Invalid twine!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/ADT/Twine.h"
, 179, __extension__ __PRETTY_FUNCTION__))
;
180 }
181
182 /// Construct a twine from explicit values.
183 explicit Twine(Child LHS, NodeKind LHSKind, Child RHS, NodeKind RHSKind)
184 : LHS(LHS), RHS(RHS), LHSKind(LHSKind), RHSKind(RHSKind) {
185 assert(isValid() && "Invalid twine!")(static_cast <bool> (isValid() && "Invalid twine!"
) ? void (0) : __assert_fail ("isValid() && \"Invalid twine!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/ADT/Twine.h"
, 185, __extension__ __PRETTY_FUNCTION__))
;
186 }
187
188 /// Check for the null twine.
189 bool isNull() const {
190 return getLHSKind() == NullKind;
191 }
192
193 /// Check for the empty twine.
194 bool isEmpty() const {
195 return getLHSKind() == EmptyKind;
196 }
197
198 /// Check if this is a nullary twine (null or empty).
199 bool isNullary() const {
200 return isNull() || isEmpty();
201 }
202
203 /// Check if this is a unary twine.
204 bool isUnary() const {
205 return getRHSKind() == EmptyKind && !isNullary();
206 }
207
208 /// Check if this is a binary twine.
209 bool isBinary() const {
210 return getLHSKind() != NullKind && getRHSKind() != EmptyKind;
211 }
212
213 /// Check if this is a valid twine (satisfying the invariants on
214 /// order and number of arguments).
215 bool isValid() const {
216 // Nullary twines always have Empty on the RHS.
217 if (isNullary() && getRHSKind() != EmptyKind)
218 return false;
219
220 // Null should never appear on the RHS.
221 if (getRHSKind() == NullKind)
222 return false;
223
224 // The RHS cannot be non-empty if the LHS is empty.
225 if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind)
226 return false;
227
228 // A twine child should always be binary.
229 if (getLHSKind() == TwineKind &&
230 !LHS.twine->isBinary())
231 return false;
232 if (getRHSKind() == TwineKind &&
233 !RHS.twine->isBinary())
234 return false;
235
236 return true;
237 }
238
239 /// Get the NodeKind of the left-hand side.
240 NodeKind getLHSKind() const { return LHSKind; }
241
242 /// Get the NodeKind of the right-hand side.
243 NodeKind getRHSKind() const { return RHSKind; }
244
245 /// Print one child from a twine.
246 void printOneChild(raw_ostream &OS, Child Ptr, NodeKind Kind) const;
247
248 /// Print the representation of one child from a twine.
249 void printOneChildRepr(raw_ostream &OS, Child Ptr,
250 NodeKind Kind) const;
251
252 public:
253 /// @name Constructors
254 /// @{
255
256 /// Construct from an empty string.
257 /*implicit*/ Twine() {
258 assert(isValid() && "Invalid twine!")(static_cast <bool> (isValid() && "Invalid twine!"
) ? void (0) : __assert_fail ("isValid() && \"Invalid twine!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/ADT/Twine.h"
, 258, __extension__ __PRETTY_FUNCTION__))
;
259 }
260
261 Twine(const Twine &) = default;
262
263 /// Construct from a C string.
264 ///
265 /// We take care here to optimize "" into the empty twine -- this will be
266 /// optimized out for string constants. This allows Twine arguments have
267 /// default "" values, without introducing unnecessary string constants.
268 /*implicit*/ Twine(const char *Str) {
20
Calling implicit default constructor for 'Child'
21
Returning from default constructor for 'Child'
22
Calling implicit default constructor for 'Child'
23
Returning from default constructor for 'Child'
269 if (Str[0] != '\0') {
24
Taking true branch
270 LHS.cString = Str;
271 LHSKind = CStringKind;
272 } else
273 LHSKind = EmptyKind;
274
275 assert(isValid() && "Invalid twine!")(static_cast <bool> (isValid() && "Invalid twine!"
) ? void (0) : __assert_fail ("isValid() && \"Invalid twine!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/ADT/Twine.h"
, 275, __extension__ __PRETTY_FUNCTION__))
;
25
Within the expansion of the macro 'assert':
a
Assuming the condition is true
276 }
277
278 /// Construct from an std::string.
279 /*implicit*/ Twine(const std::string &Str) : LHSKind(StdStringKind) {
280 LHS.stdString = &Str;
281 assert(isValid() && "Invalid twine!")(static_cast <bool> (isValid() && "Invalid twine!"
) ? void (0) : __assert_fail ("isValid() && \"Invalid twine!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/ADT/Twine.h"
, 281, __extension__ __PRETTY_FUNCTION__))
;
282 }
283
284 /// Construct from a StringRef.
285 /*implicit*/ Twine(const StringRef &Str) : LHSKind(StringRefKind) {
286 LHS.stringRef = &Str;
287 assert(isValid() && "Invalid twine!")(static_cast <bool> (isValid() && "Invalid twine!"
) ? void (0) : __assert_fail ("isValid() && \"Invalid twine!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/ADT/Twine.h"
, 287, __extension__ __PRETTY_FUNCTION__))
;
288 }
289
290 /// Construct from a SmallString.
291 /*implicit*/ Twine(const SmallVectorImpl<char> &Str)
292 : LHSKind(SmallStringKind) {
293 LHS.smallString = &Str;
294 assert(isValid() && "Invalid twine!")(static_cast <bool> (isValid() && "Invalid twine!"
) ? void (0) : __assert_fail ("isValid() && \"Invalid twine!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/ADT/Twine.h"
, 294, __extension__ __PRETTY_FUNCTION__))
;
295 }
296
297 /// Construct from a formatv_object_base.
298 /*implicit*/ Twine(const formatv_object_base &Fmt)
299 : LHSKind(FormatvObjectKind) {
300 LHS.formatvObject = &Fmt;
301 assert(isValid() && "Invalid twine!")(static_cast <bool> (isValid() && "Invalid twine!"
) ? void (0) : __assert_fail ("isValid() && \"Invalid twine!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/ADT/Twine.h"
, 301, __extension__ __PRETTY_FUNCTION__))
;
302 }
303
304 /// Construct from a char.
305 explicit Twine(char Val) : LHSKind(CharKind) {
306 LHS.character = Val;
307 }
308
309 /// Construct from a signed char.
310 explicit Twine(signed char Val) : LHSKind(CharKind) {
311 LHS.character = static_cast<char>(Val);
312 }
313
314 /// Construct from an unsigned char.
315 explicit Twine(unsigned char Val) : LHSKind(CharKind) {
316 LHS.character = static_cast<char>(Val);
317 }
318
319 /// Construct a twine to print \p Val as an unsigned decimal integer.
320 explicit Twine(unsigned Val) : LHSKind(DecUIKind) {
321 LHS.decUI = Val;
322 }
323
324 /// Construct a twine to print \p Val as a signed decimal integer.
325 explicit Twine(int Val) : LHSKind(DecIKind) {
326 LHS.decI = Val;
327 }
328
329 /// Construct a twine to print \p Val as an unsigned decimal integer.
330 explicit Twine(const unsigned long &Val) : LHSKind(DecULKind) {
331 LHS.decUL = &Val;
332 }
333
334 /// Construct a twine to print \p Val as a signed decimal integer.
335 explicit Twine(const long &Val) : LHSKind(DecLKind) {
336 LHS.decL = &Val;
337 }
338
339 /// Construct a twine to print \p Val as an unsigned decimal integer.
340 explicit Twine(const unsigned long long &Val) : LHSKind(DecULLKind) {
341 LHS.decULL = &Val;
342 }
343
344 /// Construct a twine to print \p Val as a signed decimal integer.
345 explicit Twine(const long long &Val) : LHSKind(DecLLKind) {
346 LHS.decLL = &Val;
347 }
348
349 // FIXME: Unfortunately, to make sure this is as efficient as possible we
350 // need extra binary constructors from particular types. We can't rely on
351 // the compiler to be smart enough to fold operator+()/concat() down to the
352 // right thing. Yet.
353
354 /// Construct as the concatenation of a C string and a StringRef.
355 /*implicit*/ Twine(const char *LHS, const StringRef &RHS)
356 : LHSKind(CStringKind), RHSKind(StringRefKind) {
357 this->LHS.cString = LHS;
358 this->RHS.stringRef = &RHS;
359 assert(isValid() && "Invalid twine!")(static_cast <bool> (isValid() && "Invalid twine!"
) ? void (0) : __assert_fail ("isValid() && \"Invalid twine!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/ADT/Twine.h"
, 359, __extension__ __PRETTY_FUNCTION__))
;
360 }
361
362 /// Construct as the concatenation of a StringRef and a C string.
363 /*implicit*/ Twine(const StringRef &LHS, const char *RHS)
364 : LHSKind(StringRefKind), RHSKind(CStringKind) {
365 this->LHS.stringRef = &LHS;
366 this->RHS.cString = RHS;
367 assert(isValid() && "Invalid twine!")(static_cast <bool> (isValid() && "Invalid twine!"
) ? void (0) : __assert_fail ("isValid() && \"Invalid twine!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/ADT/Twine.h"
, 367, __extension__ __PRETTY_FUNCTION__))
;
368 }
369
370 /// Since the intended use of twines is as temporary objects, assignments
371 /// when concatenating might cause undefined behavior or stack corruptions
372 Twine &operator=(const Twine &) = delete;
373
374 /// Create a 'null' string, which is an empty string that always
375 /// concatenates to form another empty string.
376 static Twine createNull() {
377 return Twine(NullKind);
378 }
379
380 /// @}
381 /// @name Numeric Conversions
382 /// @{
383
384 // Construct a twine to print \p Val as an unsigned hexadecimal integer.
385 static Twine utohexstr(const uint64_t &Val) {
386 Child LHS, RHS;
387 LHS.uHex = &Val;
388 RHS.twine = nullptr;
389 return Twine(LHS, UHexKind, RHS, EmptyKind);
390 }
391
392 /// @}
393 /// @name Predicate Operations
394 /// @{
395
396 /// Check if this twine is trivially empty; a false return value does not
397 /// necessarily mean the twine is empty.
398 bool isTriviallyEmpty() const {
399 return isNullary();
400 }
401
402 /// Return true if this twine can be dynamically accessed as a single
403 /// StringRef value with getSingleStringRef().
404 bool isSingleStringRef() const {
405 if (getRHSKind() != EmptyKind) return false;
406
407 switch (getLHSKind()) {
408 case EmptyKind:
409 case CStringKind:
410 case StdStringKind:
411 case StringRefKind:
412 case SmallStringKind:
413 return true;
414 default:
415 return false;
416 }
417 }
418
419 /// @}
420 /// @name String Operations
421 /// @{
422
423 Twine concat(const Twine &Suffix) const;
424
425 /// @}
426 /// @name Output & Conversion.
427 /// @{
428
429 /// Return the twine contents as a std::string.
430 std::string str() const;
431
432 /// Append the concatenated string into the given SmallString or SmallVector.
433 void toVector(SmallVectorImpl<char> &Out) const;
434
435 /// This returns the twine as a single StringRef. This method is only valid
436 /// if isSingleStringRef() is true.
437 StringRef getSingleStringRef() const {
438 assert(isSingleStringRef() &&"This cannot be had as a single stringref!")(static_cast <bool> (isSingleStringRef() &&"This cannot be had as a single stringref!"
) ? void (0) : __assert_fail ("isSingleStringRef() &&\"This cannot be had as a single stringref!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/ADT/Twine.h"
, 438, __extension__ __PRETTY_FUNCTION__))
;
439 switch (getLHSKind()) {
440 default: llvm_unreachable("Out of sync with isSingleStringRef")::llvm::llvm_unreachable_internal("Out of sync with isSingleStringRef"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/ADT/Twine.h"
, 440)
;
441 case EmptyKind: return StringRef();
442 case CStringKind: return StringRef(LHS.cString);
443 case StdStringKind: return StringRef(*LHS.stdString);
444 case StringRefKind: return *LHS.stringRef;
445 case SmallStringKind:
446 return StringRef(LHS.smallString->data(), LHS.smallString->size());
447 }
448 }
449
450 /// This returns the twine as a single StringRef if it can be
451 /// represented as such. Otherwise the twine is written into the given
452 /// SmallVector and a StringRef to the SmallVector's data is returned.
453 StringRef toStringRef(SmallVectorImpl<char> &Out) const {
454 if (isSingleStringRef())
455 return getSingleStringRef();
456 toVector(Out);
457 return StringRef(Out.data(), Out.size());
458 }
459
460 /// This returns the twine as a single null terminated StringRef if it
461 /// can be represented as such. Otherwise the twine is written into the
462 /// given SmallVector and a StringRef to the SmallVector's data is returned.
463 ///
464 /// The returned StringRef's size does not include the null terminator.
465 StringRef toNullTerminatedStringRef(SmallVectorImpl<char> &Out) const;
466
467 /// Write the concatenated string represented by this twine to the
468 /// stream \p OS.
469 void print(raw_ostream &OS) const;
470
471 /// Dump the concatenated string represented by this twine to stderr.
472 void dump() const;
473
474 /// Write the representation of this twine to the stream \p OS.
475 void printRepr(raw_ostream &OS) const;
476
477 /// Dump the representation of this twine to stderr.
478 void dumpRepr() const;
479
480 /// @}
481 };
482
483 /// @name Twine Inline Implementations
484 /// @{
485
486 inline Twine Twine::concat(const Twine &Suffix) const {
487 // Concatenation with null is null.
488 if (isNull() || Suffix.isNull())
489 return Twine(NullKind);
490
491 // Concatenation with empty yields the other side.
492 if (isEmpty())
493 return Suffix;
494 if (Suffix.isEmpty())
495 return *this;
496
497 // Otherwise we need to create a new node, taking care to fold in unary
498 // twines.
499 Child NewLHS, NewRHS;
500 NewLHS.twine = this;
501 NewRHS.twine = &Suffix;
502 NodeKind NewLHSKind = TwineKind, NewRHSKind = TwineKind;
503 if (isUnary()) {
504 NewLHS = LHS;
505 NewLHSKind = getLHSKind();
506 }
507 if (Suffix.isUnary()) {
508 NewRHS = Suffix.LHS;
509 NewRHSKind = Suffix.getLHSKind();
510 }
511
512 return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind);
513 }
514
515 inline Twine operator+(const Twine &LHS, const Twine &RHS) {
516 return LHS.concat(RHS);
517 }
518
519 /// Additional overload to guarantee simplified codegen; this is equivalent to
520 /// concat().
521
522 inline Twine operator+(const char *LHS, const StringRef &RHS) {
523 return Twine(LHS, RHS);
524 }
525
526 /// Additional overload to guarantee simplified codegen; this is equivalent to
527 /// concat().
528
529 inline Twine operator+(const StringRef &LHS, const char *RHS) {
530 return Twine(LHS, RHS);
531 }
532
533 inline raw_ostream &operator<<(raw_ostream &OS, const Twine &RHS) {
534 RHS.print(OS);
535 return OS;
536 }
537
538 /// @}
539
540} // end namespace llvm
541
542#endif // LLVM_ADT_TWINE_H