Bug Summary

File:lib/MC/MCParser/DarwinAsmParser.cpp
Warning:line 788, column 3
Use of memory after it is freed

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name DarwinAsmParser.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/lib/MC/MCParser -I /build/llvm-toolchain-snapshot-7~svn329677/lib/MC/MCParser -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/lib/MC/MCParser -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/lib/MC/MCParser/DarwinAsmParser.cpp

/build/llvm-toolchain-snapshot-7~svn329677/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))
1
Taking false branch
762 return TokError("unexpected token in '.secure_log_unique' directive");
763
764 if (getContext().getSecureLogUsed())
2
Assuming the condition is false
3
Taking false branch
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)
4
Assuming 'SecureLogFile' is non-null
5
Taking false branch
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) {
6
Assuming 'OS' is null
7
Taking true branch
776 std::error_code EC;
777 auto NewOS = llvm::make_unique<raw_fd_ostream>(
8
Calling 'make_unique'
10
Returned allocated memory
778 StringRef(SecureLogFile), EC, sys::fs::F_Append | sys::fs::F_Text);
779 if (EC)
11
Taking false branch
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));
12
Calling '~unique_ptr'
17
Returning from '~unique_ptr'
784 }
785
786 // Write the message.
787 unsigned CurBuf = getSourceManager().FindBufferContainingLoc(IDLoc);
788 *OS << getSourceManager().getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
18
Use of memory after it is freed
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))
1006 return TokError("invalid OS major version number, integer expected");
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-7~svn329677/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-7~svn329677/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))
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)
1115 return Error(PlatformLoc, "unknown platform name");
1116
1117 if (getLexer().isNot(AsmToken::Comma))
1118 return TokError("version number required, comma expected");
1119 Lex();
1120
1121 unsigned Major;
1122 unsigned Minor;
1123 unsigned Update;
1124 if (parseVersion(&Major, &Minor, &Update))
1125 return true;
1126
1127 if (parseToken(AsmToken::EndOfStatement))
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);
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-7~svn329677/include/llvm/ADT/STLExtras.h

1//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- 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// This file contains some templates that are useful if you are working with the
11// STL at all.
12//
13// No library is required when using these functions.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_ADT_STLEXTRAS_H
18#define LLVM_ADT_STLEXTRAS_H
19
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/iterator.h"
23#include "llvm/ADT/iterator_range.h"
24#include "llvm/Support/ErrorHandling.h"
25#include <algorithm>
26#include <cassert>
27#include <cstddef>
28#include <cstdint>
29#include <cstdlib>
30#include <functional>
31#include <initializer_list>
32#include <iterator>
33#include <limits>
34#include <memory>
35#include <tuple>
36#include <type_traits>
37#include <utility>
38
39#ifdef EXPENSIVE_CHECKS
40#include <random> // for std::mt19937
41#endif
42
43namespace llvm {
44
45// Only used by compiler if both template types are the same. Useful when
46// using SFINAE to test for the existence of member functions.
47template <typename T, T> struct SameType;
48
49namespace detail {
50
51template <typename RangeT>
52using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
53
54template <typename RangeT>
55using ValueOfRange = typename std::remove_reference<decltype(
56 *std::begin(std::declval<RangeT &>()))>::type;
57
58} // end namespace detail
59
60//===----------------------------------------------------------------------===//
61// Extra additions to <functional>
62//===----------------------------------------------------------------------===//
63
64template <class Ty> struct identity {
65 using argument_type = Ty;
66
67 Ty &operator()(Ty &self) const {
68 return self;
69 }
70 const Ty &operator()(const Ty &self) const {
71 return self;
72 }
73};
74
75template <class Ty> struct less_ptr {
76 bool operator()(const Ty* left, const Ty* right) const {
77 return *left < *right;
78 }
79};
80
81template <class Ty> struct greater_ptr {
82 bool operator()(const Ty* left, const Ty* right) const {
83 return *right < *left;
84 }
85};
86
87/// An efficient, type-erasing, non-owning reference to a callable. This is
88/// intended for use as the type of a function parameter that is not used
89/// after the function in question returns.
90///
91/// This class does not own the callable, so it is not in general safe to store
92/// a function_ref.
93template<typename Fn> class function_ref;
94
95template<typename Ret, typename ...Params>
96class function_ref<Ret(Params...)> {
97 Ret (*callback)(intptr_t callable, Params ...params) = nullptr;
98 intptr_t callable;
99
100 template<typename Callable>
101 static Ret callback_fn(intptr_t callable, Params ...params) {
102 return (*reinterpret_cast<Callable*>(callable))(
103 std::forward<Params>(params)...);
104 }
105
106public:
107 function_ref() = default;
108 function_ref(std::nullptr_t) {}
109
110 template <typename Callable>
111 function_ref(Callable &&callable,
112 typename std::enable_if<
113 !std::is_same<typename std::remove_reference<Callable>::type,
114 function_ref>::value>::type * = nullptr)
115 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
116 callable(reinterpret_cast<intptr_t>(&callable)) {}
117
118 Ret operator()(Params ...params) const {
119 return callback(callable, std::forward<Params>(params)...);
120 }
121
122 operator bool() const { return callback; }
123};
124
125// deleter - Very very very simple method that is used to invoke operator
126// delete on something. It is used like this:
127//
128// for_each(V.begin(), B.end(), deleter<Interval>);
129template <class T>
130inline void deleter(T *Ptr) {
131 delete Ptr;
132}
133
134//===----------------------------------------------------------------------===//
135// Extra additions to <iterator>
136//===----------------------------------------------------------------------===//
137
138namespace adl_detail {
139
140using std::begin;
141
142template <typename ContainerTy>
143auto adl_begin(ContainerTy &&container)
144 -> decltype(begin(std::forward<ContainerTy>(container))) {
145 return begin(std::forward<ContainerTy>(container));
146}
147
148using std::end;
149
150template <typename ContainerTy>
151auto adl_end(ContainerTy &&container)
152 -> decltype(end(std::forward<ContainerTy>(container))) {
153 return end(std::forward<ContainerTy>(container));
154}
155
156using std::swap;
157
158template <typename T>
159void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(),
160 std::declval<T>()))) {
161 swap(std::forward<T>(lhs), std::forward<T>(rhs));
162}
163
164} // end namespace adl_detail
165
166template <typename ContainerTy>
167auto adl_begin(ContainerTy &&container)
168 -> decltype(adl_detail::adl_begin(std::forward<ContainerTy>(container))) {
169 return adl_detail::adl_begin(std::forward<ContainerTy>(container));
170}
171
172template <typename ContainerTy>
173auto adl_end(ContainerTy &&container)
174 -> decltype(adl_detail::adl_end(std::forward<ContainerTy>(container))) {
175 return adl_detail::adl_end(std::forward<ContainerTy>(container));
176}
177
178template <typename T>
179void adl_swap(T &&lhs, T &&rhs) noexcept(
180 noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) {
181 adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs));
182}
183
184// mapped_iterator - This is a simple iterator adapter that causes a function to
185// be applied whenever operator* is invoked on the iterator.
186
187template <typename ItTy, typename FuncTy,
188 typename FuncReturnTy =
189 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
190class mapped_iterator
191 : public iterator_adaptor_base<
192 mapped_iterator<ItTy, FuncTy>, ItTy,
193 typename std::iterator_traits<ItTy>::iterator_category,
194 typename std::remove_reference<FuncReturnTy>::type> {
195public:
196 mapped_iterator(ItTy U, FuncTy F)
197 : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
198
199 ItTy getCurrent() { return this->I; }
200
201 FuncReturnTy operator*() { return F(*this->I); }
202
203private:
204 FuncTy F;
205};
206
207// map_iterator - Provide a convenient way to create mapped_iterators, just like
208// make_pair is useful for creating pairs...
209template <class ItTy, class FuncTy>
210inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) {
211 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
212}
213
214/// Helper to determine if type T has a member called rbegin().
215template <typename Ty> class has_rbegin_impl {
216 using yes = char[1];
217 using no = char[2];
218
219 template <typename Inner>
220 static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
221
222 template <typename>
223 static no& test(...);
224
225public:
226 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
227};
228
229/// Metafunction to determine if T& or T has a member called rbegin().
230template <typename Ty>
231struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
232};
233
234// Returns an iterator_range over the given container which iterates in reverse.
235// Note that the container must have rbegin()/rend() methods for this to work.
236template <typename ContainerTy>
237auto reverse(ContainerTy &&C,
238 typename std::enable_if<has_rbegin<ContainerTy>::value>::type * =
239 nullptr) -> decltype(make_range(C.rbegin(), C.rend())) {
240 return make_range(C.rbegin(), C.rend());
241}
242
243// Returns a std::reverse_iterator wrapped around the given iterator.
244template <typename IteratorTy>
245std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
246 return std::reverse_iterator<IteratorTy>(It);
247}
248
249// Returns an iterator_range over the given container which iterates in reverse.
250// Note that the container must have begin()/end() methods which return
251// bidirectional iterators for this to work.
252template <typename ContainerTy>
253auto reverse(
254 ContainerTy &&C,
255 typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr)
256 -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)),
257 llvm::make_reverse_iterator(std::begin(C)))) {
258 return make_range(llvm::make_reverse_iterator(std::end(C)),
259 llvm::make_reverse_iterator(std::begin(C)));
260}
261
262/// An iterator adaptor that filters the elements of given inner iterators.
263///
264/// The predicate parameter should be a callable object that accepts the wrapped
265/// iterator's reference type and returns a bool. When incrementing or
266/// decrementing the iterator, it will call the predicate on each element and
267/// skip any where it returns false.
268///
269/// \code
270/// int A[] = { 1, 2, 3, 4 };
271/// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
272/// // R contains { 1, 3 }.
273/// \endcode
274template <typename WrappedIteratorT, typename PredicateT>
275class filter_iterator
276 : public iterator_adaptor_base<
277 filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
278 typename std::common_type<
279 std::forward_iterator_tag,
280 typename std::iterator_traits<
281 WrappedIteratorT>::iterator_category>::type> {
282 using BaseT = iterator_adaptor_base<
283 filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
284 typename std::common_type<
285 std::forward_iterator_tag,
286 typename std::iterator_traits<WrappedIteratorT>::iterator_category>::
287 type>;
288
289 struct PayloadType {
290 WrappedIteratorT End;
291 PredicateT Pred;
292 };
293
294 Optional<PayloadType> Payload;
295
296 void findNextValid() {
297 assert(Payload && "Payload should be engaged when findNextValid is called")(static_cast <bool> (Payload && "Payload should be engaged when findNextValid is called"
) ? void (0) : __assert_fail ("Payload && \"Payload should be engaged when findNextValid is called\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 297, __extension__ __PRETTY_FUNCTION__))
;
298 while (this->I != Payload->End && !Payload->Pred(*this->I))
299 BaseT::operator++();
300 }
301
302 // Construct the begin iterator. The begin iterator requires to know where end
303 // is, so that it can properly stop when it hits end.
304 filter_iterator(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
305 : BaseT(std::move(Begin)),
306 Payload(PayloadType{std::move(End), std::move(Pred)}) {
307 findNextValid();
308 }
309
310 // Construct the end iterator. It's not incrementable, so Payload doesn't
311 // have to be engaged.
312 filter_iterator(WrappedIteratorT End) : BaseT(End) {}
313
314public:
315 using BaseT::operator++;
316
317 filter_iterator &operator++() {
318 BaseT::operator++();
319 findNextValid();
320 return *this;
321 }
322
323 template <typename RT, typename PT>
324 friend iterator_range<filter_iterator<detail::IterOfRange<RT>, PT>>
325 make_filter_range(RT &&, PT);
326};
327
328/// Convenience function that takes a range of elements and a predicate,
329/// and return a new filter_iterator range.
330///
331/// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
332/// lifetime of that temporary is not kept by the returned range object, and the
333/// temporary is going to be dropped on the floor after the make_iterator_range
334/// full expression that contains this function call.
335template <typename RangeT, typename PredicateT>
336iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
337make_filter_range(RangeT &&Range, PredicateT Pred) {
338 using FilterIteratorT =
339 filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
340 return make_range(FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
341 std::end(std::forward<RangeT>(Range)),
342 std::move(Pred)),
343 FilterIteratorT(std::end(std::forward<RangeT>(Range))));
344}
345
346// forward declarations required by zip_shortest/zip_first
347template <typename R, typename UnaryPredicate>
348bool all_of(R &&range, UnaryPredicate P);
349
350template <size_t... I> struct index_sequence;
351
352template <class... Ts> struct index_sequence_for;
353
354namespace detail {
355
356using std::declval;
357
358// We have to alias this since inlining the actual type at the usage site
359// in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
360template<typename... Iters> struct ZipTupleType {
361 using type = std::tuple<decltype(*declval<Iters>())...>;
362};
363
364template <typename ZipType, typename... Iters>
365using zip_traits = iterator_facade_base<
366 ZipType, typename std::common_type<std::bidirectional_iterator_tag,
367 typename std::iterator_traits<
368 Iters>::iterator_category...>::type,
369 // ^ TODO: Implement random access methods.
370 typename ZipTupleType<Iters...>::type,
371 typename std::iterator_traits<typename std::tuple_element<
372 0, std::tuple<Iters...>>::type>::difference_type,
373 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
374 // inner iterators have the same difference_type. It would fail if, for
375 // instance, the second field's difference_type were non-numeric while the
376 // first is.
377 typename ZipTupleType<Iters...>::type *,
378 typename ZipTupleType<Iters...>::type>;
379
380template <typename ZipType, typename... Iters>
381struct zip_common : public zip_traits<ZipType, Iters...> {
382 using Base = zip_traits<ZipType, Iters...>;
383 using value_type = typename Base::value_type;
384
385 std::tuple<Iters...> iterators;
386
387protected:
388 template <size_t... Ns> value_type deref(index_sequence<Ns...>) const {
389 return value_type(*std::get<Ns>(iterators)...);
390 }
391
392 template <size_t... Ns>
393 decltype(iterators) tup_inc(index_sequence<Ns...>) const {
394 return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
395 }
396
397 template <size_t... Ns>
398 decltype(iterators) tup_dec(index_sequence<Ns...>) const {
399 return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
400 }
401
402public:
403 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
404
405 value_type operator*() { return deref(index_sequence_for<Iters...>{}); }
406
407 const value_type operator*() const {
408 return deref(index_sequence_for<Iters...>{});
409 }
410
411 ZipType &operator++() {
412 iterators = tup_inc(index_sequence_for<Iters...>{});
413 return *reinterpret_cast<ZipType *>(this);
414 }
415
416 ZipType &operator--() {
417 static_assert(Base::IsBidirectional,
418 "All inner iterators must be at least bidirectional.");
419 iterators = tup_dec(index_sequence_for<Iters...>{});
420 return *reinterpret_cast<ZipType *>(this);
421 }
422};
423
424template <typename... Iters>
425struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
426 using Base = zip_common<zip_first<Iters...>, Iters...>;
427
428 bool operator==(const zip_first<Iters...> &other) const {
429 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
430 }
431
432 zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
433};
434
435template <typename... Iters>
436class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
437 template <size_t... Ns>
438 bool test(const zip_shortest<Iters...> &other, index_sequence<Ns...>) const {
439 return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
440 std::get<Ns>(other.iterators)...},
441 identity<bool>{});
442 }
443
444public:
445 using Base = zip_common<zip_shortest<Iters...>, Iters...>;
446
447 zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
448
449 bool operator==(const zip_shortest<Iters...> &other) const {
450 return !test(other, index_sequence_for<Iters...>{});
451 }
452};
453
454template <template <typename...> class ItType, typename... Args> class zippy {
455public:
456 using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
457 using iterator_category = typename iterator::iterator_category;
458 using value_type = typename iterator::value_type;
459 using difference_type = typename iterator::difference_type;
460 using pointer = typename iterator::pointer;
461 using reference = typename iterator::reference;
462
463private:
464 std::tuple<Args...> ts;
465
466 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const {
467 return iterator(std::begin(std::get<Ns>(ts))...);
468 }
469 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const {
470 return iterator(std::end(std::get<Ns>(ts))...);
471 }
472
473public:
474 zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
475
476 iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); }
477 iterator end() const { return end_impl(index_sequence_for<Args...>{}); }
478};
479
480} // end namespace detail
481
482/// zip iterator for two or more iteratable types.
483template <typename T, typename U, typename... Args>
484detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
485 Args &&... args) {
486 return detail::zippy<detail::zip_shortest, T, U, Args...>(
487 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
488}
489
490/// zip iterator that, for the sake of efficiency, assumes the first iteratee to
491/// be the shortest.
492template <typename T, typename U, typename... Args>
493detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
494 Args &&... args) {
495 return detail::zippy<detail::zip_first, T, U, Args...>(
496 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
497}
498
499/// Iterator wrapper that concatenates sequences together.
500///
501/// This can concatenate different iterators, even with different types, into
502/// a single iterator provided the value types of all the concatenated
503/// iterators expose `reference` and `pointer` types that can be converted to
504/// `ValueT &` and `ValueT *` respectively. It doesn't support more
505/// interesting/customized pointer or reference types.
506///
507/// Currently this only supports forward or higher iterator categories as
508/// inputs and always exposes a forward iterator interface.
509template <typename ValueT, typename... IterTs>
510class concat_iterator
511 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
512 std::forward_iterator_tag, ValueT> {
513 using BaseT = typename concat_iterator::iterator_facade_base;
514
515 /// We store both the current and end iterators for each concatenated
516 /// sequence in a tuple of pairs.
517 ///
518 /// Note that something like iterator_range seems nice at first here, but the
519 /// range properties are of little benefit and end up getting in the way
520 /// because we need to do mutation on the current iterators.
521 std::tuple<std::pair<IterTs, IterTs>...> IterPairs;
522
523 /// Attempts to increment a specific iterator.
524 ///
525 /// Returns true if it was able to increment the iterator. Returns false if
526 /// the iterator is already at the end iterator.
527 template <size_t Index> bool incrementHelper() {
528 auto &IterPair = std::get<Index>(IterPairs);
529 if (IterPair.first == IterPair.second)
530 return false;
531
532 ++IterPair.first;
533 return true;
534 }
535
536 /// Increments the first non-end iterator.
537 ///
538 /// It is an error to call this with all iterators at the end.
539 template <size_t... Ns> void increment(index_sequence<Ns...>) {
540 // Build a sequence of functions to increment each iterator if possible.
541 bool (concat_iterator::*IncrementHelperFns[])() = {
542 &concat_iterator::incrementHelper<Ns>...};
543
544 // Loop over them, and stop as soon as we succeed at incrementing one.
545 for (auto &IncrementHelperFn : IncrementHelperFns)
546 if ((this->*IncrementHelperFn)())
547 return;
548
549 llvm_unreachable("Attempted to increment an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to increment an end concat iterator!"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 549)
;
550 }
551
552 /// Returns null if the specified iterator is at the end. Otherwise,
553 /// dereferences the iterator and returns the address of the resulting
554 /// reference.
555 template <size_t Index> ValueT *getHelper() const {
556 auto &IterPair = std::get<Index>(IterPairs);
557 if (IterPair.first == IterPair.second)
558 return nullptr;
559
560 return &*IterPair.first;
561 }
562
563 /// Finds the first non-end iterator, dereferences, and returns the resulting
564 /// reference.
565 ///
566 /// It is an error to call this with all iterators at the end.
567 template <size_t... Ns> ValueT &get(index_sequence<Ns...>) const {
568 // Build a sequence of functions to get from iterator if possible.
569 ValueT *(concat_iterator::*GetHelperFns[])() const = {
570 &concat_iterator::getHelper<Ns>...};
571
572 // Loop over them, and return the first result we find.
573 for (auto &GetHelperFn : GetHelperFns)
574 if (ValueT *P = (this->*GetHelperFn)())
575 return *P;
576
577 llvm_unreachable("Attempted to get a pointer from an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to get a pointer from an end concat iterator!"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 577)
;
578 }
579
580public:
581 /// Constructs an iterator from a squence of ranges.
582 ///
583 /// We need the full range to know how to switch between each of the
584 /// iterators.
585 template <typename... RangeTs>
586 explicit concat_iterator(RangeTs &&... Ranges)
587 : IterPairs({std::begin(Ranges), std::end(Ranges)}...) {}
588
589 using BaseT::operator++;
590
591 concat_iterator &operator++() {
592 increment(index_sequence_for<IterTs...>());
593 return *this;
594 }
595
596 ValueT &operator*() const { return get(index_sequence_for<IterTs...>()); }
597
598 bool operator==(const concat_iterator &RHS) const {
599 return IterPairs == RHS.IterPairs;
600 }
601};
602
603namespace detail {
604
605/// Helper to store a sequence of ranges being concatenated and access them.
606///
607/// This is designed to facilitate providing actual storage when temporaries
608/// are passed into the constructor such that we can use it as part of range
609/// based for loops.
610template <typename ValueT, typename... RangeTs> class concat_range {
611public:
612 using iterator =
613 concat_iterator<ValueT,
614 decltype(std::begin(std::declval<RangeTs &>()))...>;
615
616private:
617 std::tuple<RangeTs...> Ranges;
618
619 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) {
620 return iterator(std::get<Ns>(Ranges)...);
621 }
622 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) {
623 return iterator(make_range(std::end(std::get<Ns>(Ranges)),
624 std::end(std::get<Ns>(Ranges)))...);
625 }
626
627public:
628 concat_range(RangeTs &&... Ranges)
629 : Ranges(std::forward<RangeTs>(Ranges)...) {}
630
631 iterator begin() { return begin_impl(index_sequence_for<RangeTs...>{}); }
632 iterator end() { return end_impl(index_sequence_for<RangeTs...>{}); }
633};
634
635} // end namespace detail
636
637/// Concatenated range across two or more ranges.
638///
639/// The desired value type must be explicitly specified.
640template <typename ValueT, typename... RangeTs>
641detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
642 static_assert(sizeof...(RangeTs) > 1,
643 "Need more than one range to concatenate!");
644 return detail::concat_range<ValueT, RangeTs...>(
645 std::forward<RangeTs>(Ranges)...);
646}
647
648//===----------------------------------------------------------------------===//
649// Extra additions to <utility>
650//===----------------------------------------------------------------------===//
651
652/// \brief Function object to check whether the first component of a std::pair
653/// compares less than the first component of another std::pair.
654struct less_first {
655 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
656 return lhs.first < rhs.first;
657 }
658};
659
660/// \brief Function object to check whether the second component of a std::pair
661/// compares less than the second component of another std::pair.
662struct less_second {
663 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
664 return lhs.second < rhs.second;
665 }
666};
667
668// A subset of N3658. More stuff can be added as-needed.
669
670/// \brief Represents a compile-time sequence of integers.
671template <class T, T... I> struct integer_sequence {
672 using value_type = T;
673
674 static constexpr size_t size() { return sizeof...(I); }
675};
676
677/// \brief Alias for the common case of a sequence of size_ts.
678template <size_t... I>
679struct index_sequence : integer_sequence<std::size_t, I...> {};
680
681template <std::size_t N, std::size_t... I>
682struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
683template <std::size_t... I>
684struct build_index_impl<0, I...> : index_sequence<I...> {};
685
686/// \brief Creates a compile-time integer sequence for a parameter pack.
687template <class... Ts>
688struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
689
690/// Utility type to build an inheritance chain that makes it easy to rank
691/// overload candidates.
692template <int N> struct rank : rank<N - 1> {};
693template <> struct rank<0> {};
694
695/// \brief traits class for checking whether type T is one of any of the given
696/// types in the variadic list.
697template <typename T, typename... Ts> struct is_one_of {
698 static const bool value = false;
699};
700
701template <typename T, typename U, typename... Ts>
702struct is_one_of<T, U, Ts...> {
703 static const bool value =
704 std::is_same<T, U>::value || is_one_of<T, Ts...>::value;
705};
706
707/// \brief traits class for checking whether type T is a base class for all
708/// the given types in the variadic list.
709template <typename T, typename... Ts> struct are_base_of {
710 static const bool value = true;
711};
712
713template <typename T, typename U, typename... Ts>
714struct are_base_of<T, U, Ts...> {
715 static const bool value =
716 std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value;
717};
718
719//===----------------------------------------------------------------------===//
720// Extra additions for arrays
721//===----------------------------------------------------------------------===//
722
723/// Find the length of an array.
724template <class T, std::size_t N>
725constexpr inline size_t array_lengthof(T (&)[N]) {
726 return N;
727}
728
729/// Adapt std::less<T> for array_pod_sort.
730template<typename T>
731inline int array_pod_sort_comparator(const void *P1, const void *P2) {
732 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
733 *reinterpret_cast<const T*>(P2)))
734 return -1;
735 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
736 *reinterpret_cast<const T*>(P1)))
737 return 1;
738 return 0;
739}
740
741/// get_array_pod_sort_comparator - This is an internal helper function used to
742/// get type deduction of T right.
743template<typename T>
744inline int (*get_array_pod_sort_comparator(const T &))
745 (const void*, const void*) {
746 return array_pod_sort_comparator<T>;
747}
748
749/// array_pod_sort - This sorts an array with the specified start and end
750/// extent. This is just like std::sort, except that it calls qsort instead of
751/// using an inlined template. qsort is slightly slower than std::sort, but
752/// most sorts are not performance critical in LLVM and std::sort has to be
753/// template instantiated for each type, leading to significant measured code
754/// bloat. This function should generally be used instead of std::sort where
755/// possible.
756///
757/// This function assumes that you have simple POD-like types that can be
758/// compared with std::less and can be moved with memcpy. If this isn't true,
759/// you should use std::sort.
760///
761/// NOTE: If qsort_r were portable, we could allow a custom comparator and
762/// default to std::less.
763template<class IteratorTy>
764inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
765 // Don't inefficiently call qsort with one element or trigger undefined
766 // behavior with an empty sequence.
767 auto NElts = End - Start;
768 if (NElts <= 1) return;
769#ifdef EXPENSIVE_CHECKS
770 std::mt19937 Generator(std::random_device{}());
771 std::shuffle(Start, End, Generator);
772#endif
773 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
774}
775
776template <class IteratorTy>
777inline void array_pod_sort(
778 IteratorTy Start, IteratorTy End,
779 int (*Compare)(
780 const typename std::iterator_traits<IteratorTy>::value_type *,
781 const typename std::iterator_traits<IteratorTy>::value_type *)) {
782 // Don't inefficiently call qsort with one element or trigger undefined
783 // behavior with an empty sequence.
784 auto NElts = End - Start;
785 if (NElts <= 1) return;
786#ifdef EXPENSIVE_CHECKS
787 std::mt19937 Generator(std::random_device{}());
788 std::shuffle(Start, End, Generator);
789#endif
790 qsort(&*Start, NElts, sizeof(*Start),
791 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
792}
793
794// Provide wrappers to std::sort which shuffle the elements before sorting
795// to help uncover non-deterministic behavior (PR35135).
796template <typename IteratorTy>
797inline void sort(IteratorTy Start, IteratorTy End) {
798#ifdef EXPENSIVE_CHECKS
799 std::mt19937 Generator(std::random_device{}());
800 std::shuffle(Start, End, Generator);
801#endif
802 std::sort(Start, End);
803}
804
805template <typename IteratorTy, typename Compare>
806inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
807#ifdef EXPENSIVE_CHECKS
808 std::mt19937 Generator(std::random_device{}());
809 std::shuffle(Start, End, Generator);
810#endif
811 std::sort(Start, End, Comp);
812}
813
814//===----------------------------------------------------------------------===//
815// Extra additions to <algorithm>
816//===----------------------------------------------------------------------===//
817
818/// For a container of pointers, deletes the pointers and then clears the
819/// container.
820template<typename Container>
821void DeleteContainerPointers(Container &C) {
822 for (auto V : C)
823 delete V;
824 C.clear();
825}
826
827/// In a container of pairs (usually a map) whose second element is a pointer,
828/// deletes the second elements and then clears the container.
829template<typename Container>
830void DeleteContainerSeconds(Container &C) {
831 for (auto &V : C)
832 delete V.second;
833 C.clear();
834}
835
836/// Provide wrappers to std::for_each which take ranges instead of having to
837/// pass begin/end explicitly.
838template <typename R, typename UnaryPredicate>
839UnaryPredicate for_each(R &&Range, UnaryPredicate P) {
840 return std::for_each(adl_begin(Range), adl_end(Range), P);
841}
842
843/// Provide wrappers to std::all_of which take ranges instead of having to pass
844/// begin/end explicitly.
845template <typename R, typename UnaryPredicate>
846bool all_of(R &&Range, UnaryPredicate P) {
847 return std::all_of(adl_begin(Range), adl_end(Range), P);
848}
849
850/// Provide wrappers to std::any_of which take ranges instead of having to pass
851/// begin/end explicitly.
852template <typename R, typename UnaryPredicate>
853bool any_of(R &&Range, UnaryPredicate P) {
854 return std::any_of(adl_begin(Range), adl_end(Range), P);
855}
856
857/// Provide wrappers to std::none_of which take ranges instead of having to pass
858/// begin/end explicitly.
859template <typename R, typename UnaryPredicate>
860bool none_of(R &&Range, UnaryPredicate P) {
861 return std::none_of(adl_begin(Range), adl_end(Range), P);
862}
863
864/// Provide wrappers to std::find which take ranges instead of having to pass
865/// begin/end explicitly.
866template <typename R, typename T>
867auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range)) {
868 return std::find(adl_begin(Range), adl_end(Range), Val);
869}
870
871/// Provide wrappers to std::find_if which take ranges instead of having to pass
872/// begin/end explicitly.
873template <typename R, typename UnaryPredicate>
874auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
875 return std::find_if(adl_begin(Range), adl_end(Range), P);
876}
877
878template <typename R, typename UnaryPredicate>
879auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
880 return std::find_if_not(adl_begin(Range), adl_end(Range), P);
881}
882
883/// Provide wrappers to std::remove_if which take ranges instead of having to
884/// pass begin/end explicitly.
885template <typename R, typename UnaryPredicate>
886auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
887 return std::remove_if(adl_begin(Range), adl_end(Range), P);
888}
889
890/// Provide wrappers to std::copy_if which take ranges instead of having to
891/// pass begin/end explicitly.
892template <typename R, typename OutputIt, typename UnaryPredicate>
893OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
894 return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
895}
896
897template <typename R, typename OutputIt>
898OutputIt copy(R &&Range, OutputIt Out) {
899 return std::copy(adl_begin(Range), adl_end(Range), Out);
900}
901
902/// Wrapper function around std::find to detect if an element exists
903/// in a container.
904template <typename R, typename E>
905bool is_contained(R &&Range, const E &Element) {
906 return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range);
907}
908
909/// Wrapper function around std::count to count the number of times an element
910/// \p Element occurs in the given range \p Range.
911template <typename R, typename E>
912auto count(R &&Range, const E &Element) ->
913 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
914 return std::count(adl_begin(Range), adl_end(Range), Element);
915}
916
917/// Wrapper function around std::count_if to count the number of times an
918/// element satisfying a given predicate occurs in a range.
919template <typename R, typename UnaryPredicate>
920auto count_if(R &&Range, UnaryPredicate P) ->
921 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
922 return std::count_if(adl_begin(Range), adl_end(Range), P);
923}
924
925/// Wrapper function around std::transform to apply a function to a range and
926/// store the result elsewhere.
927template <typename R, typename OutputIt, typename UnaryPredicate>
928OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) {
929 return std::transform(adl_begin(Range), adl_end(Range), d_first, P);
930}
931
932/// Provide wrappers to std::partition which take ranges instead of having to
933/// pass begin/end explicitly.
934template <typename R, typename UnaryPredicate>
935auto partition(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
936 return std::partition(adl_begin(Range), adl_end(Range), P);
937}
938
939/// Provide wrappers to std::lower_bound which take ranges instead of having to
940/// pass begin/end explicitly.
941template <typename R, typename ForwardIt>
942auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range)) {
943 return std::lower_bound(adl_begin(Range), adl_end(Range), I);
944}
945
946/// \brief Given a range of type R, iterate the entire range and return a
947/// SmallVector with elements of the vector. This is useful, for example,
948/// when you want to iterate a range and then sort the results.
949template <unsigned Size, typename R>
950SmallVector<typename std::remove_const<detail::ValueOfRange<R>>::type, Size>
951to_vector(R &&Range) {
952 return {adl_begin(Range), adl_end(Range)};
953}
954
955/// Provide a container algorithm similar to C++ Library Fundamentals v2's
956/// `erase_if` which is equivalent to:
957///
958/// C.erase(remove_if(C, pred), C.end());
959///
960/// This version works for any container with an erase method call accepting
961/// two iterators.
962template <typename Container, typename UnaryPredicate>
963void erase_if(Container &C, UnaryPredicate P) {
964 C.erase(remove_if(C, P), C.end());
965}
966
967//===----------------------------------------------------------------------===//
968// Extra additions to <memory>
969//===----------------------------------------------------------------------===//
970
971// Implement make_unique according to N3656.
972
973/// \brief Constructs a `new T()` with the given args and returns a
974/// `unique_ptr<T>` which owns the object.
975///
976/// Example:
977///
978/// auto p = make_unique<int>();
979/// auto p = make_unique<std::tuple<int, int>>(0, 1);
980template <class T, class... Args>
981typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
982make_unique(Args &&... args) {
983 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
9
Memory is allocated
984}
985
986/// \brief Constructs a `new T[n]` with the given args and returns a
987/// `unique_ptr<T[]>` which owns the object.
988///
989/// \param n size of the new array.
990///
991/// Example:
992///
993/// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
994template <class T>
995typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
996 std::unique_ptr<T>>::type
997make_unique(size_t n) {
998 return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
999}
1000
1001/// This function isn't used and is only here to provide better compile errors.
1002template <class T, class... Args>
1003typename std::enable_if<std::extent<T>::value != 0>::type
1004make_unique(Args &&...) = delete;
1005
1006struct FreeDeleter {
1007 void operator()(void* v) {
1008 ::free(v);
1009 }
1010};
1011
1012template<typename First, typename Second>
1013struct pair_hash {
1014 size_t operator()(const std::pair<First, Second> &P) const {
1015 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
1016 }
1017};
1018
1019/// A functor like C++14's std::less<void> in its absence.
1020struct less {
1021 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1022 return std::forward<A>(a) < std::forward<B>(b);
1023 }
1024};
1025
1026/// A functor like C++14's std::equal<void> in its absence.
1027struct equal {
1028 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1029 return std::forward<A>(a) == std::forward<B>(b);
1030 }
1031};
1032
1033/// Binary functor that adapts to any other binary functor after dereferencing
1034/// operands.
1035template <typename T> struct deref {
1036 T func;
1037
1038 // Could be further improved to cope with non-derivable functors and
1039 // non-binary functors (should be a variadic template member function
1040 // operator()).
1041 template <typename A, typename B>
1042 auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
1043 assert(lhs)(static_cast <bool> (lhs) ? void (0) : __assert_fail ("lhs"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 1043, __extension__ __PRETTY_FUNCTION__))
;
1044 assert(rhs)(static_cast <bool> (rhs) ? void (0) : __assert_fail ("rhs"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 1044, __extension__ __PRETTY_FUNCTION__))
;
1045 return func(*lhs, *rhs);
1046 }
1047};
1048
1049namespace detail {
1050
1051template <typename R> class enumerator_iter;
1052
1053template <typename R> struct result_pair {
1054 friend class enumerator_iter<R>;
1055
1056 result_pair() = default;
1057 result_pair(std::size_t Index, IterOfRange<R> Iter)
1058 : Index(Index), Iter(Iter) {}
1059
1060 result_pair<R> &operator=(const result_pair<R> &Other) {
1061 Index = Other.Index;
1062 Iter = Other.Iter;
1063 return *this;
1064 }
1065
1066 std::size_t index() const { return Index; }
1067 const ValueOfRange<R> &value() const { return *Iter; }
1068 ValueOfRange<R> &value() { return *Iter; }
1069
1070private:
1071 std::size_t Index = std::numeric_limits<std::size_t>::max();
1072 IterOfRange<R> Iter;
1073};
1074
1075template <typename R>
1076class enumerator_iter
1077 : public iterator_facade_base<
1078 enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>,
1079 typename std::iterator_traits<IterOfRange<R>>::difference_type,
1080 typename std::iterator_traits<IterOfRange<R>>::pointer,
1081 typename std::iterator_traits<IterOfRange<R>>::reference> {
1082 using result_type = result_pair<R>;
1083
1084public:
1085 explicit enumerator_iter(IterOfRange<R> EndIter)
1086 : Result(std::numeric_limits<size_t>::max(), EndIter) {}
1087
1088 enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
1089 : Result(Index, Iter) {}
1090
1091 result_type &operator*() { return Result; }
1092 const result_type &operator*() const { return Result; }
1093
1094 enumerator_iter<R> &operator++() {
1095 assert(Result.Index != std::numeric_limits<size_t>::max())(static_cast <bool> (Result.Index != std::numeric_limits
<size_t>::max()) ? void (0) : __assert_fail ("Result.Index != std::numeric_limits<size_t>::max()"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 1095, __extension__ __PRETTY_FUNCTION__))
;
1096 ++Result.Iter;
1097 ++Result.Index;
1098 return *this;
1099 }
1100
1101 bool operator==(const enumerator_iter<R> &RHS) const {
1102 // Don't compare indices here, only iterators. It's possible for an end
1103 // iterator to have different indices depending on whether it was created
1104 // by calling std::end() versus incrementing a valid iterator.
1105 return Result.Iter == RHS.Result.Iter;
1106 }
1107
1108 enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) {
1109 Result = Other.Result;
1110 return *this;
1111 }
1112
1113private:
1114 result_type Result;
1115};
1116
1117template <typename R> class enumerator {
1118public:
1119 explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1120
1121 enumerator_iter<R> begin() {
1122 return enumerator_iter<R>(0, std::begin(TheRange));
1123 }
1124
1125 enumerator_iter<R> end() {
1126 return enumerator_iter<R>(std::end(TheRange));
1127 }
1128
1129private:
1130 R TheRange;
1131};
1132
1133} // end namespace detail
1134
1135/// Given an input range, returns a new range whose values are are pair (A,B)
1136/// such that A is the 0-based index of the item in the sequence, and B is
1137/// the value from the original sequence. Example:
1138///
1139/// std::vector<char> Items = {'A', 'B', 'C', 'D'};
1140/// for (auto X : enumerate(Items)) {
1141/// printf("Item %d - %c\n", X.index(), X.value());
1142/// }
1143///
1144/// Output:
1145/// Item 0 - A
1146/// Item 1 - B
1147/// Item 2 - C
1148/// Item 3 - D
1149///
1150template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
1151 return detail::enumerator<R>(std::forward<R>(TheRange));
1152}
1153
1154namespace detail {
1155
1156template <typename F, typename Tuple, std::size_t... I>
1157auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>)
1158 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) {
1159 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
1160}
1161
1162} // end namespace detail
1163
1164/// Given an input tuple (a1, a2, ..., an), pass the arguments of the
1165/// tuple variadically to f as if by calling f(a1, a2, ..., an) and
1166/// return the result.
1167template <typename F, typename Tuple>
1168auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(
1169 std::forward<F>(f), std::forward<Tuple>(t),
1170 build_index_impl<
1171 std::tuple_size<typename std::decay<Tuple>::type>::value>{})) {
1172 using Indices = build_index_impl<
1173 std::tuple_size<typename std::decay<Tuple>::type>::value>;
1174
1175 return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
1176 Indices{});
1177}
1178
1179} // end namespace llvm
1180
1181#endif // LLVM_ADT_STLEXTRAS_H

/usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/bits/unique_ptr.h

1// unique_ptr implementation -*- C++ -*-
2
3// Copyright (C) 2008-2017 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file bits/unique_ptr.h
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{memory}
28 */
29
30#ifndef _UNIQUE_PTR_H1
31#define _UNIQUE_PTR_H1 1
32
33#include <bits/c++config.h>
34#include <debug/assertions.h>
35#include <type_traits>
36#include <utility>
37#include <tuple>
38#include <bits/stl_function.h>
39#include <bits/functional_hash.h>
40
41namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
42{
43_GLIBCXX_BEGIN_NAMESPACE_VERSION
44
45 /**
46 * @addtogroup pointer_abstractions
47 * @{
48 */
49
50#if _GLIBCXX_USE_DEPRECATED1
51 template<typename> class auto_ptr;
52#endif
53
54 /// Primary template of default_delete, used by unique_ptr
55 template<typename _Tp>
56 struct default_delete
57 {
58 /// Default constructor
59 constexpr default_delete() noexcept = default;
60
61 /** @brief Converting constructor.
62 *
63 * Allows conversion from a deleter for arrays of another type, @p _Up,
64 * only if @p _Up* is convertible to @p _Tp*.
65 */
66 template<typename _Up, typename = typename
67 enable_if<is_convertible<_Up*, _Tp*>::value>::type>
68 default_delete(const default_delete<_Up>&) noexcept { }
69
70 /// Calls @c delete @p __ptr
71 void
72 operator()(_Tp* __ptr) const
73 {
74 static_assert(!is_void<_Tp>::value,
75 "can't delete pointer to incomplete type");
76 static_assert(sizeof(_Tp)>0,
77 "can't delete pointer to incomplete type");
78 delete __ptr;
15
Memory is released
79 }
80 };
81
82 // _GLIBCXX_RESOLVE_LIB_DEFECTS
83 // DR 740 - omit specialization for array objects with a compile time length
84 /// Specialization for arrays, default_delete.
85 template<typename _Tp>
86 struct default_delete<_Tp[]>
87 {
88 public:
89 /// Default constructor
90 constexpr default_delete() noexcept = default;
91
92 /** @brief Converting constructor.
93 *
94 * Allows conversion from a deleter for arrays of another type, such as
95 * a const-qualified version of @p _Tp.
96 *
97 * Conversions from types derived from @c _Tp are not allowed because
98 * it is unsafe to @c delete[] an array of derived types through a
99 * pointer to the base type.
100 */
101 template<typename _Up, typename = typename
102 enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type>
103 default_delete(const default_delete<_Up[]>&) noexcept { }
104
105 /// Calls @c delete[] @p __ptr
106 template<typename _Up>
107 typename enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type
108 operator()(_Up* __ptr) const
109 {
110 static_assert(sizeof(_Tp)>0,
111 "can't delete pointer to incomplete type");
112 delete [] __ptr;
113 }
114 };
115
116 template <typename _Tp, typename _Dp>
117 class __uniq_ptr_impl
118 {
119 template <typename _Up, typename _Ep, typename = void>
120 struct _Ptr
121 {
122 using type = _Up*;
123 };
124
125 template <typename _Up, typename _Ep>
126 struct
127 _Ptr<_Up, _Ep, __void_t<typename remove_reference<_Ep>::type::pointer>>
128 {
129 using type = typename remove_reference<_Ep>::type::pointer;
130 };
131
132 public:
133 using _DeleterConstraint = enable_if<
134 __and_<__not_<is_pointer<_Dp>>,
135 is_default_constructible<_Dp>>::value>;
136
137 using pointer = typename _Ptr<_Tp, _Dp>::type;
138
139 __uniq_ptr_impl() = default;
140 __uniq_ptr_impl(pointer __p) : _M_t() { _M_ptr() = __p; }
141
142 template<typename _Del>
143 __uniq_ptr_impl(pointer __p, _Del&& __d)
144 : _M_t(__p, std::forward<_Del>(__d)) { }
145
146 pointer& _M_ptr() { return std::get<0>(_M_t); }
147 pointer _M_ptr() const { return std::get<0>(_M_t); }
148 _Dp& _M_deleter() { return std::get<1>(_M_t); }
149 const _Dp& _M_deleter() const { return std::get<1>(_M_t); }
150
151 private:
152 tuple<pointer, _Dp> _M_t;
153 };
154
155 /// 20.7.1.2 unique_ptr for single objects.
156 template <typename _Tp, typename _Dp = default_delete<_Tp>>
157 class unique_ptr
158 {
159 template <class _Up>
160 using _DeleterConstraint =
161 typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type;
162
163 __uniq_ptr_impl<_Tp, _Dp> _M_t;
164
165 public:
166 using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer;
167 using element_type = _Tp;
168 using deleter_type = _Dp;
169
170 // helper template for detecting a safe conversion from another
171 // unique_ptr
172 template<typename _Up, typename _Ep>
173 using __safe_conversion_up = __and_<
174 is_convertible<typename unique_ptr<_Up, _Ep>::pointer, pointer>,
175 __not_<is_array<_Up>>,
176 __or_<__and_<is_reference<deleter_type>,
177 is_same<deleter_type, _Ep>>,
178 __and_<__not_<is_reference<deleter_type>>,
179 is_convertible<_Ep, deleter_type>>
180 >
181 >;
182
183 // Constructors.
184
185 /// Default constructor, creates a unique_ptr that owns nothing.
186 template <typename _Up = _Dp,
187 typename = _DeleterConstraint<_Up>>
188 constexpr unique_ptr() noexcept
189 : _M_t()
190 { }
191
192 /** Takes ownership of a pointer.
193 *
194 * @param __p A pointer to an object of @c element_type
195 *
196 * The deleter will be value-initialized.
197 */
198 template <typename _Up = _Dp,
199 typename = _DeleterConstraint<_Up>>
200 explicit
201 unique_ptr(pointer __p) noexcept
202 : _M_t(__p)
203 { }
204
205 /** Takes ownership of a pointer.
206 *
207 * @param __p A pointer to an object of @c element_type
208 * @param __d A reference to a deleter.
209 *
210 * The deleter will be initialized with @p __d
211 */
212 unique_ptr(pointer __p,
213 typename conditional<is_reference<deleter_type>::value,
214 deleter_type, const deleter_type&>::type __d) noexcept
215 : _M_t(__p, __d) { }
216
217 /** Takes ownership of a pointer.
218 *
219 * @param __p A pointer to an object of @c element_type
220 * @param __d An rvalue reference to a deleter.
221 *
222 * The deleter will be initialized with @p std::move(__d)
223 */
224 unique_ptr(pointer __p,
225 typename remove_reference<deleter_type>::type&& __d) noexcept
226 : _M_t(std::move(__p), std::move(__d))
227 { static_assert(!std::is_reference<deleter_type>::value,
228 "rvalue deleter bound to reference"); }
229
230 /// Creates a unique_ptr that owns nothing.
231 template <typename _Up = _Dp,
232 typename = _DeleterConstraint<_Up>>
233 constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() { }
234
235 // Move constructors.
236
237 /// Move constructor.
238 unique_ptr(unique_ptr&& __u) noexcept
239 : _M_t(__u.release(), std::forward<deleter_type>(__u.get_deleter())) { }
240
241 /** @brief Converting constructor from another type
242 *
243 * Requires that the pointer owned by @p __u is convertible to the
244 * type of pointer owned by this object, @p __u does not own an array,
245 * and @p __u has a compatible deleter type.
246 */
247 template<typename _Up, typename _Ep, typename = _Require<
248 __safe_conversion_up<_Up, _Ep>,
249 typename conditional<is_reference<_Dp>::value,
250 is_same<_Ep, _Dp>,
251 is_convertible<_Ep, _Dp>>::type>>
252 unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept
253 : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter()))
254 { }
255
256#if _GLIBCXX_USE_DEPRECATED1
257 /// Converting constructor from @c auto_ptr
258 template<typename _Up, typename = _Require<
259 is_convertible<_Up*, _Tp*>, is_same<_Dp, default_delete<_Tp>>>>
260 unique_ptr(auto_ptr<_Up>&& __u) noexcept;
261#endif
262
263 /// Destructor, invokes the deleter if the stored pointer is not null.
264 ~unique_ptr() noexcept
265 {
266 auto& __ptr = _M_t._M_ptr();
267 if (__ptr != nullptr)
13
Taking true branch
268 get_deleter()(__ptr);
14
Calling 'default_delete::operator()'
16
Returning; memory was released via 2nd parameter
269 __ptr = pointer();
270 }
271
272 // Assignment.
273
274 /** @brief Move assignment operator.
275 *
276 * @param __u The object to transfer ownership from.
277 *
278 * Invokes the deleter first if this object owns a pointer.
279 */
280 unique_ptr&
281 operator=(unique_ptr&& __u) noexcept
282 {
283 reset(__u.release());
284 get_deleter() = std::forward<deleter_type>(__u.get_deleter());
285 return *this;
286 }
287
288 /** @brief Assignment from another type.
289 *
290 * @param __u The object to transfer ownership from, which owns a
291 * convertible pointer to a non-array object.
292 *
293 * Invokes the deleter first if this object owns a pointer.
294 */
295 template<typename _Up, typename _Ep>
296 typename enable_if< __and_<
297 __safe_conversion_up<_Up, _Ep>,
298 is_assignable<deleter_type&, _Ep&&>
299 >::value,
300 unique_ptr&>::type
301 operator=(unique_ptr<_Up, _Ep>&& __u) noexcept
302 {
303 reset(__u.release());
304 get_deleter() = std::forward<_Ep>(__u.get_deleter());
305 return *this;
306 }
307
308 /// Reset the %unique_ptr to empty, invoking the deleter if necessary.
309 unique_ptr&
310 operator=(nullptr_t) noexcept
311 {
312 reset();
313 return *this;
314 }
315
316 // Observers.
317
318 /// Dereference the stored pointer.
319 typename add_lvalue_reference<element_type>::type
320 operator*() const
321 {
322 __glibcxx_assert(get() != pointer());
323 return *get();
324 }
325
326 /// Return the stored pointer.
327 pointer
328 operator->() const noexcept
329 {
330 _GLIBCXX_DEBUG_PEDASSERT(get() != pointer());
331 return get();
332 }
333
334 /// Return the stored pointer.
335 pointer
336 get() const noexcept
337 { return _M_t._M_ptr(); }
338
339 /// Return a reference to the stored deleter.
340 deleter_type&
341 get_deleter() noexcept
342 { return _M_t._M_deleter(); }
343
344 /// Return a reference to the stored deleter.
345 const deleter_type&
346 get_deleter() const noexcept
347 { return _M_t._M_deleter(); }
348
349 /// Return @c true if the stored pointer is not null.
350 explicit operator bool() const noexcept
351 { return get() == pointer() ? false : true; }
352
353 // Modifiers.
354
355 /// Release ownership of any stored pointer.
356 pointer
357 release() noexcept
358 {
359 pointer __p = get();
360 _M_t._M_ptr() = pointer();
361 return __p;
362 }
363
364 /** @brief Replace the stored pointer.
365 *
366 * @param __p The new pointer to store.
367 *
368 * The deleter will be invoked if a pointer is already owned.
369 */
370 void
371 reset(pointer __p = pointer()) noexcept
372 {
373 using std::swap;
374 swap(_M_t._M_ptr(), __p);
375 if (__p != pointer())
376 get_deleter()(__p);
377 }
378
379 /// Exchange the pointer and deleter with another object.
380 void
381 swap(unique_ptr& __u) noexcept
382 {
383 using std::swap;
384 swap(_M_t, __u._M_t);
385 }
386
387 // Disable copy from lvalue.
388 unique_ptr(const unique_ptr&) = delete;
389 unique_ptr& operator=(const unique_ptr&) = delete;
390 };
391
392 /// 20.7.1.3 unique_ptr for array objects with a runtime length
393 // [unique.ptr.runtime]
394 // _GLIBCXX_RESOLVE_LIB_DEFECTS
395 // DR 740 - omit specialization for array objects with a compile time length
396 template<typename _Tp, typename _Dp>
397 class unique_ptr<_Tp[], _Dp>
398 {
399 template <typename _Up>
400 using _DeleterConstraint =
401 typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type;
402
403 __uniq_ptr_impl<_Tp, _Dp> _M_t;
404
405 template<typename _Up>
406 using __remove_cv = typename remove_cv<_Up>::type;
407
408 // like is_base_of<_Tp, _Up> but false if unqualified types are the same
409 template<typename _Up>
410 using __is_derived_Tp
411 = __and_< is_base_of<_Tp, _Up>,
412 __not_<is_same<__remove_cv<_Tp>, __remove_cv<_Up>>> >;
413
414 public:
415 using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer;
416 using element_type = _Tp;
417 using deleter_type = _Dp;
418
419 // helper template for detecting a safe conversion from another
420 // unique_ptr
421 template<typename _Up, typename _Ep,
422 typename _Up_up = unique_ptr<_Up, _Ep>,
423 typename _Up_element_type = typename _Up_up::element_type>
424 using __safe_conversion_up = __and_<
425 is_array<_Up>,
426 is_same<pointer, element_type*>,
427 is_same<typename _Up_up::pointer, _Up_element_type*>,
428 is_convertible<_Up_element_type(*)[], element_type(*)[]>,
429 __or_<__and_<is_reference<deleter_type>, is_same<deleter_type, _Ep>>,
430 __and_<__not_<is_reference<deleter_type>>,
431 is_convertible<_Ep, deleter_type>>>
432 >;
433
434 // helper template for detecting a safe conversion from a raw pointer
435 template<typename _Up>
436 using __safe_conversion_raw = __and_<
437 __or_<__or_<is_same<_Up, pointer>,
438 is_same<_Up, nullptr_t>>,
439 __and_<is_pointer<_Up>,
440 is_same<pointer, element_type*>,
441 is_convertible<
442 typename remove_pointer<_Up>::type(*)[],
443 element_type(*)[]>
444 >
445 >
446 >;
447
448 // Constructors.
449
450 /// Default constructor, creates a unique_ptr that owns nothing.
451 template <typename _Up = _Dp,
452 typename = _DeleterConstraint<_Up>>
453 constexpr unique_ptr() noexcept
454 : _M_t()
455 { }
456
457 /** Takes ownership of a pointer.
458 *
459 * @param __p A pointer to an array of a type safely convertible
460 * to an array of @c element_type
461 *
462 * The deleter will be value-initialized.
463 */
464 template<typename _Up,
465 typename _Vp = _Dp,
466 typename = _DeleterConstraint<_Vp>,
467 typename = typename enable_if<
468 __safe_conversion_raw<_Up>::value, bool>::type>
469 explicit
470 unique_ptr(_Up __p) noexcept
471 : _M_t(__p)
472 { }
473
474 /** Takes ownership of a pointer.
475 *
476 * @param __p A pointer to an array of a type safely convertible
477 * to an array of @c element_type
478 * @param __d A reference to a deleter.
479 *
480 * The deleter will be initialized with @p __d
481 */
482 template<typename _Up,
483 typename = typename enable_if<
484 __safe_conversion_raw<_Up>::value, bool>::type>
485 unique_ptr(_Up __p,
486 typename conditional<is_reference<deleter_type>::value,
487 deleter_type, const deleter_type&>::type __d) noexcept
488 : _M_t(__p, __d) { }
489
490 /** Takes ownership of a pointer.
491 *
492 * @param __p A pointer to an array of a type safely convertible
493 * to an array of @c element_type
494 * @param __d A reference to a deleter.
495 *
496 * The deleter will be initialized with @p std::move(__d)
497 */
498 template<typename _Up,
499 typename = typename enable_if<
500 __safe_conversion_raw<_Up>::value, bool>::type>
501 unique_ptr(_Up __p, typename
502 remove_reference<deleter_type>::type&& __d) noexcept
503 : _M_t(std::move(__p), std::move(__d))
504 { static_assert(!is_reference<deleter_type>::value,
505 "rvalue deleter bound to reference"); }
506
507 /// Move constructor.
508 unique_ptr(unique_ptr&& __u) noexcept
509 : _M_t(__u.release(), std::forward<deleter_type>(__u.get_deleter())) { }
510
511 /// Creates a unique_ptr that owns nothing.
512 template <typename _Up = _Dp,
513 typename = _DeleterConstraint<_Up>>
514 constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() { }
515
516 template<typename _Up, typename _Ep,
517 typename = _Require<__safe_conversion_up<_Up, _Ep>>>
518 unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept
519 : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter()))
520 { }
521
522 /// Destructor, invokes the deleter if the stored pointer is not null.
523 ~unique_ptr()
524 {
525 auto& __ptr = _M_t._M_ptr();
526 if (__ptr != nullptr)
527 get_deleter()(__ptr);
528 __ptr = pointer();
529 }
530
531 // Assignment.
532
533 /** @brief Move assignment operator.
534 *
535 * @param __u The object to transfer ownership from.
536 *
537 * Invokes the deleter first if this object owns a pointer.
538 */
539 unique_ptr&
540 operator=(unique_ptr&& __u) noexcept
541 {
542 reset(__u.release());
543 get_deleter() = std::forward<deleter_type>(__u.get_deleter());
544 return *this;
545 }
546
547 /** @brief Assignment from another type.
548 *
549 * @param __u The object to transfer ownership from, which owns a
550 * convertible pointer to an array object.
551 *
552 * Invokes the deleter first if this object owns a pointer.
553 */
554 template<typename _Up, typename _Ep>
555 typename
556 enable_if<__and_<__safe_conversion_up<_Up, _Ep>,
557 is_assignable<deleter_type&, _Ep&&>
558 >::value,
559 unique_ptr&>::type
560 operator=(unique_ptr<_Up, _Ep>&& __u) noexcept
561 {
562 reset(__u.release());
563 get_deleter() = std::forward<_Ep>(__u.get_deleter());
564 return *this;
565 }
566
567 /// Reset the %unique_ptr to empty, invoking the deleter if necessary.
568 unique_ptr&
569 operator=(nullptr_t) noexcept
570 {
571 reset();
572 return *this;
573 }
574
575 // Observers.
576
577 /// Access an element of owned array.
578 typename std::add_lvalue_reference<element_type>::type
579 operator[](size_t __i) const
580 {
581 __glibcxx_assert(get() != pointer());
582 return get()[__i];
583 }
584
585 /// Return the stored pointer.
586 pointer
587 get() const noexcept
588 { return _M_t._M_ptr(); }
589
590 /// Return a reference to the stored deleter.
591 deleter_type&
592 get_deleter() noexcept
593 { return _M_t._M_deleter(); }
594
595 /// Return a reference to the stored deleter.
596 const deleter_type&
597 get_deleter() const noexcept
598 { return _M_t._M_deleter(); }
599
600 /// Return @c true if the stored pointer is not null.
601 explicit operator bool() const noexcept
602 { return get() == pointer() ? false : true; }
603
604 // Modifiers.
605
606 /// Release ownership of any stored pointer.
607 pointer
608 release() noexcept
609 {
610 pointer __p = get();
611 _M_t._M_ptr() = pointer();
612 return __p;
613 }
614
615 /** @brief Replace the stored pointer.
616 *
617 * @param __p The new pointer to store.
618 *
619 * The deleter will be invoked if a pointer is already owned.
620 */
621 template <typename _Up,
622 typename = _Require<
623 __or_<is_same<_Up, pointer>,
624 __and_<is_same<pointer, element_type*>,
625 is_pointer<_Up>,
626 is_convertible<
627 typename remove_pointer<_Up>::type(*)[],
628 element_type(*)[]
629 >
630 >
631 >
632 >>
633 void
634 reset(_Up __p) noexcept
635 {
636 pointer __ptr = __p;
637 using std::swap;
638 swap(_M_t._M_ptr(), __ptr);
639 if (__ptr != nullptr)
640 get_deleter()(__ptr);
641 }
642
643 void reset(nullptr_t = nullptr) noexcept
644 {
645 reset(pointer());
646 }
647
648 /// Exchange the pointer and deleter with another object.
649 void
650 swap(unique_ptr& __u) noexcept
651 {
652 using std::swap;
653 swap(_M_t, __u._M_t);
654 }
655
656 // Disable copy from lvalue.
657 unique_ptr(const unique_ptr&) = delete;
658 unique_ptr& operator=(const unique_ptr&) = delete;
659 };
660
661 template<typename _Tp, typename _Dp>
662 inline
663#if __cplusplus201103L > 201402L || !defined(__STRICT_ANSI__1) // c++1z or gnu++11
664 // Constrained free swap overload, see p0185r1
665 typename enable_if<__is_swappable<_Dp>::value>::type
666#else
667 void
668#endif
669 swap(unique_ptr<_Tp, _Dp>& __x,
670 unique_ptr<_Tp, _Dp>& __y) noexcept
671 { __x.swap(__y); }
672
673#if __cplusplus201103L > 201402L || !defined(__STRICT_ANSI__1) // c++1z or gnu++11
674 template<typename _Tp, typename _Dp>
675 typename enable_if<!__is_swappable<_Dp>::value>::type
676 swap(unique_ptr<_Tp, _Dp>&,
677 unique_ptr<_Tp, _Dp>&) = delete;
678#endif
679
680 template<typename _Tp, typename _Dp,
681 typename _Up, typename _Ep>
682 inline bool
683 operator==(const unique_ptr<_Tp, _Dp>& __x,
684 const unique_ptr<_Up, _Ep>& __y)
685 { return __x.get() == __y.get(); }
686
687 template<typename _Tp, typename _Dp>
688 inline bool
689 operator==(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept
690 { return !__x; }
691
692 template<typename _Tp, typename _Dp>
693 inline bool
694 operator==(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept
695 { return !__x; }
696
697 template<typename _Tp, typename _Dp,
698 typename _Up, typename _Ep>
699 inline bool
700 operator!=(const unique_ptr<_Tp, _Dp>& __x,
701 const unique_ptr<_Up, _Ep>& __y)
702 { return __x.get() != __y.get(); }
703
704 template<typename _Tp, typename _Dp>
705 inline bool
706 operator!=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept
707 { return (bool)__x; }
708
709 template<typename _Tp, typename _Dp>
710 inline bool
711 operator!=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept
712 { return (bool)__x; }
713
714 template<typename _Tp, typename _Dp,
715 typename _Up, typename _Ep>
716 inline bool
717 operator<(const unique_ptr<_Tp, _Dp>& __x,
718 const unique_ptr<_Up, _Ep>& __y)
719 {
720 typedef typename
721 std::common_type<typename unique_ptr<_Tp, _Dp>::pointer,
722 typename unique_ptr<_Up, _Ep>::pointer>::type _CT;
723 return std::less<_CT>()(__x.get(), __y.get());
724 }
725
726 template<typename _Tp, typename _Dp>
727 inline bool
728 operator<(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
729 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(__x.get(),
730 nullptr); }
731
732 template<typename _Tp, typename _Dp>
733 inline bool
734 operator<(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
735 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(nullptr,
736 __x.get()); }
737
738 template<typename _Tp, typename _Dp,
739 typename _Up, typename _Ep>
740 inline bool
741 operator<=(const unique_ptr<_Tp, _Dp>& __x,
742 const unique_ptr<_Up, _Ep>& __y)
743 { return !(__y < __x); }
744
745 template<typename _Tp, typename _Dp>
746 inline bool
747 operator<=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
748 { return !(nullptr < __x); }
749
750 template<typename _Tp, typename _Dp>
751 inline bool
752 operator<=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
753 { return !(__x < nullptr); }
754
755 template<typename _Tp, typename _Dp,
756 typename _Up, typename _Ep>
757 inline bool
758 operator>(const unique_ptr<_Tp, _Dp>& __x,
759 const unique_ptr<_Up, _Ep>& __y)
760 { return (__y < __x); }
761
762 template<typename _Tp, typename _Dp>
763 inline bool
764 operator>(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
765 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(nullptr,
766 __x.get()); }
767
768 template<typename _Tp, typename _Dp>
769 inline bool
770 operator>(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
771 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(__x.get(),
772 nullptr); }
773
774 template<typename _Tp, typename _Dp,
775 typename _Up, typename _Ep>
776 inline bool
777 operator>=(const unique_ptr<_Tp, _Dp>& __x,
778 const unique_ptr<_Up, _Ep>& __y)
779 { return !(__x < __y); }
780
781 template<typename _Tp, typename _Dp>
782 inline bool
783 operator>=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
784 { return !(__x < nullptr); }
785
786 template<typename _Tp, typename _Dp>
787 inline bool
788 operator>=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
789 { return !(nullptr < __x); }
790
791 /// std::hash specialization for unique_ptr.
792 template<typename _Tp, typename _Dp>
793 struct hash<unique_ptr<_Tp, _Dp>>
794 : public __hash_base<size_t, unique_ptr<_Tp, _Dp>>,
795 private __poison_hash<typename unique_ptr<_Tp, _Dp>::pointer>
796 {
797 size_t
798 operator()(const unique_ptr<_Tp, _Dp>& __u) const noexcept
799 {
800 typedef unique_ptr<_Tp, _Dp> _UP;
801 return std::hash<typename _UP::pointer>()(__u.get());
802 }
803 };
804
805#if __cplusplus201103L > 201103L
806
807#define __cpp_lib_make_unique 201304
808
809 template<typename _Tp>
810 struct _MakeUniq
811 { typedef unique_ptr<_Tp> __single_object; };
812
813 template<typename _Tp>
814 struct _MakeUniq<_Tp[]>
815 { typedef unique_ptr<_Tp[]> __array; };
816
817 template<typename _Tp, size_t _Bound>
818 struct _MakeUniq<_Tp[_Bound]>
819 { struct __invalid_type { }; };
820
821 /// std::make_unique for single objects
822 template<typename _Tp, typename... _Args>
823 inline typename _MakeUniq<_Tp>::__single_object
824 make_unique(_Args&&... __args)
825 { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
826
827 /// std::make_unique for arrays of unknown bound
828 template<typename _Tp>
829 inline typename _MakeUniq<_Tp>::__array
830 make_unique(size_t __num)
831 { return unique_ptr<_Tp>(new remove_extent_t<_Tp>[__num]()); }
832
833 /// Disable std::make_unique for arrays of known bound
834 template<typename _Tp, typename... _Args>
835 inline typename _MakeUniq<_Tp>::__invalid_type
836 make_unique(_Args&&...) = delete;
837#endif
838
839 // @} group pointer_abstractions
840
841_GLIBCXX_END_NAMESPACE_VERSION
842} // namespace
843
844#endif /* _UNIQUE_PTR_H */