Bug Summary

File:build/source/clang/utils/TableGen/MveEmitter.cpp
Warning:line 1411, column 23
Division by zero

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name MveEmitter.cpp -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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/utils/TableGen -I /build/source/clang/utils/TableGen -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1679915782 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-03-27-130437-16335-1 -x c++ /build/source/clang/utils/TableGen/MveEmitter.cpp

/build/source/clang/utils/TableGen/MveEmitter.cpp

1//===- MveEmitter.cpp - Generate arm_mve.h for use with clang -*- C++ -*-=====//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This set of linked tablegen backends is responsible for emitting the bits
10// and pieces that implement <arm_mve.h>, which is defined by the ACLE standard
11// and provides a set of types and functions for (more or less) direct access
12// to the MVE instruction set, including the scalar shifts as well as the
13// vector instructions.
14//
15// MVE's standard intrinsic functions are unusual in that they have a system of
16// polymorphism. For example, the function vaddq() can behave like vaddq_u16(),
17// vaddq_f32(), vaddq_s8(), etc., depending on the types of the vector
18// arguments you give it.
19//
20// This constrains the implementation strategies. The usual approach to making
21// the user-facing functions polymorphic would be to either use
22// __attribute__((overloadable)) to make a set of vaddq() functions that are
23// all inline wrappers on the underlying clang builtins, or to define a single
24// vaddq() macro which expands to an instance of _Generic.
25//
26// The inline-wrappers approach would work fine for most intrinsics, except for
27// the ones that take an argument required to be a compile-time constant,
28// because if you wrap an inline function around a call to a builtin, the
29// constant nature of the argument is not passed through.
30//
31// The _Generic approach can be made to work with enough effort, but it takes a
32// lot of machinery, because of the design feature of _Generic that even the
33// untaken branches are required to pass all front-end validity checks such as
34// type-correctness. You can work around that by nesting further _Generics all
35// over the place to coerce things to the right type in untaken branches, but
36// what you get out is complicated, hard to guarantee its correctness, and
37// worst of all, gives _completely unreadable_ error messages if the user gets
38// the types wrong for an intrinsic call.
39//
40// Therefore, my strategy is to introduce a new __attribute__ that allows a
41// function to be mapped to a clang builtin even though it doesn't have the
42// same name, and then declare all the user-facing MVE function names with that
43// attribute, mapping each one directly to the clang builtin. And the
44// polymorphic ones have __attribute__((overloadable)) as well. So once the
45// compiler has resolved the overload, it knows the internal builtin ID of the
46// selected function, and can check the immediate arguments against that; and
47// if the user gets the types wrong in a call to a polymorphic intrinsic, they
48// get a completely clear error message showing all the declarations of that
49// function in the header file and explaining why each one doesn't fit their
50// call.
51//
52// The downside of this is that if every clang builtin has to correspond
53// exactly to a user-facing ACLE intrinsic, then you can't save work in the
54// frontend by doing it in the header file: CGBuiltin.cpp has to do the entire
55// job of converting an ACLE intrinsic call into LLVM IR. So the Tablegen
56// description for an MVE intrinsic has to contain a full description of the
57// sequence of IRBuilder calls that clang will need to make.
58//
59//===----------------------------------------------------------------------===//
60
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/StringRef.h"
63#include "llvm/ADT/StringSwitch.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/raw_ostream.h"
66#include "llvm/TableGen/Error.h"
67#include "llvm/TableGen/Record.h"
68#include "llvm/TableGen/StringToOffsetTable.h"
69#include <cassert>
70#include <cstddef>
71#include <cstdint>
72#include <list>
73#include <map>
74#include <memory>
75#include <set>
76#include <string>
77#include <vector>
78
79using namespace llvm;
80
81namespace {
82
83class EmitterBase;
84class Result;
85
86// -----------------------------------------------------------------------------
87// A system of classes to represent all the types we'll need to deal with in
88// the prototypes of intrinsics.
89//
90// Query methods include finding out the C name of a type; the "LLVM name" in
91// the sense of a C++ code snippet that can be used in the codegen function;
92// the suffix that represents the type in the ACLE intrinsic naming scheme
93// (e.g. 's32' represents int32_t in intrinsics such as vaddq_s32); whether the
94// type is floating-point related (hence should be under #ifdef in the MVE
95// header so that it isn't included in integer-only MVE mode); and the type's
96// size in bits. Not all subtypes support all these queries.
97
98class Type {
99public:
100 enum class TypeKind {
101 // Void appears as a return type (for store intrinsics, which are pure
102 // side-effect). It's also used as the parameter type in the Tablegen
103 // when an intrinsic doesn't need to come in various suffixed forms like
104 // vfooq_s8,vfooq_u16,vfooq_f32.
105 Void,
106
107 // Scalar is used for ordinary int and float types of all sizes.
108 Scalar,
109
110 // Vector is used for anything that occupies exactly one MVE vector
111 // register, i.e. {uint,int,float}NxM_t.
112 Vector,
113
114 // MultiVector is used for the {uint,int,float}NxMxK_t types used by the
115 // interleaving load/store intrinsics v{ld,st}{2,4}q.
116 MultiVector,
117
118 // Predicate is used by all the predicated intrinsics. Its C
119 // representation is mve_pred16_t (which is just an alias for uint16_t).
120 // But we give more detail here, by indicating that a given predicate
121 // instruction is logically regarded as a vector of i1 containing the
122 // same number of lanes as the input vector type. So our Predicate type
123 // comes with a lane count, which we use to decide which kind of <n x i1>
124 // we'll invoke the pred_i2v IR intrinsic to translate it into.
125 Predicate,
126
127 // Pointer is used for pointer types (obviously), and comes with a flag
128 // indicating whether it's a pointer to a const or mutable instance of
129 // the pointee type.
130 Pointer,
131 };
132
133private:
134 const TypeKind TKind;
135
136protected:
137 Type(TypeKind K) : TKind(K) {}
138
139public:
140 TypeKind typeKind() const { return TKind; }
141 virtual ~Type() = default;
142 virtual bool requiresFloat() const = 0;
143 virtual bool requiresMVE() const = 0;
144 virtual unsigned sizeInBits() const = 0;
145 virtual std::string cName() const = 0;
146 virtual std::string llvmName() const {
147 PrintFatalError("no LLVM type name available for type " + cName());
148 }
149 virtual std::string acleSuffix(std::string) const {
150 PrintFatalError("no ACLE suffix available for this type");
151 }
152};
153
154enum class ScalarTypeKind { SignedInt, UnsignedInt, Float };
155inline std::string toLetter(ScalarTypeKind kind) {
156 switch (kind) {
157 case ScalarTypeKind::SignedInt:
158 return "s";
159 case ScalarTypeKind::UnsignedInt:
160 return "u";
161 case ScalarTypeKind::Float:
162 return "f";
163 }
164 llvm_unreachable("Unhandled ScalarTypeKind enum")::llvm::llvm_unreachable_internal("Unhandled ScalarTypeKind enum"
, "clang/utils/TableGen/MveEmitter.cpp", 164)
;
165}
166inline std::string toCPrefix(ScalarTypeKind kind) {
167 switch (kind) {
168 case ScalarTypeKind::SignedInt:
169 return "int";
170 case ScalarTypeKind::UnsignedInt:
171 return "uint";
172 case ScalarTypeKind::Float:
173 return "float";
174 }
175 llvm_unreachable("Unhandled ScalarTypeKind enum")::llvm::llvm_unreachable_internal("Unhandled ScalarTypeKind enum"
, "clang/utils/TableGen/MveEmitter.cpp", 175)
;
176}
177
178class VoidType : public Type {
179public:
180 VoidType() : Type(TypeKind::Void) {}
181 unsigned sizeInBits() const override { return 0; }
25
Returning zero
182 bool requiresFloat() const override { return false; }
183 bool requiresMVE() const override { return false; }
184 std::string cName() const override { return "void"; }
185
186 static bool classof(const Type *T) { return T->typeKind() == TypeKind::Void; }
187 std::string acleSuffix(std::string) const override { return ""; }
188};
189
190class PointerType : public Type {
191 const Type *Pointee;
192 bool Const;
193
194public:
195 PointerType(const Type *Pointee, bool Const)
196 : Type(TypeKind::Pointer), Pointee(Pointee), Const(Const) {}
197 unsigned sizeInBits() const override { return 32; }
198 bool requiresFloat() const override { return Pointee->requiresFloat(); }
199 bool requiresMVE() const override { return Pointee->requiresMVE(); }
200 std::string cName() const override {
201 std::string Name = Pointee->cName();
202
203 // The syntax for a pointer in C is different when the pointee is
204 // itself a pointer. The MVE intrinsics don't contain any double
205 // pointers, so we don't need to worry about that wrinkle.
206 assert(!isa<PointerType>(Pointee) && "Pointer to pointer not supported")(static_cast <bool> (!isa<PointerType>(Pointee) &&
"Pointer to pointer not supported") ? void (0) : __assert_fail
("!isa<PointerType>(Pointee) && \"Pointer to pointer not supported\""
, "clang/utils/TableGen/MveEmitter.cpp", 206, __extension__ __PRETTY_FUNCTION__
))
;
207
208 if (Const)
209 Name = "const " + Name;
210 return Name + " *";
211 }
212 std::string llvmName() const override {
213 return "llvm::PointerType::getUnqual(" + Pointee->llvmName() + ")";
214 }
215 const Type *getPointeeType() const { return Pointee; }
216
217 static bool classof(const Type *T) {
218 return T->typeKind() == TypeKind::Pointer;
219 }
220};
221
222// Base class for all the types that have a name of the form
223// [prefix][numbers]_t, like int32_t, uint16x8_t, float32x4x2_t.
224//
225// For this sub-hierarchy we invent a cNameBase() method which returns the
226// whole name except for the trailing "_t", so that Vector and MultiVector can
227// append an extra "x2" or whatever to their element type's cNameBase(). Then
228// the main cName() query method puts "_t" on the end for the final type name.
229
230class CRegularNamedType : public Type {
231 using Type::Type;
232 virtual std::string cNameBase() const = 0;
233
234public:
235 std::string cName() const override { return cNameBase() + "_t"; }
236};
237
238class ScalarType : public CRegularNamedType {
239 ScalarTypeKind Kind;
240 unsigned Bits;
241 std::string NameOverride;
242
243public:
244 ScalarType(const Record *Record) : CRegularNamedType(TypeKind::Scalar) {
245 Kind = StringSwitch<ScalarTypeKind>(Record->getValueAsString("kind"))
246 .Case("s", ScalarTypeKind::SignedInt)
247 .Case("u", ScalarTypeKind::UnsignedInt)
248 .Case("f", ScalarTypeKind::Float);
249 Bits = Record->getValueAsInt("size");
250 NameOverride = std::string(Record->getValueAsString("nameOverride"));
251 }
252 unsigned sizeInBits() const override { return Bits; }
253 ScalarTypeKind kind() const { return Kind; }
254 std::string suffix() const { return toLetter(Kind) + utostr(Bits); }
255 std::string cNameBase() const override {
256 return toCPrefix(Kind) + utostr(Bits);
257 }
258 std::string cName() const override {
259 if (NameOverride.empty())
260 return CRegularNamedType::cName();
261 return NameOverride;
262 }
263 std::string llvmName() const override {
264 if (Kind == ScalarTypeKind::Float) {
265 if (Bits == 16)
266 return "HalfTy";
267 if (Bits == 32)
268 return "FloatTy";
269 if (Bits == 64)
270 return "DoubleTy";
271 PrintFatalError("bad size for floating type");
272 }
273 return "Int" + utostr(Bits) + "Ty";
274 }
275 std::string acleSuffix(std::string overrideLetter) const override {
276 return "_" + (overrideLetter.size() ? overrideLetter : toLetter(Kind))
277 + utostr(Bits);
278 }
279 bool isInteger() const { return Kind != ScalarTypeKind::Float; }
280 bool requiresFloat() const override { return !isInteger(); }
281 bool requiresMVE() const override { return false; }
282 bool hasNonstandardName() const { return !NameOverride.empty(); }
283
284 static bool classof(const Type *T) {
285 return T->typeKind() == TypeKind::Scalar;
286 }
287};
288
289class VectorType : public CRegularNamedType {
290 const ScalarType *Element;
291 unsigned Lanes;
292
293public:
294 VectorType(const ScalarType *Element, unsigned Lanes)
295 : CRegularNamedType(TypeKind::Vector), Element(Element), Lanes(Lanes) {}
296 unsigned sizeInBits() const override { return Lanes * Element->sizeInBits(); }
297 unsigned lanes() const { return Lanes; }
298 bool requiresFloat() const override { return Element->requiresFloat(); }
299 bool requiresMVE() const override { return true; }
300 std::string cNameBase() const override {
301 return Element->cNameBase() + "x" + utostr(Lanes);
302 }
303 std::string llvmName() const override {
304 return "llvm::FixedVectorType::get(" + Element->llvmName() + ", " +
305 utostr(Lanes) + ")";
306 }
307
308 static bool classof(const Type *T) {
309 return T->typeKind() == TypeKind::Vector;
310 }
311};
312
313class MultiVectorType : public CRegularNamedType {
314 const VectorType *Element;
315 unsigned Registers;
316
317public:
318 MultiVectorType(unsigned Registers, const VectorType *Element)
319 : CRegularNamedType(TypeKind::MultiVector), Element(Element),
320 Registers(Registers) {}
321 unsigned sizeInBits() const override {
322 return Registers * Element->sizeInBits();
323 }
324 unsigned registers() const { return Registers; }
325 bool requiresFloat() const override { return Element->requiresFloat(); }
326 bool requiresMVE() const override { return true; }
327 std::string cNameBase() const override {
328 return Element->cNameBase() + "x" + utostr(Registers);
329 }
330
331 // MultiVectorType doesn't override llvmName, because we don't expect to do
332 // automatic code generation for the MVE intrinsics that use it: the {vld2,
333 // vld4, vst2, vst4} family are the only ones that use these types, so it was
334 // easier to hand-write the codegen for dealing with these structs than to
335 // build in lots of extra automatic machinery that would only be used once.
336
337 static bool classof(const Type *T) {
338 return T->typeKind() == TypeKind::MultiVector;
339 }
340};
341
342class PredicateType : public CRegularNamedType {
343 unsigned Lanes;
344
345public:
346 PredicateType(unsigned Lanes)
347 : CRegularNamedType(TypeKind::Predicate), Lanes(Lanes) {}
348 unsigned sizeInBits() const override { return 16; }
349 std::string cNameBase() const override { return "mve_pred16"; }
350 bool requiresFloat() const override { return false; };
351 bool requiresMVE() const override { return true; }
352 std::string llvmName() const override {
353 return "llvm::FixedVectorType::get(Builder.getInt1Ty(), " + utostr(Lanes) +
354 ")";
355 }
356
357 static bool classof(const Type *T) {
358 return T->typeKind() == TypeKind::Predicate;
359 }
360};
361
362// -----------------------------------------------------------------------------
363// Class to facilitate merging together the code generation for many intrinsics
364// by means of varying a few constant or type parameters.
365//
366// Most obviously, the intrinsics in a single parametrised family will have
367// code generation sequences that only differ in a type or two, e.g. vaddq_s8
368// and vaddq_u16 will look the same apart from putting a different vector type
369// in the call to CGM.getIntrinsic(). But also, completely different intrinsics
370// will often code-generate in the same way, with only a different choice of
371// _which_ IR intrinsic they lower to (e.g. vaddq_m_s8 and vmulq_m_s8), but
372// marshalling the arguments and return values of the IR intrinsic in exactly
373// the same way. And others might differ only in some other kind of constant,
374// such as a lane index.
375//
376// So, when we generate the IR-building code for all these intrinsics, we keep
377// track of every value that could possibly be pulled out of the code and
378// stored ahead of time in a local variable. Then we group together intrinsics
379// by textual equivalence of the code that would result if _all_ those
380// parameters were stored in local variables. That gives us maximal sets that
381// can be implemented by a single piece of IR-building code by changing
382// parameter values ahead of time.
383//
384// After we've done that, we do a second pass in which we only allocate _some_
385// of the parameters into local variables, by tracking which ones have the same
386// values as each other (so that a single variable can be reused) and which
387// ones are the same across the whole set (so that no variable is needed at
388// all).
389//
390// Hence the class below. Its allocParam method is invoked during code
391// generation by every method of a Result subclass (see below) that wants to
392// give it the opportunity to pull something out into a switchable parameter.
393// It returns a variable name for the parameter, or (if it's being used in the
394// second pass once we've decided that some parameters don't need to be stored
395// in variables after all) it might just return the input expression unchanged.
396
397struct CodeGenParamAllocator {
398 // Accumulated during code generation
399 std::vector<std::string> *ParamTypes = nullptr;
400 std::vector<std::string> *ParamValues = nullptr;
401
402 // Provided ahead of time in pass 2, to indicate which parameters are being
403 // assigned to what. This vector contains an entry for each call to
404 // allocParam expected during code gen (which we counted up in pass 1), and
405 // indicates the number of the parameter variable that should be returned, or
406 // -1 if this call shouldn't allocate a parameter variable at all.
407 //
408 // We rely on the recursive code generation working identically in passes 1
409 // and 2, so that the same list of calls to allocParam happen in the same
410 // order. That guarantees that the parameter numbers recorded in pass 1 will
411 // match the entries in this vector that store what EmitterBase::EmitBuiltinCG
412 // decided to do about each one in pass 2.
413 std::vector<int> *ParamNumberMap = nullptr;
414
415 // Internally track how many things we've allocated
416 unsigned nparams = 0;
417
418 std::string allocParam(StringRef Type, StringRef Value) {
419 unsigned ParamNumber;
420
421 if (!ParamNumberMap) {
422 // In pass 1, unconditionally assign a new parameter variable to every
423 // value we're asked to process.
424 ParamNumber = nparams++;
425 } else {
426 // In pass 2, consult the map provided by the caller to find out which
427 // variable we should be keeping things in.
428 int MapValue = (*ParamNumberMap)[nparams++];
429 if (MapValue < 0)
430 return std::string(Value);
431 ParamNumber = MapValue;
432 }
433
434 // If we've allocated a new parameter variable for the first time, store
435 // its type and value to be retrieved after codegen.
436 if (ParamTypes && ParamTypes->size() == ParamNumber)
437 ParamTypes->push_back(std::string(Type));
438 if (ParamValues && ParamValues->size() == ParamNumber)
439 ParamValues->push_back(std::string(Value));
440
441 // Unimaginative naming scheme for parameter variables.
442 return "Param" + utostr(ParamNumber);
443 }
444};
445
446// -----------------------------------------------------------------------------
447// System of classes that represent all the intermediate values used during
448// code-generation for an intrinsic.
449//
450// The base class 'Result' can represent a value of the LLVM type 'Value', or
451// sometimes 'Address' (for loads/stores, including an alignment requirement).
452//
453// In the case where the Tablegen provides a value in the codegen dag as a
454// plain integer literal, the Result object we construct here will be one that
455// returns true from hasIntegerConstantValue(). This allows the generated C++
456// code to use the constant directly in contexts which can take a literal
457// integer, such as Builder.CreateExtractValue(thing, 1), without going to the
458// effort of calling llvm::ConstantInt::get() and then pulling the constant
459// back out of the resulting llvm:Value later.
460
461class Result {
462public:
463 // Convenient shorthand for the pointer type we'll be using everywhere.
464 using Ptr = std::shared_ptr<Result>;
465
466private:
467 Ptr Predecessor;
468 std::string VarName;
469 bool VarNameUsed = false;
470 unsigned Visited = 0;
471
472public:
473 virtual ~Result() = default;
474 using Scope = std::map<std::string, Ptr>;
475 virtual void genCode(raw_ostream &OS, CodeGenParamAllocator &) const = 0;
476 virtual bool hasIntegerConstantValue() const { return false; }
477 virtual uint32_t integerConstantValue() const { return 0; }
478 virtual bool hasIntegerValue() const { return false; }
479 virtual std::string getIntegerValue(const std::string &) {
480 llvm_unreachable("non-working Result::getIntegerValue called")::llvm::llvm_unreachable_internal("non-working Result::getIntegerValue called"
, "clang/utils/TableGen/MveEmitter.cpp", 480)
;
481 }
482 virtual std::string typeName() const { return "Value *"; }
483
484 // Mostly, when a code-generation operation has a dependency on prior
485 // operations, it's because it uses the output values of those operations as
486 // inputs. But there's one exception, which is the use of 'seq' in Tablegen
487 // to indicate that operations have to be performed in sequence regardless of
488 // whether they use each others' output values.
489 //
490 // So, the actual generation of code is done by depth-first search, using the
491 // prerequisites() method to get a list of all the other Results that have to
492 // be computed before this one. That method divides into the 'predecessor',
493 // set by setPredecessor() while processing a 'seq' dag node, and the list
494 // returned by 'morePrerequisites', which each subclass implements to return
495 // a list of the Results it uses as input to whatever its own computation is
496 // doing.
497
498 virtual void morePrerequisites(std::vector<Ptr> &output) const {}
499 std::vector<Ptr> prerequisites() const {
500 std::vector<Ptr> ToRet;
501 if (Predecessor)
502 ToRet.push_back(Predecessor);
503 morePrerequisites(ToRet);
504 return ToRet;
505 }
506
507 void setPredecessor(Ptr p) {
508 // If the user has nested one 'seq' node inside another, and this
509 // method is called on the return value of the inner 'seq' (i.e.
510 // the final item inside it), then we can't link _this_ node to p,
511 // because it already has a predecessor. Instead, walk the chain
512 // until we find the first item in the inner seq, and link that to
513 // p, so that nesting seqs has the obvious effect of linking
514 // everything together into one long sequential chain.
515 Result *r = this;
516 while (r->Predecessor)
517 r = r->Predecessor.get();
518 r->Predecessor = p;
519 }
520
521 // Each Result will be assigned a variable name in the output code, but not
522 // all those variable names will actually be used (e.g. the return value of
523 // Builder.CreateStore has void type, so nobody will want to refer to it). To
524 // prevent annoying compiler warnings, we track whether each Result's
525 // variable name was ever actually mentioned in subsequent statements, so
526 // that it can be left out of the final generated code.
527 std::string varname() {
528 VarNameUsed = true;
529 return VarName;
530 }
531 void setVarname(const StringRef s) { VarName = std::string(s); }
532 bool varnameUsed() const { return VarNameUsed; }
533
534 // Emit code to generate this result as a Value *.
535 virtual std::string asValue() {
536 return varname();
537 }
538
539 // Code generation happens in multiple passes. This method tracks whether a
540 // Result has yet been visited in a given pass, without the need for a
541 // tedious loop in between passes that goes through and resets a 'visited'
542 // flag back to false: you just set Pass=1 the first time round, and Pass=2
543 // the second time.
544 bool needsVisiting(unsigned Pass) {
545 bool ToRet = Visited < Pass;
546 Visited = Pass;
547 return ToRet;
548 }
549};
550
551// Result subclass that retrieves one of the arguments to the clang builtin
552// function. In cases where the argument has pointer type, we call
553// EmitPointerWithAlignment and store the result in a variable of type Address,
554// so that load and store IR nodes can know the right alignment. Otherwise, we
555// call EmitScalarExpr.
556//
557// There are aggregate parameters in the MVE intrinsics API, but we don't deal
558// with them in this Tablegen back end: they only arise in the vld2q/vld4q and
559// vst2q/vst4q family, which is few enough that we just write the code by hand
560// for those in CGBuiltin.cpp.
561class BuiltinArgResult : public Result {
562public:
563 unsigned ArgNum;
564 bool AddressType;
565 bool Immediate;
566 BuiltinArgResult(unsigned ArgNum, bool AddressType, bool Immediate)
567 : ArgNum(ArgNum), AddressType(AddressType), Immediate(Immediate) {}
568 void genCode(raw_ostream &OS, CodeGenParamAllocator &) const override {
569 OS << (AddressType ? "EmitPointerWithAlignment" : "EmitScalarExpr")
570 << "(E->getArg(" << ArgNum << "))";
571 }
572 std::string typeName() const override {
573 return AddressType ? "Address" : Result::typeName();
574 }
575 // Emit code to generate this result as a Value *.
576 std::string asValue() override {
577 if (AddressType)
578 return "(" + varname() + ".getPointer())";
579 return Result::asValue();
580 }
581 bool hasIntegerValue() const override { return Immediate; }
582 std::string getIntegerValue(const std::string &IntType) override {
583 return "GetIntegerConstantValue<" + IntType + ">(E->getArg(" +
584 utostr(ArgNum) + "), getContext())";
585 }
586};
587
588// Result subclass for an integer literal appearing in Tablegen. This may need
589// to be turned into an llvm::Result by means of llvm::ConstantInt::get(), or
590// it may be used directly as an integer, depending on which IRBuilder method
591// it's being passed to.
592class IntLiteralResult : public Result {
593public:
594 const ScalarType *IntegerType;
595 uint32_t IntegerValue;
596 IntLiteralResult(const ScalarType *IntegerType, uint32_t IntegerValue)
597 : IntegerType(IntegerType), IntegerValue(IntegerValue) {}
598 void genCode(raw_ostream &OS,
599 CodeGenParamAllocator &ParamAlloc) const override {
600 OS << "llvm::ConstantInt::get("
601 << ParamAlloc.allocParam("llvm::Type *", IntegerType->llvmName())
602 << ", ";
603 OS << ParamAlloc.allocParam(IntegerType->cName(), utostr(IntegerValue))
604 << ")";
605 }
606 bool hasIntegerConstantValue() const override { return true; }
607 uint32_t integerConstantValue() const override { return IntegerValue; }
608};
609
610// Result subclass representing a cast between different integer types. We use
611// our own ScalarType abstraction as the representation of the target type,
612// which gives both size and signedness.
613class IntCastResult : public Result {
614public:
615 const ScalarType *IntegerType;
616 Ptr V;
617 IntCastResult(const ScalarType *IntegerType, Ptr V)
618 : IntegerType(IntegerType), V(V) {}
619 void genCode(raw_ostream &OS,
620 CodeGenParamAllocator &ParamAlloc) const override {
621 OS << "Builder.CreateIntCast(" << V->varname() << ", "
622 << ParamAlloc.allocParam("llvm::Type *", IntegerType->llvmName()) << ", "
623 << ParamAlloc.allocParam("bool",
624 IntegerType->kind() == ScalarTypeKind::SignedInt
625 ? "true"
626 : "false")
627 << ")";
628 }
629 void morePrerequisites(std::vector<Ptr> &output) const override {
630 output.push_back(V);
631 }
632};
633
634// Result subclass representing a cast between different pointer types.
635class PointerCastResult : public Result {
636public:
637 const PointerType *PtrType;
638 Ptr V;
639 PointerCastResult(const PointerType *PtrType, Ptr V)
640 : PtrType(PtrType), V(V) {}
641 void genCode(raw_ostream &OS,
642 CodeGenParamAllocator &ParamAlloc) const override {
643 OS << "Builder.CreatePointerCast(" << V->asValue() << ", "
644 << ParamAlloc.allocParam("llvm::Type *", PtrType->llvmName()) << ")";
645 }
646 void morePrerequisites(std::vector<Ptr> &output) const override {
647 output.push_back(V);
648 }
649};
650
651// Result subclass representing a call to an IRBuilder method. Each IRBuilder
652// method we want to use will have a Tablegen record giving the method name and
653// describing any important details of how to call it, such as whether a
654// particular argument should be an integer constant instead of an llvm::Value.
655class IRBuilderResult : public Result {
656public:
657 StringRef CallPrefix;
658 std::vector<Ptr> Args;
659 std::set<unsigned> AddressArgs;
660 std::map<unsigned, std::string> IntegerArgs;
661 IRBuilderResult(StringRef CallPrefix, std::vector<Ptr> Args,
662 std::set<unsigned> AddressArgs,
663 std::map<unsigned, std::string> IntegerArgs)
664 : CallPrefix(CallPrefix), Args(Args), AddressArgs(AddressArgs),
665 IntegerArgs(IntegerArgs) {}
666 void genCode(raw_ostream &OS,
667 CodeGenParamAllocator &ParamAlloc) const override {
668 OS << CallPrefix;
669 const char *Sep = "";
670 for (unsigned i = 0, e = Args.size(); i < e; ++i) {
671 Ptr Arg = Args[i];
672 auto it = IntegerArgs.find(i);
673
674 OS << Sep;
675 Sep = ", ";
676
677 if (it != IntegerArgs.end()) {
678 if (Arg->hasIntegerConstantValue())
679 OS << "static_cast<" << it->second << ">("
680 << ParamAlloc.allocParam(it->second,
681 utostr(Arg->integerConstantValue()))
682 << ")";
683 else if (Arg->hasIntegerValue())
684 OS << ParamAlloc.allocParam(it->second,
685 Arg->getIntegerValue(it->second));
686 } else {
687 OS << Arg->varname();
688 }
689 }
690 OS << ")";
691 }
692 void morePrerequisites(std::vector<Ptr> &output) const override {
693 for (unsigned i = 0, e = Args.size(); i < e; ++i) {
694 Ptr Arg = Args[i];
695 if (IntegerArgs.find(i) != IntegerArgs.end())
696 continue;
697 output.push_back(Arg);
698 }
699 }
700};
701
702// Result subclass representing making an Address out of a Value.
703class AddressResult : public Result {
704public:
705 Ptr Arg;
706 const Type *Ty;
707 unsigned Align;
708 AddressResult(Ptr Arg, const Type *Ty, unsigned Align)
709 : Arg(Arg), Ty(Ty), Align(Align) {}
710 void genCode(raw_ostream &OS,
711 CodeGenParamAllocator &ParamAlloc) const override {
712 OS << "Address(" << Arg->varname() << ", " << Ty->llvmName()
713 << ", CharUnits::fromQuantity(" << Align << "))";
714 }
715 std::string typeName() const override {
716 return "Address";
717 }
718 void morePrerequisites(std::vector<Ptr> &output) const override {
719 output.push_back(Arg);
720 }
721};
722
723// Result subclass representing a call to an IR intrinsic, which we first have
724// to look up using an Intrinsic::ID constant and an array of types.
725class IRIntrinsicResult : public Result {
726public:
727 std::string IntrinsicID;
728 std::vector<const Type *> ParamTypes;
729 std::vector<Ptr> Args;
730 IRIntrinsicResult(StringRef IntrinsicID, std::vector<const Type *> ParamTypes,
731 std::vector<Ptr> Args)
732 : IntrinsicID(std::string(IntrinsicID)), ParamTypes(ParamTypes),
733 Args(Args) {}
734 void genCode(raw_ostream &OS,
735 CodeGenParamAllocator &ParamAlloc) const override {
736 std::string IntNo = ParamAlloc.allocParam(
737 "Intrinsic::ID", "Intrinsic::" + IntrinsicID);
738 OS << "Builder.CreateCall(CGM.getIntrinsic(" << IntNo;
739 if (!ParamTypes.empty()) {
740 OS << ", {";
741 const char *Sep = "";
742 for (auto T : ParamTypes) {
743 OS << Sep << ParamAlloc.allocParam("llvm::Type *", T->llvmName());
744 Sep = ", ";
745 }
746 OS << "}";
747 }
748 OS << "), {";
749 const char *Sep = "";
750 for (auto Arg : Args) {
751 OS << Sep << Arg->asValue();
752 Sep = ", ";
753 }
754 OS << "})";
755 }
756 void morePrerequisites(std::vector<Ptr> &output) const override {
757 output.insert(output.end(), Args.begin(), Args.end());
758 }
759};
760
761// Result subclass that specifies a type, for use in IRBuilder operations such
762// as CreateBitCast that take a type argument.
763class TypeResult : public Result {
764public:
765 const Type *T;
766 TypeResult(const Type *T) : T(T) {}
767 void genCode(raw_ostream &OS, CodeGenParamAllocator &) const override {
768 OS << T->llvmName();
769 }
770 std::string typeName() const override {
771 return "llvm::Type *";
772 }
773};
774
775// -----------------------------------------------------------------------------
776// Class that describes a single ACLE intrinsic.
777//
778// A Tablegen record will typically describe more than one ACLE intrinsic, by
779// means of setting the 'list<Type> Params' field to a list of multiple
780// parameter types, so as to define vaddq_{s8,u8,...,f16,f32} all in one go.
781// We'll end up with one instance of ACLEIntrinsic for *each* parameter type,
782// rather than a single one for all of them. Hence, the constructor takes both
783// a Tablegen record and the current value of the parameter type.
784
785class ACLEIntrinsic {
786 // Structure documenting that one of the intrinsic's arguments is required to
787 // be a compile-time constant integer, and what constraints there are on its
788 // value. Used when generating Sema checking code.
789 struct ImmediateArg {
790 enum class BoundsType { ExplicitRange, UInt };
791 BoundsType boundsType;
792 int64_t i1, i2;
793 StringRef ExtraCheckType, ExtraCheckArgs;
794 const Type *ArgType;
795 };
796
797 // For polymorphic intrinsics, FullName is the explicit name that uniquely
798 // identifies this variant of the intrinsic, and ShortName is the name it
799 // shares with at least one other intrinsic.
800 std::string ShortName, FullName;
801
802 // Name of the architecture extension, used in the Clang builtin name
803 StringRef BuiltinExtension;
804
805 // A very small number of intrinsics _only_ have a polymorphic
806 // variant (vuninitializedq taking an unevaluated argument).
807 bool PolymorphicOnly;
808
809 // Another rarely-used flag indicating that the builtin doesn't
810 // evaluate its argument(s) at all.
811 bool NonEvaluating;
812
813 // True if the intrinsic needs only the C header part (no codegen, semantic
814 // checks, etc). Used for redeclaring MVE intrinsics in the arm_cde.h header.
815 bool HeaderOnly;
816
817 const Type *ReturnType;
818 std::vector<const Type *> ArgTypes;
819 std::map<unsigned, ImmediateArg> ImmediateArgs;
820 Result::Ptr Code;
821
822 std::map<std::string, std::string> CustomCodeGenArgs;
823
824 // Recursive function that does the internals of code generation.
825 void genCodeDfs(Result::Ptr V, std::list<Result::Ptr> &Used,
826 unsigned Pass) const {
827 if (!V->needsVisiting(Pass))
828 return;
829
830 for (Result::Ptr W : V->prerequisites())
831 genCodeDfs(W, Used, Pass);
832
833 Used.push_back(V);
834 }
835
836public:
837 const std::string &shortName() const { return ShortName; }
838 const std::string &fullName() const { return FullName; }
839 StringRef builtinExtension() const { return BuiltinExtension; }
840 const Type *returnType() const { return ReturnType; }
841 const std::vector<const Type *> &argTypes() const { return ArgTypes; }
842 bool requiresFloat() const {
843 if (ReturnType->requiresFloat())
844 return true;
845 for (const Type *T : ArgTypes)
846 if (T->requiresFloat())
847 return true;
848 return false;
849 }
850 bool requiresMVE() const {
851 return ReturnType->requiresMVE() ||
852 any_of(ArgTypes, [](const Type *T) { return T->requiresMVE(); });
853 }
854 bool polymorphic() const { return ShortName != FullName; }
855 bool polymorphicOnly() const { return PolymorphicOnly; }
856 bool nonEvaluating() const { return NonEvaluating; }
857 bool headerOnly() const { return HeaderOnly; }
858
859 // External entry point for code generation, called from EmitterBase.
860 void genCode(raw_ostream &OS, CodeGenParamAllocator &ParamAlloc,
861 unsigned Pass) const {
862 assert(!headerOnly() && "Called genCode for header-only intrinsic")(static_cast <bool> (!headerOnly() && "Called genCode for header-only intrinsic"
) ? void (0) : __assert_fail ("!headerOnly() && \"Called genCode for header-only intrinsic\""
, "clang/utils/TableGen/MveEmitter.cpp", 862, __extension__ __PRETTY_FUNCTION__
))
;
863 if (!hasCode()) {
864 for (auto kv : CustomCodeGenArgs)
865 OS << " " << kv.first << " = " << kv.second << ";\n";
866 OS << " break; // custom code gen\n";
867 return;
868 }
869 std::list<Result::Ptr> Used;
870 genCodeDfs(Code, Used, Pass);
871
872 unsigned varindex = 0;
873 for (Result::Ptr V : Used)
874 if (V->varnameUsed())
875 V->setVarname("Val" + utostr(varindex++));
876
877 for (Result::Ptr V : Used) {
878 OS << " ";
879 if (V == Used.back()) {
880 assert(!V->varnameUsed())(static_cast <bool> (!V->varnameUsed()) ? void (0) :
__assert_fail ("!V->varnameUsed()", "clang/utils/TableGen/MveEmitter.cpp"
, 880, __extension__ __PRETTY_FUNCTION__))
;
881 OS << "return "; // FIXME: what if the top-level thing is void?
882 } else if (V->varnameUsed()) {
883 std::string Type = V->typeName();
884 OS << V->typeName();
885 if (!StringRef(Type).endswith("*"))
886 OS << " ";
887 OS << V->varname() << " = ";
888 }
889 V->genCode(OS, ParamAlloc);
890 OS << ";\n";
891 }
892 }
893 bool hasCode() const { return Code != nullptr; }
894
895 static std::string signedHexLiteral(const llvm::APInt &iOrig) {
896 llvm::APInt i = iOrig.trunc(64);
897 SmallString<40> s;
898 i.toString(s, 16, true, true);
899 return std::string(s.str());
900 }
901
902 std::string genSema() const {
903 assert(!headerOnly() && "Called genSema for header-only intrinsic")(static_cast <bool> (!headerOnly() && "Called genSema for header-only intrinsic"
) ? void (0) : __assert_fail ("!headerOnly() && \"Called genSema for header-only intrinsic\""
, "clang/utils/TableGen/MveEmitter.cpp", 903, __extension__ __PRETTY_FUNCTION__
))
;
904 std::vector<std::string> SemaChecks;
905
906 for (const auto &kv : ImmediateArgs) {
907 const ImmediateArg &IA = kv.second;
908
909 llvm::APInt lo(128, 0), hi(128, 0);
910 switch (IA.boundsType) {
911 case ImmediateArg::BoundsType::ExplicitRange:
912 lo = IA.i1;
913 hi = IA.i2;
914 break;
915 case ImmediateArg::BoundsType::UInt:
916 lo = 0;
917 hi = llvm::APInt::getMaxValue(IA.i1).zext(128);
918 break;
919 }
920
921 std::string Index = utostr(kv.first);
922
923 // Emit a range check if the legal range of values for the
924 // immediate is smaller than the _possible_ range of values for
925 // its type.
926 unsigned ArgTypeBits = IA.ArgType->sizeInBits();
927 llvm::APInt ArgTypeRange = llvm::APInt::getMaxValue(ArgTypeBits).zext(128);
928 llvm::APInt ActualRange = (hi-lo).trunc(64).sext(128);
929 if (ActualRange.ult(ArgTypeRange))
930 SemaChecks.push_back("SemaBuiltinConstantArgRange(TheCall, " + Index +
931 ", " + signedHexLiteral(lo) + ", " +
932 signedHexLiteral(hi) + ")");
933
934 if (!IA.ExtraCheckType.empty()) {
935 std::string Suffix;
936 if (!IA.ExtraCheckArgs.empty()) {
937 std::string tmp;
938 StringRef Arg = IA.ExtraCheckArgs;
939 if (Arg == "!lanesize") {
940 tmp = utostr(IA.ArgType->sizeInBits());
941 Arg = tmp;
942 }
943 Suffix = (Twine(", ") + Arg).str();
944 }
945 SemaChecks.push_back((Twine("SemaBuiltinConstantArg") +
946 IA.ExtraCheckType + "(TheCall, " + Index +
947 Suffix + ")")
948 .str());
949 }
950
951 assert(!SemaChecks.empty())(static_cast <bool> (!SemaChecks.empty()) ? void (0) : __assert_fail
("!SemaChecks.empty()", "clang/utils/TableGen/MveEmitter.cpp"
, 951, __extension__ __PRETTY_FUNCTION__))
;
952 }
953 if (SemaChecks.empty())
954 return "";
955 return join(std::begin(SemaChecks), std::end(SemaChecks),
956 " ||\n ") +
957 ";\n";
958 }
959
960 ACLEIntrinsic(EmitterBase &ME, Record *R, const Type *Param);
961};
962
963// -----------------------------------------------------------------------------
964// The top-level class that holds all the state from analyzing the entire
965// Tablegen input.
966
967class EmitterBase {
968protected:
969 // EmitterBase holds a collection of all the types we've instantiated.
970 VoidType Void;
971 std::map<std::string, std::unique_ptr<ScalarType>> ScalarTypes;
972 std::map<std::tuple<ScalarTypeKind, unsigned, unsigned>,
973 std::unique_ptr<VectorType>>
974 VectorTypes;
975 std::map<std::pair<std::string, unsigned>, std::unique_ptr<MultiVectorType>>
976 MultiVectorTypes;
977 std::map<unsigned, std::unique_ptr<PredicateType>> PredicateTypes;
978 std::map<std::string, std::unique_ptr<PointerType>> PointerTypes;
979
980 // And all the ACLEIntrinsic instances we've created.
981 std::map<std::string, std::unique_ptr<ACLEIntrinsic>> ACLEIntrinsics;
982
983public:
984 // Methods to create a Type object, or return the right existing one from the
985 // maps stored in this object.
986 const VoidType *getVoidType() { return &Void; }
987 const ScalarType *getScalarType(StringRef Name) {
988 return ScalarTypes[std::string(Name)].get();
989 }
990 const ScalarType *getScalarType(Record *R) {
991 return getScalarType(R->getName());
992 }
993 const VectorType *getVectorType(const ScalarType *ST, unsigned Lanes) {
994 std::tuple<ScalarTypeKind, unsigned, unsigned> key(ST->kind(),
995 ST->sizeInBits(), Lanes);
996 if (VectorTypes.find(key) == VectorTypes.end())
997 VectorTypes[key] = std::make_unique<VectorType>(ST, Lanes);
998 return VectorTypes[key].get();
999 }
1000 const VectorType *getVectorType(const ScalarType *ST) {
1001 return getVectorType(ST, 128 / ST->sizeInBits());
1002 }
1003 const MultiVectorType *getMultiVectorType(unsigned Registers,
1004 const VectorType *VT) {
1005 std::pair<std::string, unsigned> key(VT->cNameBase(), Registers);
1006 if (MultiVectorTypes.find(key) == MultiVectorTypes.end())
1007 MultiVectorTypes[key] = std::make_unique<MultiVectorType>(Registers, VT);
1008 return MultiVectorTypes[key].get();
1009 }
1010 const PredicateType *getPredicateType(unsigned Lanes) {
1011 unsigned key = Lanes;
1012 if (PredicateTypes.find(key) == PredicateTypes.end())
1013 PredicateTypes[key] = std::make_unique<PredicateType>(Lanes);
1014 return PredicateTypes[key].get();
1015 }
1016 const PointerType *getPointerType(const Type *T, bool Const) {
1017 PointerType PT(T, Const);
1018 std::string key = PT.cName();
1019 if (PointerTypes.find(key) == PointerTypes.end())
1020 PointerTypes[key] = std::make_unique<PointerType>(PT);
1021 return PointerTypes[key].get();
1022 }
1023
1024 // Methods to construct a type from various pieces of Tablegen. These are
1025 // always called in the context of setting up a particular ACLEIntrinsic, so
1026 // there's always an ambient parameter type (because we're iterating through
1027 // the Params list in the Tablegen record for the intrinsic), which is used
1028 // to expand Tablegen classes like 'Vector' which mean something different in
1029 // each member of a parametric family.
1030 const Type *getType(Record *R, const Type *Param);
1031 const Type *getType(DagInit *D, const Type *Param);
1032 const Type *getType(Init *I, const Type *Param);
1033
1034 // Functions that translate the Tablegen representation of an intrinsic's
1035 // code generation into a collection of Value objects (which will then be
1036 // reprocessed to read out the actual C++ code included by CGBuiltin.cpp).
1037 Result::Ptr getCodeForDag(DagInit *D, const Result::Scope &Scope,
1038 const Type *Param);
1039 Result::Ptr getCodeForDagArg(DagInit *D, unsigned ArgNum,
1040 const Result::Scope &Scope, const Type *Param);
1041 Result::Ptr getCodeForArg(unsigned ArgNum, const Type *ArgType, bool Promote,
1042 bool Immediate);
1043
1044 void GroupSemaChecks(std::map<std::string, std::set<std::string>> &Checks);
1045
1046 // Constructor and top-level functions.
1047
1048 EmitterBase(RecordKeeper &Records);
1049 virtual ~EmitterBase() = default;
1050
1051 virtual void EmitHeader(raw_ostream &OS) = 0;
1052 virtual void EmitBuiltinDef(raw_ostream &OS) = 0;
1053 virtual void EmitBuiltinSema(raw_ostream &OS) = 0;
1054 void EmitBuiltinCG(raw_ostream &OS);
1055 void EmitBuiltinAliases(raw_ostream &OS);
1056};
1057
1058const Type *EmitterBase::getType(Init *I, const Type *Param) {
1059 if (auto Dag = dyn_cast<DagInit>(I))
1060 return getType(Dag, Param);
1061 if (auto Def = dyn_cast<DefInit>(I))
1062 return getType(Def->getDef(), Param);
1063
1064 PrintFatalError("Could not convert this value into a type");
1065}
1066
1067const Type *EmitterBase::getType(Record *R, const Type *Param) {
1068 // Pass to a subfield of any wrapper records. We don't expect more than one
1069 // of these: immediate operands are used as plain numbers rather than as
1070 // llvm::Value, so it's meaningless to promote their type anyway.
1071 if (R->isSubClassOf("Immediate"))
1072 R = R->getValueAsDef("type");
1073 else if (R->isSubClassOf("unpromoted"))
1074 R = R->getValueAsDef("underlying_type");
1075
1076 if (R->getName() == "Void")
1077 return getVoidType();
1078 if (R->isSubClassOf("PrimitiveType"))
1079 return getScalarType(R);
1080 if (R->isSubClassOf("ComplexType"))
1081 return getType(R->getValueAsDag("spec"), Param);
1082
1083 PrintFatalError(R->getLoc(), "Could not convert this record into a type");
1084}
1085
1086const Type *EmitterBase::getType(DagInit *D, const Type *Param) {
1087 // The meat of the getType system: types in the Tablegen are represented by a
1088 // dag whose operators select sub-cases of this function.
1089
1090 Record *Op = cast<DefInit>(D->getOperator())->getDef();
1091 if (!Op->isSubClassOf("ComplexTypeOp"))
1092 PrintFatalError(
1093 "Expected ComplexTypeOp as dag operator in type expression");
1094
1095 if (Op->getName() == "CTO_Parameter") {
1096 if (isa<VoidType>(Param))
1097 PrintFatalError("Parametric type in unparametrised context");
1098 return Param;
1099 }
1100
1101 if (Op->getName() == "CTO_Vec") {
1102 const Type *Element = getType(D->getArg(0), Param);
1103 if (D->getNumArgs() == 1) {
1104 return getVectorType(cast<ScalarType>(Element));
1105 } else {
1106 const Type *ExistingVector = getType(D->getArg(1), Param);
1107 return getVectorType(cast<ScalarType>(Element),
1108 cast<VectorType>(ExistingVector)->lanes());
1109 }
1110 }
1111
1112 if (Op->getName() == "CTO_Pred") {
1113 const Type *Element = getType(D->getArg(0), Param);
1114 return getPredicateType(128 / Element->sizeInBits());
1115 }
1116
1117 if (Op->isSubClassOf("CTO_Tuple")) {
1118 unsigned Registers = Op->getValueAsInt("n");
1119 const Type *Element = getType(D->getArg(0), Param);
1120 return getMultiVectorType(Registers, cast<VectorType>(Element));
1121 }
1122
1123 if (Op->isSubClassOf("CTO_Pointer")) {
1124 const Type *Pointee = getType(D->getArg(0), Param);
1125 return getPointerType(Pointee, Op->getValueAsBit("const"));
1126 }
1127
1128 if (Op->getName() == "CTO_CopyKind") {
1129 const ScalarType *STSize = cast<ScalarType>(getType(D->getArg(0), Param));
1130 const ScalarType *STKind = cast<ScalarType>(getType(D->getArg(1), Param));
1131 for (const auto &kv : ScalarTypes) {
1132 const ScalarType *RT = kv.second.get();
1133 if (RT->kind() == STKind->kind() && RT->sizeInBits() == STSize->sizeInBits())
1134 return RT;
1135 }
1136 PrintFatalError("Cannot find a type to satisfy CopyKind");
1137 }
1138
1139 if (Op->isSubClassOf("CTO_ScaleSize")) {
1140 const ScalarType *STKind = cast<ScalarType>(getType(D->getArg(0), Param));
1141 int Num = Op->getValueAsInt("num"), Denom = Op->getValueAsInt("denom");
1142 unsigned DesiredSize = STKind->sizeInBits() * Num / Denom;
1143 for (const auto &kv : ScalarTypes) {
1144 const ScalarType *RT = kv.second.get();
1145 if (RT->kind() == STKind->kind() && RT->sizeInBits() == DesiredSize)
1146 return RT;
1147 }
1148 PrintFatalError("Cannot find a type to satisfy ScaleSize");
1149 }
1150
1151 PrintFatalError("Bad operator in type dag expression");
1152}
1153
1154Result::Ptr EmitterBase::getCodeForDag(DagInit *D, const Result::Scope &Scope,
1155 const Type *Param) {
1156 Record *Op = cast<DefInit>(D->getOperator())->getDef();
1157
1158 if (Op->getName() == "seq") {
1159 Result::Scope SubScope = Scope;
1160 Result::Ptr PrevV = nullptr;
1161 for (unsigned i = 0, e = D->getNumArgs(); i < e; ++i) {
1162 // We don't use getCodeForDagArg here, because the argument name
1163 // has different semantics in a seq
1164 Result::Ptr V =
1165 getCodeForDag(cast<DagInit>(D->getArg(i)), SubScope, Param);
1166 StringRef ArgName = D->getArgNameStr(i);
1167 if (!ArgName.empty())
1168 SubScope[std::string(ArgName)] = V;
1169 if (PrevV)
1170 V->setPredecessor(PrevV);
1171 PrevV = V;
1172 }
1173 return PrevV;
1174 } else if (Op->isSubClassOf("Type")) {
1175 if (D->getNumArgs() != 1)
1176 PrintFatalError("Type casts should have exactly one argument");
1177 const Type *CastType = getType(Op, Param);
1178 Result::Ptr Arg = getCodeForDagArg(D, 0, Scope, Param);
1179 if (const auto *ST = dyn_cast<ScalarType>(CastType)) {
1180 if (!ST->requiresFloat()) {
1181 if (Arg->hasIntegerConstantValue())
1182 return std::make_shared<IntLiteralResult>(
1183 ST, Arg->integerConstantValue());
1184 else
1185 return std::make_shared<IntCastResult>(ST, Arg);
1186 }
1187 } else if (const auto *PT = dyn_cast<PointerType>(CastType)) {
1188 return std::make_shared<PointerCastResult>(PT, Arg);
1189 }
1190 PrintFatalError("Unsupported type cast");
1191 } else if (Op->getName() == "address") {
1192 if (D->getNumArgs() != 2)
1193 PrintFatalError("'address' should have two arguments");
1194 Result::Ptr Arg = getCodeForDagArg(D, 0, Scope, Param);
1195
1196 const Type *Ty = nullptr;
1197 if (auto *DI = dyn_cast<DagInit>(D->getArg(0)))
1198 if (auto *PTy = dyn_cast<PointerType>(getType(DI->getOperator(), Param)))
1199 Ty = PTy->getPointeeType();
1200 if (!Ty)
1201 PrintFatalError("'address' pointer argument should be a pointer");
1202
1203 unsigned Alignment;
1204 if (auto *II = dyn_cast<IntInit>(D->getArg(1))) {
1205 Alignment = II->getValue();
1206 } else {
1207 PrintFatalError("'address' alignment argument should be an integer");
1208 }
1209 return std::make_shared<AddressResult>(Arg, Ty, Alignment);
1210 } else if (Op->getName() == "unsignedflag") {
1211 if (D->getNumArgs() != 1)
1212 PrintFatalError("unsignedflag should have exactly one argument");
1213 Record *TypeRec = cast<DefInit>(D->getArg(0))->getDef();
1214 if (!TypeRec->isSubClassOf("Type"))
1215 PrintFatalError("unsignedflag's argument should be a type");
1216 if (const auto *ST = dyn_cast<ScalarType>(getType(TypeRec, Param))) {
1217 return std::make_shared<IntLiteralResult>(
1218 getScalarType("u32"), ST->kind() == ScalarTypeKind::UnsignedInt);
1219 } else {
1220 PrintFatalError("unsignedflag's argument should be a scalar type");
1221 }
1222 } else if (Op->getName() == "bitsize") {
1223 if (D->getNumArgs() != 1)
1224 PrintFatalError("bitsize should have exactly one argument");
1225 Record *TypeRec = cast<DefInit>(D->getArg(0))->getDef();
1226 if (!TypeRec->isSubClassOf("Type"))
1227 PrintFatalError("bitsize's argument should be a type");
1228 if (const auto *ST = dyn_cast<ScalarType>(getType(TypeRec, Param))) {
1229 return std::make_shared<IntLiteralResult>(getScalarType("u32"),
1230 ST->sizeInBits());
1231 } else {
1232 PrintFatalError("bitsize's argument should be a scalar type");
1233 }
1234 } else {
1235 std::vector<Result::Ptr> Args;
1236 for (unsigned i = 0, e = D->getNumArgs(); i < e; ++i)
1237 Args.push_back(getCodeForDagArg(D, i, Scope, Param));
1238 if (Op->isSubClassOf("IRBuilderBase")) {
1239 std::set<unsigned> AddressArgs;
1240 std::map<unsigned, std::string> IntegerArgs;
1241 for (Record *sp : Op->getValueAsListOfDefs("special_params")) {
1242 unsigned Index = sp->getValueAsInt("index");
1243 if (sp->isSubClassOf("IRBuilderAddrParam")) {
1244 AddressArgs.insert(Index);
1245 } else if (sp->isSubClassOf("IRBuilderIntParam")) {
1246 IntegerArgs[Index] = std::string(sp->getValueAsString("type"));
1247 }
1248 }
1249 return std::make_shared<IRBuilderResult>(Op->getValueAsString("prefix"),
1250 Args, AddressArgs, IntegerArgs);
1251 } else if (Op->isSubClassOf("IRIntBase")) {
1252 std::vector<const Type *> ParamTypes;
1253 for (Record *RParam : Op->getValueAsListOfDefs("params"))
1254 ParamTypes.push_back(getType(RParam, Param));
1255 std::string IntName = std::string(Op->getValueAsString("intname"));
1256 if (Op->getValueAsBit("appendKind"))
1257 IntName += "_" + toLetter(cast<ScalarType>(Param)->kind());
1258 return std::make_shared<IRIntrinsicResult>(IntName, ParamTypes, Args);
1259 } else {
1260 PrintFatalError("Unsupported dag node " + Op->getName());
1261 }
1262 }
1263}
1264
1265Result::Ptr EmitterBase::getCodeForDagArg(DagInit *D, unsigned ArgNum,
1266 const Result::Scope &Scope,
1267 const Type *Param) {
1268 Init *Arg = D->getArg(ArgNum);
1269 StringRef Name = D->getArgNameStr(ArgNum);
1270
1271 if (!Name.empty()) {
1272 if (!isa<UnsetInit>(Arg))
1273 PrintFatalError(
1274 "dag operator argument should not have both a value and a name");
1275 auto it = Scope.find(std::string(Name));
1276 if (it == Scope.end())
1277 PrintFatalError("unrecognized variable name '" + Name + "'");
1278 return it->second;
1279 }
1280
1281 // Sometimes the Arg is a bit. Prior to multiclass template argument
1282 // checking, integers would sneak through the bit declaration,
1283 // but now they really are bits.
1284 if (auto *BI = dyn_cast<BitInit>(Arg))
1285 return std::make_shared<IntLiteralResult>(getScalarType("u32"),
1286 BI->getValue());
1287
1288 if (auto *II = dyn_cast<IntInit>(Arg))
1289 return std::make_shared<IntLiteralResult>(getScalarType("u32"),
1290 II->getValue());
1291
1292 if (auto *DI = dyn_cast<DagInit>(Arg))
1293 return getCodeForDag(DI, Scope, Param);
1294
1295 if (auto *DI = dyn_cast<DefInit>(Arg)) {
1296 Record *Rec = DI->getDef();
1297 if (Rec->isSubClassOf("Type")) {
1298 const Type *T = getType(Rec, Param);
1299 return std::make_shared<TypeResult>(T);
1300 }
1301 }
1302
1303 PrintError("bad DAG argument type for code generation");
1304 PrintNote("DAG: " + D->getAsString());
1305 if (TypedInit *Typed = dyn_cast<TypedInit>(Arg))
1306 PrintNote("argument type: " + Typed->getType()->getAsString());
1307 PrintFatalNote("argument number " + Twine(ArgNum) + ": " + Arg->getAsString());
1308}
1309
1310Result::Ptr EmitterBase::getCodeForArg(unsigned ArgNum, const Type *ArgType,
1311 bool Promote, bool Immediate) {
1312 Result::Ptr V = std::make_shared<BuiltinArgResult>(
1313 ArgNum, isa<PointerType>(ArgType), Immediate);
1314
1315 if (Promote) {
1316 if (const auto *ST = dyn_cast<ScalarType>(ArgType)) {
1317 if (ST->isInteger() && ST->sizeInBits() < 32)
1318 V = std::make_shared<IntCastResult>(getScalarType("u32"), V);
1319 } else if (const auto *PT = dyn_cast<PredicateType>(ArgType)) {
1320 V = std::make_shared<IntCastResult>(getScalarType("u32"), V);
1321 V = std::make_shared<IRIntrinsicResult>("arm_mve_pred_i2v",
1322 std::vector<const Type *>{PT},
1323 std::vector<Result::Ptr>{V});
1324 }
1325 }
1326
1327 return V;
1328}
1329
1330ACLEIntrinsic::ACLEIntrinsic(EmitterBase &ME, Record *R, const Type *Param)
1331 : ReturnType(ME.getType(R->getValueAsDef("ret"), Param)) {
1332 // Derive the intrinsic's full name, by taking the name of the
1333 // Tablegen record (or override) and appending the suffix from its
1334 // parameter type. (If the intrinsic is unparametrised, its
1335 // parameter type will be given as Void, which returns the empty
1336 // string for acleSuffix.)
1337 StringRef BaseName =
1338 (R->isSubClassOf("NameOverride") ? R->getValueAsString("basename")
5
'?' condition is false
1339 : R->getName());
1340 StringRef overrideLetter = R->getValueAsString("overrideKindLetter");
1341 FullName =
1342 (Twine(BaseName) + Param->acleSuffix(std::string(overrideLetter))).str();
1343
1344 // Derive the intrinsic's polymorphic name, by removing components from the
1345 // full name as specified by its 'pnt' member ('polymorphic name type'),
1346 // which indicates how many type suffixes to remove, and any other piece of
1347 // the name that should be removed.
1348 Record *PolymorphicNameType = R->getValueAsDef("pnt");
1349 SmallVector<StringRef, 8> NameParts;
1350 StringRef(FullName).split(NameParts, '_');
1351 for (unsigned i = 0, e = PolymorphicNameType->getValueAsInt(
7
Loop condition is false. Execution continues on line 1355
1352 "NumTypeSuffixesToDiscard");
1353 i < e; ++i)
6
Assuming 'i' is >= 'e'
1354 NameParts.pop_back();
1355 if (!PolymorphicNameType->isValueUnset("ExtraSuffixToDiscard")) {
8
Taking true branch
1356 StringRef ExtraSuffix =
1357 PolymorphicNameType->getValueAsString("ExtraSuffixToDiscard");
1358 auto it = NameParts.end();
1359 while (it != NameParts.begin()) {
9
Assuming the condition is false
10
Loop condition is false. Execution continues on line 1367
1360 --it;
1361 if (*it == ExtraSuffix) {
1362 NameParts.erase(it);
1363 break;
1364 }
1365 }
1366 }
1367 ShortName = join(std::begin(NameParts), std::end(NameParts), "_");
1368
1369 BuiltinExtension = R->getValueAsString("builtinExtension");
1370
1371 PolymorphicOnly = R->getValueAsBit("polymorphicOnly");
1372 NonEvaluating = R->getValueAsBit("nonEvaluating");
1373 HeaderOnly = R->getValueAsBit("headerOnly");
1374
1375 // Process the intrinsic's argument list.
1376 DagInit *ArgsDag = R->getValueAsDag("args");
1377 Result::Scope Scope;
1378 for (unsigned i = 0, e = ArgsDag->getNumArgs(); i < e; ++i) {
11
Assuming 'i' is < 'e'
12
Loop condition is true. Entering loop body
1379 Init *TypeInit = ArgsDag->getArg(i);
1380
1381 bool Promote = true;
1382 if (auto TypeDI
13.1
'TypeDI' is non-null
13.1
'TypeDI' is non-null
13.1
'TypeDI' is non-null
= dyn_cast<DefInit>(TypeInit))
13
Assuming 'TypeInit' is a 'CastReturnType'
14
Taking true branch
1383 if (TypeDI->getDef()->isSubClassOf("unpromoted"))
15
Taking false branch
1384 Promote = false;
1385
1386 // Work out the type of the argument, for use in the function prototype in
1387 // the header file.
1388 const Type *ArgType = ME.getType(TypeInit, Param);
1389 ArgTypes.push_back(ArgType);
1390
1391 // If the argument is a subclass of Immediate, record the details about
1392 // what values it can take, for Sema checking.
1393 bool Immediate = false;
1394 if (auto TypeDI
16.1
'TypeDI' is non-null
16.1
'TypeDI' is non-null
16.1
'TypeDI' is non-null
= dyn_cast<DefInit>(TypeInit)) {
16
'TypeInit' is a 'DefInit'
17
Taking true branch
1395 Record *TypeRec = TypeDI->getDef();
1396 if (TypeRec->isSubClassOf("Immediate")) {
18
Taking true branch
1397 Immediate = true;
1398
1399 Record *Bounds = TypeRec->getValueAsDef("bounds");
1400 ImmediateArg &IA = ImmediateArgs[i];
1401 if (Bounds->isSubClassOf("IB_ConstRange")) {
19
Taking false branch
1402 IA.boundsType = ImmediateArg::BoundsType::ExplicitRange;
1403 IA.i1 = Bounds->getValueAsInt("lo");
1404 IA.i2 = Bounds->getValueAsInt("hi");
1405 } else if (Bounds->getName() == "IB_UEltValue") {
20
Assuming the condition is false
21
Taking false branch
1406 IA.boundsType = ImmediateArg::BoundsType::UInt;
1407 IA.i1 = Param->sizeInBits();
1408 } else if (Bounds->getName() == "IB_LaneIndex") {
22
Assuming the condition is true
23
Taking true branch
1409 IA.boundsType = ImmediateArg::BoundsType::ExplicitRange;
1410 IA.i1 = 0;
1411 IA.i2 = 128 / Param->sizeInBits() - 1;
24
Calling 'VoidType::sizeInBits'
26
Returning from 'VoidType::sizeInBits'
27
Division by zero
1412 } else if (Bounds->isSubClassOf("IB_EltBit")) {
1413 IA.boundsType = ImmediateArg::BoundsType::ExplicitRange;
1414 IA.i1 = Bounds->getValueAsInt("base");
1415 const Type *T = ME.getType(Bounds->getValueAsDef("type"), Param);
1416 IA.i2 = IA.i1 + T->sizeInBits() - 1;
1417 } else {
1418 PrintFatalError("unrecognised ImmediateBounds subclass");
1419 }
1420
1421 IA.ArgType = ArgType;
1422
1423 if (!TypeRec->isValueUnset("extra")) {
1424 IA.ExtraCheckType = TypeRec->getValueAsString("extra");
1425 if (!TypeRec->isValueUnset("extraarg"))
1426 IA.ExtraCheckArgs = TypeRec->getValueAsString("extraarg");
1427 }
1428 }
1429 }
1430
1431 // The argument will usually have a name in the arguments dag, which goes
1432 // into the variable-name scope that the code gen will refer to.
1433 StringRef ArgName = ArgsDag->getArgNameStr(i);
1434 if (!ArgName.empty())
1435 Scope[std::string(ArgName)] =
1436 ME.getCodeForArg(i, ArgType, Promote, Immediate);
1437 }
1438
1439 // Finally, go through the codegen dag and translate it into a Result object
1440 // (with an arbitrary DAG of depended-on Results hanging off it).
1441 DagInit *CodeDag = R->getValueAsDag("codegen");
1442 Record *MainOp = cast<DefInit>(CodeDag->getOperator())->getDef();
1443 if (MainOp->isSubClassOf("CustomCodegen")) {
1444 // Or, if it's the special case of CustomCodegen, just accumulate
1445 // a list of parameters we're going to assign to variables before
1446 // breaking from the loop.
1447 CustomCodeGenArgs["CustomCodeGenType"] =
1448 (Twine("CustomCodeGen::") + MainOp->getValueAsString("type")).str();
1449 for (unsigned i = 0, e = CodeDag->getNumArgs(); i < e; ++i) {
1450 StringRef Name = CodeDag->getArgNameStr(i);
1451 if (Name.empty()) {
1452 PrintFatalError("Operands to CustomCodegen should have names");
1453 } else if (auto *II = dyn_cast<IntInit>(CodeDag->getArg(i))) {
1454 CustomCodeGenArgs[std::string(Name)] = itostr(II->getValue());
1455 } else if (auto *SI = dyn_cast<StringInit>(CodeDag->getArg(i))) {
1456 CustomCodeGenArgs[std::string(Name)] = std::string(SI->getValue());
1457 } else {
1458 PrintFatalError("Operands to CustomCodegen should be integers");
1459 }
1460 }
1461 } else {
1462 Code = ME.getCodeForDag(CodeDag, Scope, Param);
1463 }
1464}
1465
1466EmitterBase::EmitterBase(RecordKeeper &Records) {
1467 // Construct the whole EmitterBase.
1468
1469 // First, look up all the instances of PrimitiveType. This gives us the list
1470 // of vector typedefs we have to put in arm_mve.h, and also allows us to
1471 // collect all the useful ScalarType instances into a big list so that we can
1472 // use it for operations such as 'find the unsigned version of this signed
1473 // integer type'.
1474 for (Record *R : Records.getAllDerivedDefinitions("PrimitiveType"))
1475 ScalarTypes[std::string(R->getName())] = std::make_unique<ScalarType>(R);
1476
1477 // Now go through the instances of Intrinsic, and for each one, iterate
1478 // through its list of type parameters making an ACLEIntrinsic for each one.
1479 for (Record *R : Records.getAllDerivedDefinitions("Intrinsic")) {
1480 for (Record *RParam : R->getValueAsListOfDefs("params")) {
1481 const Type *Param = getType(RParam, getVoidType());
1482 auto Intrinsic = std::make_unique<ACLEIntrinsic>(*this, R, Param);
3
Calling 'make_unique<(anonymous namespace)::ACLEIntrinsic, (anonymous namespace)::EmitterBase &, llvm::Record *&, const (anonymous namespace)::Type *&>'
1483 ACLEIntrinsics[Intrinsic->fullName()] = std::move(Intrinsic);
1484 }
1485 }
1486}
1487
1488/// A wrapper on raw_string_ostream that contains its own buffer rather than
1489/// having to point it at one elsewhere. (In other words, it works just like
1490/// std::ostringstream; also, this makes it convenient to declare a whole array
1491/// of them at once.)
1492///
1493/// We have to set this up using multiple inheritance, to ensure that the
1494/// string member has been constructed before raw_string_ostream's constructor
1495/// is given a pointer to it.
1496class string_holder {
1497protected:
1498 std::string S;
1499};
1500class raw_self_contained_string_ostream : private string_holder,
1501 public raw_string_ostream {
1502public:
1503 raw_self_contained_string_ostream() : raw_string_ostream(S) {}
1504};
1505
1506const char LLVMLicenseHeader[] =
1507 " *\n"
1508 " *\n"
1509 " * Part of the LLVM Project, under the Apache License v2.0 with LLVM"
1510 " Exceptions.\n"
1511 " * See https://llvm.org/LICENSE.txt for license information.\n"
1512 " * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n"
1513 " *\n"
1514 " *===-----------------------------------------------------------------"
1515 "------===\n"
1516 " */\n"
1517 "\n";
1518
1519// Machinery for the grouping of intrinsics by similar codegen.
1520//
1521// The general setup is that 'MergeableGroup' stores the things that a set of
1522// similarly shaped intrinsics have in common: the text of their code
1523// generation, and the number and type of their parameter variables.
1524// MergeableGroup is the key in a std::map whose value is a set of
1525// OutputIntrinsic, which stores the ways in which a particular intrinsic
1526// specializes the MergeableGroup's generic description: the function name and
1527// the _values_ of the parameter variables.
1528
1529struct ComparableStringVector : std::vector<std::string> {
1530 // Infrastructure: a derived class of vector<string> which comes with an
1531 // ordering, so that it can be used as a key in maps and an element in sets.
1532 // There's no requirement on the ordering beyond being deterministic.
1533 bool operator<(const ComparableStringVector &rhs) const {
1534 if (size() != rhs.size())
1535 return size() < rhs.size();
1536 for (size_t i = 0, e = size(); i < e; ++i)
1537 if ((*this)[i] != rhs[i])
1538 return (*this)[i] < rhs[i];
1539 return false;
1540 }
1541};
1542
1543struct OutputIntrinsic {
1544 const ACLEIntrinsic *Int;
1545 std::string Name;
1546 ComparableStringVector ParamValues;
1547 bool operator<(const OutputIntrinsic &rhs) const {
1548 if (Name != rhs.Name)
1549 return Name < rhs.Name;
1550 return ParamValues < rhs.ParamValues;
1551 }
1552};
1553struct MergeableGroup {
1554 std::string Code;
1555 ComparableStringVector ParamTypes;
1556 bool operator<(const MergeableGroup &rhs) const {
1557 if (Code != rhs.Code)
1558 return Code < rhs.Code;
1559 return ParamTypes < rhs.ParamTypes;
1560 }
1561};
1562
1563void EmitterBase::EmitBuiltinCG(raw_ostream &OS) {
1564 // Pass 1: generate code for all the intrinsics as if every type or constant
1565 // that can possibly be abstracted out into a parameter variable will be.
1566 // This identifies the sets of intrinsics we'll group together into a single
1567 // piece of code generation.
1568
1569 std::map<MergeableGroup, std::set<OutputIntrinsic>> MergeableGroupsPrelim;
1570
1571 for (const auto &kv : ACLEIntrinsics) {
1572 const ACLEIntrinsic &Int = *kv.second;
1573 if (Int.headerOnly())
1574 continue;
1575
1576 MergeableGroup MG;
1577 OutputIntrinsic OI;
1578
1579 OI.Int = &Int;
1580 OI.Name = Int.fullName();
1581 CodeGenParamAllocator ParamAllocPrelim{&MG.ParamTypes, &OI.ParamValues};
1582 raw_string_ostream OS(MG.Code);
1583 Int.genCode(OS, ParamAllocPrelim, 1);
1584 OS.flush();
1585
1586 MergeableGroupsPrelim[MG].insert(OI);
1587 }
1588
1589 // Pass 2: for each of those groups, optimize the parameter variable set by
1590 // eliminating 'parameters' that are the same for all intrinsics in the
1591 // group, and merging together pairs of parameter variables that take the
1592 // same values as each other for all intrinsics in the group.
1593
1594 std::map<MergeableGroup, std::set<OutputIntrinsic>> MergeableGroups;
1595
1596 for (const auto &kv : MergeableGroupsPrelim) {
1597 const MergeableGroup &MG = kv.first;
1598 std::vector<int> ParamNumbers;
1599 std::map<ComparableStringVector, int> ParamNumberMap;
1600
1601 // Loop over the parameters for this group.
1602 for (size_t i = 0, e = MG.ParamTypes.size(); i < e; ++i) {
1603 // Is this parameter the same for all intrinsics in the group?
1604 const OutputIntrinsic &OI_first = *kv.second.begin();
1605 bool Constant = all_of(kv.second, [&](const OutputIntrinsic &OI) {
1606 return OI.ParamValues[i] == OI_first.ParamValues[i];
1607 });
1608
1609 // If so, record it as -1, meaning 'no parameter variable needed'. Then
1610 // the corresponding call to allocParam in pass 2 will not generate a
1611 // variable at all, and just use the value inline.
1612 if (Constant) {
1613 ParamNumbers.push_back(-1);
1614 continue;
1615 }
1616
1617 // Otherwise, make a list of the values this parameter takes for each
1618 // intrinsic, and see if that value vector matches anything we already
1619 // have. We also record the parameter type, so that we don't accidentally
1620 // match up two parameter variables with different types. (Not that
1621 // there's much chance of them having textually equivalent values, but in
1622 // _principle_ it could happen.)
1623 ComparableStringVector key;
1624 key.push_back(MG.ParamTypes[i]);
1625 for (const auto &OI : kv.second)
1626 key.push_back(OI.ParamValues[i]);
1627
1628 auto Found = ParamNumberMap.find(key);
1629 if (Found != ParamNumberMap.end()) {
1630 // Yes, an existing parameter variable can be reused for this.
1631 ParamNumbers.push_back(Found->second);
1632 continue;
1633 }
1634
1635 // No, we need a new parameter variable.
1636 int ExistingIndex = ParamNumberMap.size();
1637 ParamNumberMap[key] = ExistingIndex;
1638 ParamNumbers.push_back(ExistingIndex);
1639 }
1640
1641 // Now we're ready to do the pass 2 code generation, which will emit the
1642 // reduced set of parameter variables we've just worked out.
1643
1644 for (const auto &OI_prelim : kv.second) {
1645 const ACLEIntrinsic *Int = OI_prelim.Int;
1646
1647 MergeableGroup MG;
1648 OutputIntrinsic OI;
1649
1650 OI.Int = OI_prelim.Int;
1651 OI.Name = OI_prelim.Name;
1652 CodeGenParamAllocator ParamAlloc{&MG.ParamTypes, &OI.ParamValues,
1653 &ParamNumbers};
1654 raw_string_ostream OS(MG.Code);
1655 Int->genCode(OS, ParamAlloc, 2);
1656 OS.flush();
1657
1658 MergeableGroups[MG].insert(OI);
1659 }
1660 }
1661
1662 // Output the actual C++ code.
1663
1664 for (const auto &kv : MergeableGroups) {
1665 const MergeableGroup &MG = kv.first;
1666
1667 // List of case statements in the main switch on BuiltinID, and an open
1668 // brace.
1669 const char *prefix = "";
1670 for (const auto &OI : kv.second) {
1671 OS << prefix << "case ARM::BI__builtin_arm_" << OI.Int->builtinExtension()
1672 << "_" << OI.Name << ":";
1673
1674 prefix = "\n";
1675 }
1676 OS << " {\n";
1677
1678 if (!MG.ParamTypes.empty()) {
1679 // If we've got some parameter variables, then emit their declarations...
1680 for (size_t i = 0, e = MG.ParamTypes.size(); i < e; ++i) {
1681 StringRef Type = MG.ParamTypes[i];
1682 OS << " " << Type;
1683 if (!Type.endswith("*"))
1684 OS << " ";
1685 OS << " Param" << utostr(i) << ";\n";
1686 }
1687
1688 // ... and an inner switch on BuiltinID that will fill them in with each
1689 // individual intrinsic's values.
1690 OS << " switch (BuiltinID) {\n";
1691 for (const auto &OI : kv.second) {
1692 OS << " case ARM::BI__builtin_arm_" << OI.Int->builtinExtension()
1693 << "_" << OI.Name << ":\n";
1694 for (size_t i = 0, e = MG.ParamTypes.size(); i < e; ++i)
1695 OS << " Param" << utostr(i) << " = " << OI.ParamValues[i] << ";\n";
1696 OS << " break;\n";
1697 }
1698 OS << " }\n";
1699 }
1700
1701 // And finally, output the code, and close the outer pair of braces. (The
1702 // code will always end with a 'return' statement, so we need not insert a
1703 // 'break' here.)
1704 OS << MG.Code << "}\n";
1705 }
1706}
1707
1708void EmitterBase::EmitBuiltinAliases(raw_ostream &OS) {
1709 // Build a sorted table of:
1710 // - intrinsic id number
1711 // - full name
1712 // - polymorphic name or -1
1713 StringToOffsetTable StringTable;
1714 OS << "static const IntrinToName MapData[] = {\n";
1715 for (const auto &kv : ACLEIntrinsics) {
1716 const ACLEIntrinsic &Int = *kv.second;
1717 if (Int.headerOnly())
1718 continue;
1719 int32_t ShortNameOffset =
1720 Int.polymorphic() ? StringTable.GetOrAddStringOffset(Int.shortName())
1721 : -1;
1722 OS << " { ARM::BI__builtin_arm_" << Int.builtinExtension() << "_"
1723 << Int.fullName() << ", "
1724 << StringTable.GetOrAddStringOffset(Int.fullName()) << ", "
1725 << ShortNameOffset << "},\n";
1726 }
1727 OS << "};\n\n";
1728
1729 OS << "ArrayRef<IntrinToName> Map(MapData);\n\n";
1730
1731 OS << "static const char IntrinNames[] = {\n";
1732 StringTable.EmitString(OS);
1733 OS << "};\n\n";
1734}
1735
1736void EmitterBase::GroupSemaChecks(
1737 std::map<std::string, std::set<std::string>> &Checks) {
1738 for (const auto &kv : ACLEIntrinsics) {
1739 const ACLEIntrinsic &Int = *kv.second;
1740 if (Int.headerOnly())
1741 continue;
1742 std::string Check = Int.genSema();
1743 if (!Check.empty())
1744 Checks[Check].insert(Int.fullName());
1745 }
1746}
1747
1748// -----------------------------------------------------------------------------
1749// The class used for generating arm_mve.h and related Clang bits
1750//
1751
1752class MveEmitter : public EmitterBase {
1753public:
1754 MveEmitter(RecordKeeper &Records) : EmitterBase(Records){};
1755 void EmitHeader(raw_ostream &OS) override;
1756 void EmitBuiltinDef(raw_ostream &OS) override;
1757 void EmitBuiltinSema(raw_ostream &OS) override;
1758};
1759
1760void MveEmitter::EmitHeader(raw_ostream &OS) {
1761 // Accumulate pieces of the header file that will be enabled under various
1762 // different combinations of #ifdef. The index into parts[] is made up of
1763 // the following bit flags.
1764 constexpr unsigned Float = 1;
1765 constexpr unsigned UseUserNamespace = 2;
1766
1767 constexpr unsigned NumParts = 4;
1768 raw_self_contained_string_ostream parts[NumParts];
1769
1770 // Write typedefs for all the required vector types, and a few scalar
1771 // types that don't already have the name we want them to have.
1772
1773 parts[0] << "typedef uint16_t mve_pred16_t;\n";
1774 parts[Float] << "typedef __fp16 float16_t;\n"
1775 "typedef float float32_t;\n";
1776 for (const auto &kv : ScalarTypes) {
1777 const ScalarType *ST = kv.second.get();
1778 if (ST->hasNonstandardName())
1779 continue;
1780 raw_ostream &OS = parts[ST->requiresFloat() ? Float : 0];
1781 const VectorType *VT = getVectorType(ST);
1782
1783 OS << "typedef __attribute__((__neon_vector_type__(" << VT->lanes()
1784 << "), __clang_arm_mve_strict_polymorphism)) " << ST->cName() << " "
1785 << VT->cName() << ";\n";
1786
1787 // Every vector type also comes with a pair of multi-vector types for
1788 // the VLD2 and VLD4 instructions.
1789 for (unsigned n = 2; n <= 4; n += 2) {
1790 const MultiVectorType *MT = getMultiVectorType(n, VT);
1791 OS << "typedef struct { " << VT->cName() << " val[" << n << "]; } "
1792 << MT->cName() << ";\n";
1793 }
1794 }
1795 parts[0] << "\n";
1796 parts[Float] << "\n";
1797
1798 // Write declarations for all the intrinsics.
1799
1800 for (const auto &kv : ACLEIntrinsics) {
1801 const ACLEIntrinsic &Int = *kv.second;
1802
1803 // We generate each intrinsic twice, under its full unambiguous
1804 // name and its shorter polymorphic name (if the latter exists).
1805 for (bool Polymorphic : {false, true}) {
1806 if (Polymorphic && !Int.polymorphic())
1807 continue;
1808 if (!Polymorphic && Int.polymorphicOnly())
1809 continue;
1810
1811 // We also generate each intrinsic under a name like __arm_vfooq
1812 // (which is in C language implementation namespace, so it's
1813 // safe to define in any conforming user program) and a shorter
1814 // one like vfooq (which is in user namespace, so a user might
1815 // reasonably have used it for something already). If so, they
1816 // can #define __ARM_MVE_PRESERVE_USER_NAMESPACE before
1817 // including the header, which will suppress the shorter names
1818 // and leave only the implementation-namespace ones. Then they
1819 // have to write __arm_vfooq everywhere, of course.
1820
1821 for (bool UserNamespace : {false, true}) {
1822 raw_ostream &OS = parts[(Int.requiresFloat() ? Float : 0) |
1823 (UserNamespace ? UseUserNamespace : 0)];
1824
1825 // Make the name of the function in this declaration.
1826
1827 std::string FunctionName =
1828 Polymorphic ? Int.shortName() : Int.fullName();
1829 if (!UserNamespace)
1830 FunctionName = "__arm_" + FunctionName;
1831
1832 // Make strings for the types involved in the function's
1833 // prototype.
1834
1835 std::string RetTypeName = Int.returnType()->cName();
1836 if (!StringRef(RetTypeName).endswith("*"))
1837 RetTypeName += " ";
1838
1839 std::vector<std::string> ArgTypeNames;
1840 for (const Type *ArgTypePtr : Int.argTypes())
1841 ArgTypeNames.push_back(ArgTypePtr->cName());
1842 std::string ArgTypesString =
1843 join(std::begin(ArgTypeNames), std::end(ArgTypeNames), ", ");
1844
1845 // Emit the actual declaration. All these functions are
1846 // declared 'static inline' without a body, which is fine
1847 // provided clang recognizes them as builtins, and has the
1848 // effect that this type signature is used in place of the one
1849 // that Builtins.def didn't provide. That's how we can get
1850 // structure types that weren't defined until this header was
1851 // included to be part of the type signature of a builtin that
1852 // was known to clang already.
1853 //
1854 // The declarations use __attribute__(__clang_arm_builtin_alias),
1855 // so that each function declared will be recognized as the
1856 // appropriate MVE builtin in spite of its user-facing name.
1857 //
1858 // (That's better than making them all wrapper functions,
1859 // partly because it avoids any compiler error message citing
1860 // the wrapper function definition instead of the user's code,
1861 // and mostly because some MVE intrinsics have arguments
1862 // required to be compile-time constants, and that property
1863 // can't be propagated through a wrapper function. It can be
1864 // propagated through a macro, but macros can't be overloaded
1865 // on argument types very easily - you have to use _Generic,
1866 // which makes error messages very confusing when the user
1867 // gets it wrong.)
1868 //
1869 // Finally, the polymorphic versions of the intrinsics are
1870 // also defined with __attribute__(overloadable), so that when
1871 // the same name is defined with several type signatures, the
1872 // right thing happens. Each one of the overloaded
1873 // declarations is given a different builtin id, which
1874 // has exactly the effect we want: first clang resolves the
1875 // overload to the right function, then it knows which builtin
1876 // it's referring to, and then the Sema checking for that
1877 // builtin can check further things like the constant
1878 // arguments.
1879 //
1880 // One more subtlety is the newline just before the return
1881 // type name. That's a cosmetic tweak to make the error
1882 // messages legible if the user gets the types wrong in a call
1883 // to a polymorphic function: this way, clang will print just
1884 // the _final_ line of each declaration in the header, to show
1885 // the type signatures that would have been legal. So all the
1886 // confusing machinery with __attribute__ is left out of the
1887 // error message, and the user sees something that's more or
1888 // less self-documenting: "here's a list of actually readable
1889 // type signatures for vfooq(), and here's why each one didn't
1890 // match your call".
1891
1892 OS << "static __inline__ __attribute__(("
1893 << (Polymorphic ? "__overloadable__, " : "")
1894 << "__clang_arm_builtin_alias(__builtin_arm_mve_" << Int.fullName()
1895 << ")))\n"
1896 << RetTypeName << FunctionName << "(" << ArgTypesString << ");\n";
1897 }
1898 }
1899 }
1900 for (auto &part : parts)
1901 part << "\n";
1902
1903 // Now we've finished accumulating bits and pieces into the parts[] array.
1904 // Put it all together to write the final output file.
1905
1906 OS << "/*===---- arm_mve.h - ARM MVE intrinsics "
1907 "-----------------------------------===\n"
1908 << LLVMLicenseHeader
1909 << "#ifndef __ARM_MVE_H\n"
1910 "#define __ARM_MVE_H\n"
1911 "\n"
1912 "#if !__ARM_FEATURE_MVE\n"
1913 "#error \"MVE support not enabled\"\n"
1914 "#endif\n"
1915 "\n"
1916 "#include <stdint.h>\n"
1917 "\n"
1918 "#ifdef __cplusplus\n"
1919 "extern \"C\" {\n"
1920 "#endif\n"
1921 "\n";
1922
1923 for (size_t i = 0; i < NumParts; ++i) {
1924 std::vector<std::string> conditions;
1925 if (i & Float)
1926 conditions.push_back("(__ARM_FEATURE_MVE & 2)");
1927 if (i & UseUserNamespace)
1928 conditions.push_back("(!defined __ARM_MVE_PRESERVE_USER_NAMESPACE)");
1929
1930 std::string condition =
1931 join(std::begin(conditions), std::end(conditions), " && ");
1932 if (!condition.empty())
1933 OS << "#if " << condition << "\n\n";
1934 OS << parts[i].str();
1935 if (!condition.empty())
1936 OS << "#endif /* " << condition << " */\n\n";
1937 }
1938
1939 OS << "#ifdef __cplusplus\n"
1940 "} /* extern \"C\" */\n"
1941 "#endif\n"
1942 "\n"
1943 "#endif /* __ARM_MVE_H */\n";
1944}
1945
1946void MveEmitter::EmitBuiltinDef(raw_ostream &OS) {
1947 for (const auto &kv : ACLEIntrinsics) {
1948 const ACLEIntrinsic &Int = *kv.second;
1949 OS << "BUILTIN(__builtin_arm_mve_" << Int.fullName()
1950 << ", \"\", \"n\")\n";
1951 }
1952
1953 std::set<std::string> ShortNamesSeen;
1954
1955 for (const auto &kv : ACLEIntrinsics) {
1956 const ACLEIntrinsic &Int = *kv.second;
1957 if (Int.polymorphic()) {
1958 StringRef Name = Int.shortName();
1959 if (ShortNamesSeen.find(std::string(Name)) == ShortNamesSeen.end()) {
1960 OS << "BUILTIN(__builtin_arm_mve_" << Name << ", \"vi.\", \"nt";
1961 if (Int.nonEvaluating())
1962 OS << "u"; // indicate that this builtin doesn't evaluate its args
1963 OS << "\")\n";
1964 ShortNamesSeen.insert(std::string(Name));
1965 }
1966 }
1967 }
1968}
1969
1970void MveEmitter::EmitBuiltinSema(raw_ostream &OS) {
1971 std::map<std::string, std::set<std::string>> Checks;
1972 GroupSemaChecks(Checks);
1973
1974 for (const auto &kv : Checks) {
1975 for (StringRef Name : kv.second)
1976 OS << "case ARM::BI__builtin_arm_mve_" << Name << ":\n";
1977 OS << " return " << kv.first;
1978 }
1979}
1980
1981// -----------------------------------------------------------------------------
1982// Class that describes an ACLE intrinsic implemented as a macro.
1983//
1984// This class is used when the intrinsic is polymorphic in 2 or 3 types, but we
1985// want to avoid a combinatorial explosion by reinterpreting the arguments to
1986// fixed types.
1987
1988class FunctionMacro {
1989 std::vector<StringRef> Params;
1990 StringRef Definition;
1991
1992public:
1993 FunctionMacro(const Record &R);
1994
1995 const std::vector<StringRef> &getParams() const { return Params; }
1996 StringRef getDefinition() const { return Definition; }
1997};
1998
1999FunctionMacro::FunctionMacro(const Record &R) {
2000 Params = R.getValueAsListOfStrings("params");
2001 Definition = R.getValueAsString("definition");
2002}
2003
2004// -----------------------------------------------------------------------------
2005// The class used for generating arm_cde.h and related Clang bits
2006//
2007
2008class CdeEmitter : public EmitterBase {
2009 std::map<StringRef, FunctionMacro> FunctionMacros;
2010
2011public:
2012 CdeEmitter(RecordKeeper &Records);
2013 void EmitHeader(raw_ostream &OS) override;
2014 void EmitBuiltinDef(raw_ostream &OS) override;
2015 void EmitBuiltinSema(raw_ostream &OS) override;
2016};
2017
2018CdeEmitter::CdeEmitter(RecordKeeper &Records) : EmitterBase(Records) {
2
Calling constructor for 'EmitterBase'
2019 for (Record *R : Records.getAllDerivedDefinitions("FunctionMacro"))
2020 FunctionMacros.emplace(R->getName(), FunctionMacro(*R));
2021}
2022
2023void CdeEmitter::EmitHeader(raw_ostream &OS) {
2024 // Accumulate pieces of the header file that will be enabled under various
2025 // different combinations of #ifdef. The index into parts[] is one of the
2026 // following:
2027 constexpr unsigned None = 0;
2028 constexpr unsigned MVE = 1;
2029 constexpr unsigned MVEFloat = 2;
2030
2031 constexpr unsigned NumParts = 3;
2032 raw_self_contained_string_ostream parts[NumParts];
2033
2034 // Write typedefs for all the required vector types, and a few scalar
2035 // types that don't already have the name we want them to have.
2036
2037 parts[MVE] << "typedef uint16_t mve_pred16_t;\n";
2038 parts[MVEFloat] << "typedef __fp16 float16_t;\n"
2039 "typedef float float32_t;\n";
2040 for (const auto &kv : ScalarTypes) {
2041 const ScalarType *ST = kv.second.get();
2042 if (ST->hasNonstandardName())
2043 continue;
2044 // We don't have float64x2_t
2045 if (ST->kind() == ScalarTypeKind::Float && ST->sizeInBits() == 64)
2046 continue;
2047 raw_ostream &OS = parts[ST->requiresFloat() ? MVEFloat : MVE];
2048 const VectorType *VT = getVectorType(ST);
2049
2050 OS << "typedef __attribute__((__neon_vector_type__(" << VT->lanes()
2051 << "), __clang_arm_mve_strict_polymorphism)) " << ST->cName() << " "
2052 << VT->cName() << ";\n";
2053 }
2054 parts[MVE] << "\n";
2055 parts[MVEFloat] << "\n";
2056
2057 // Write declarations for all the intrinsics.
2058
2059 for (const auto &kv : ACLEIntrinsics) {
2060 const ACLEIntrinsic &Int = *kv.second;
2061
2062 // We generate each intrinsic twice, under its full unambiguous
2063 // name and its shorter polymorphic name (if the latter exists).
2064 for (bool Polymorphic : {false, true}) {
2065 if (Polymorphic && !Int.polymorphic())
2066 continue;
2067 if (!Polymorphic && Int.polymorphicOnly())
2068 continue;
2069
2070 raw_ostream &OS =
2071 parts[Int.requiresFloat() ? MVEFloat
2072 : Int.requiresMVE() ? MVE : None];
2073
2074 // Make the name of the function in this declaration.
2075 std::string FunctionName =
2076 "__arm_" + (Polymorphic ? Int.shortName() : Int.fullName());
2077
2078 // Make strings for the types involved in the function's
2079 // prototype.
2080 std::string RetTypeName = Int.returnType()->cName();
2081 if (!StringRef(RetTypeName).endswith("*"))
2082 RetTypeName += " ";
2083
2084 std::vector<std::string> ArgTypeNames;
2085 for (const Type *ArgTypePtr : Int.argTypes())
2086 ArgTypeNames.push_back(ArgTypePtr->cName());
2087 std::string ArgTypesString =
2088 join(std::begin(ArgTypeNames), std::end(ArgTypeNames), ", ");
2089
2090 // Emit the actual declaration. See MveEmitter::EmitHeader for detailed
2091 // comments
2092 OS << "static __inline__ __attribute__(("
2093 << (Polymorphic ? "__overloadable__, " : "")
2094 << "__clang_arm_builtin_alias(__builtin_arm_" << Int.builtinExtension()
2095 << "_" << Int.fullName() << ")))\n"
2096 << RetTypeName << FunctionName << "(" << ArgTypesString << ");\n";
2097 }
2098 }
2099
2100 for (const auto &kv : FunctionMacros) {
2101 StringRef Name = kv.first;
2102 const FunctionMacro &FM = kv.second;
2103
2104 raw_ostream &OS = parts[MVE];
2105 OS << "#define "
2106 << "__arm_" << Name << "(" << join(FM.getParams(), ", ") << ") "
2107 << FM.getDefinition() << "\n";
2108 }
2109
2110 for (auto &part : parts)
2111 part << "\n";
2112
2113 // Now we've finished accumulating bits and pieces into the parts[] array.
2114 // Put it all together to write the final output file.
2115
2116 OS << "/*===---- arm_cde.h - ARM CDE intrinsics "
2117 "-----------------------------------===\n"
2118 << LLVMLicenseHeader
2119 << "#ifndef __ARM_CDE_H\n"
2120 "#define __ARM_CDE_H\n"
2121 "\n"
2122 "#if !__ARM_FEATURE_CDE\n"
2123 "#error \"CDE support not enabled\"\n"
2124 "#endif\n"
2125 "\n"
2126 "#include <stdint.h>\n"
2127 "\n"
2128 "#ifdef __cplusplus\n"
2129 "extern \"C\" {\n"
2130 "#endif\n"
2131 "\n";
2132
2133 for (size_t i = 0; i < NumParts; ++i) {
2134 std::string condition;
2135 if (i == MVEFloat)
2136 condition = "__ARM_FEATURE_MVE & 2";
2137 else if (i == MVE)
2138 condition = "__ARM_FEATURE_MVE";
2139
2140 if (!condition.empty())
2141 OS << "#if " << condition << "\n\n";
2142 OS << parts[i].str();
2143 if (!condition.empty())
2144 OS << "#endif /* " << condition << " */\n\n";
2145 }
2146
2147 OS << "#ifdef __cplusplus\n"
2148 "} /* extern \"C\" */\n"
2149 "#endif\n"
2150 "\n"
2151 "#endif /* __ARM_CDE_H */\n";
2152}
2153
2154void CdeEmitter::EmitBuiltinDef(raw_ostream &OS) {
2155 for (const auto &kv : ACLEIntrinsics) {
2156 if (kv.second->headerOnly())
2157 continue;
2158 const ACLEIntrinsic &Int = *kv.second;
2159 OS << "BUILTIN(__builtin_arm_cde_" << Int.fullName()
2160 << ", \"\", \"ncU\")\n";
2161 }
2162}
2163
2164void CdeEmitter::EmitBuiltinSema(raw_ostream &OS) {
2165 std::map<std::string, std::set<std::string>> Checks;
2166 GroupSemaChecks(Checks);
2167
2168 for (const auto &kv : Checks) {
2169 for (StringRef Name : kv.second)
2170 OS << "case ARM::BI__builtin_arm_cde_" << Name << ":\n";
2171 OS << " Err = " << kv.first << " break;\n";
2172 }
2173}
2174
2175} // namespace
2176
2177namespace clang {
2178
2179// MVE
2180
2181void EmitMveHeader(RecordKeeper &Records, raw_ostream &OS) {
2182 MveEmitter(Records).EmitHeader(OS);
2183}
2184
2185void EmitMveBuiltinDef(RecordKeeper &Records, raw_ostream &OS) {
2186 MveEmitter(Records).EmitBuiltinDef(OS);
2187}
2188
2189void EmitMveBuiltinSema(RecordKeeper &Records, raw_ostream &OS) {
2190 MveEmitter(Records).EmitBuiltinSema(OS);
2191}
2192
2193void EmitMveBuiltinCG(RecordKeeper &Records, raw_ostream &OS) {
2194 MveEmitter(Records).EmitBuiltinCG(OS);
2195}
2196
2197void EmitMveBuiltinAliases(RecordKeeper &Records, raw_ostream &OS) {
2198 MveEmitter(Records).EmitBuiltinAliases(OS);
2199}
2200
2201// CDE
2202
2203void EmitCdeHeader(RecordKeeper &Records, raw_ostream &OS) {
2204 CdeEmitter(Records).EmitHeader(OS);
2205}
2206
2207void EmitCdeBuiltinDef(RecordKeeper &Records, raw_ostream &OS) {
2208 CdeEmitter(Records).EmitBuiltinDef(OS);
2209}
2210
2211void EmitCdeBuiltinSema(RecordKeeper &Records, raw_ostream &OS) {
2212 CdeEmitter(Records).EmitBuiltinSema(OS);
2213}
2214
2215void EmitCdeBuiltinCG(RecordKeeper &Records, raw_ostream &OS) {
2216 CdeEmitter(Records).EmitBuiltinCG(OS);
2217}
2218
2219void EmitCdeBuiltinAliases(RecordKeeper &Records, raw_ostream &OS) {
2220 CdeEmitter(Records).EmitBuiltinAliases(OS);
1
Calling constructor for 'CdeEmitter'
2221}
2222
2223} // end namespace clang

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

1// unique_ptr implementation -*- C++ -*-
2
3// Copyright (C) 2008-2020 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#if __cplusplus201703L > 201703L
41# include <compare>
42# include <ostream>
43#endif
44
45namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
46{
47_GLIBCXX_BEGIN_NAMESPACE_VERSION
48
49 /**
50 * @addtogroup pointer_abstractions
51 * @{
52 */
53
54#if _GLIBCXX_USE_DEPRECATED1
55#pragma GCC diagnostic push
56#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
57 template<typename> class auto_ptr;
58#pragma GCC diagnostic pop
59#endif
60
61 /// Primary template of default_delete, used by unique_ptr for single objects
62 template<typename _Tp>
63 struct default_delete
64 {
65 /// Default constructor
66 constexpr default_delete() noexcept = default;
67
68 /** @brief Converting constructor.
69 *
70 * Allows conversion from a deleter for objects of another type, `_Up`,
71 * only if `_Up*` is convertible to `_Tp*`.
72 */
73 template<typename _Up,
74 typename = _Require<is_convertible<_Up*, _Tp*>>>
75 default_delete(const default_delete<_Up>&) noexcept { }
76
77 /// Calls `delete __ptr`
78 void
79 operator()(_Tp* __ptr) const
80 {
81 static_assert(!is_void<_Tp>::value,
82 "can't delete pointer to incomplete type");
83 static_assert(sizeof(_Tp)>0,
84 "can't delete pointer to incomplete type");
85 delete __ptr;
86 }
87 };
88
89 // _GLIBCXX_RESOLVE_LIB_DEFECTS
90 // DR 740 - omit specialization for array objects with a compile time length
91
92 /// Specialization of default_delete for arrays, used by `unique_ptr<T[]>`
93 template<typename _Tp>
94 struct default_delete<_Tp[]>
95 {
96 public:
97 /// Default constructor
98 constexpr default_delete() noexcept = default;
99
100 /** @brief Converting constructor.
101 *
102 * Allows conversion from a deleter for arrays of another type, such as
103 * a const-qualified version of `_Tp`.
104 *
105 * Conversions from types derived from `_Tp` are not allowed because
106 * it is undefined to `delete[]` an array of derived types through a
107 * pointer to the base type.
108 */
109 template<typename _Up,
110 typename = _Require<is_convertible<_Up(*)[], _Tp(*)[]>>>
111 default_delete(const default_delete<_Up[]>&) noexcept { }
112
113 /// Calls `delete[] __ptr`
114 template<typename _Up>
115 typename enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type
116 operator()(_Up* __ptr) const
117 {
118 static_assert(sizeof(_Tp)>0,
119 "can't delete pointer to incomplete type");
120 delete [] __ptr;
121 }
122 };
123
124 /// @cond undocumented
125
126 // Manages the pointer and deleter of a unique_ptr
127 template <typename _Tp, typename _Dp>
128 class __uniq_ptr_impl
129 {
130 template <typename _Up, typename _Ep, typename = void>
131 struct _Ptr
132 {
133 using type = _Up*;
134 };
135
136 template <typename _Up, typename _Ep>
137 struct
138 _Ptr<_Up, _Ep, __void_t<typename remove_reference<_Ep>::type::pointer>>
139 {
140 using type = typename remove_reference<_Ep>::type::pointer;
141 };
142
143 public:
144 using _DeleterConstraint = enable_if<
145 __and_<__not_<is_pointer<_Dp>>,
146 is_default_constructible<_Dp>>::value>;
147
148 using pointer = typename _Ptr<_Tp, _Dp>::type;
149
150 static_assert( !is_rvalue_reference<_Dp>::value,
151 "unique_ptr's deleter type must be a function object type"
152 " or an lvalue reference type" );
153
154 __uniq_ptr_impl() = default;
155 __uniq_ptr_impl(pointer __p) : _M_t() { _M_ptr() = __p; }
156
157 template<typename _Del>
158 __uniq_ptr_impl(pointer __p, _Del&& __d)
159 : _M_t(__p, std::forward<_Del>(__d)) { }
160
161 __uniq_ptr_impl(__uniq_ptr_impl&& __u) noexcept
162 : _M_t(std::move(__u._M_t))
163 { __u._M_ptr() = nullptr; }
164
165 __uniq_ptr_impl& operator=(__uniq_ptr_impl&& __u) noexcept
166 {
167 reset(__u.release());
168 _M_deleter() = std::forward<_Dp>(__u._M_deleter());
169 return *this;
170 }
171
172 pointer& _M_ptr() { return std::get<0>(_M_t); }
173 pointer _M_ptr() const { return std::get<0>(_M_t); }
174 _Dp& _M_deleter() { return std::get<1>(_M_t); }
175 const _Dp& _M_deleter() const { return std::get<1>(_M_t); }
176
177 void reset(pointer __p) noexcept
178 {
179 const pointer __old_p = _M_ptr();
180 _M_ptr() = __p;
181 if (__old_p)
182 _M_deleter()(__old_p);
183 }
184
185 pointer release() noexcept
186 {
187 pointer __p = _M_ptr();
188 _M_ptr() = nullptr;
189 return __p;
190 }
191
192 void
193 swap(__uniq_ptr_impl& __rhs) noexcept
194 {
195 using std::swap;
196 swap(this->_M_ptr(), __rhs._M_ptr());
197 swap(this->_M_deleter(), __rhs._M_deleter());
198 }
199
200 private:
201 tuple<pointer, _Dp> _M_t;
202 };
203
204 // Defines move construction + assignment as either defaulted or deleted.
205 template <typename _Tp, typename _Dp,
206 bool = is_move_constructible<_Dp>::value,
207 bool = is_move_assignable<_Dp>::value>
208 struct __uniq_ptr_data : __uniq_ptr_impl<_Tp, _Dp>
209 {
210 using __uniq_ptr_impl<_Tp, _Dp>::__uniq_ptr_impl;
211 __uniq_ptr_data(__uniq_ptr_data&&) = default;
212 __uniq_ptr_data& operator=(__uniq_ptr_data&&) = default;
213 };
214
215 template <typename _Tp, typename _Dp>
216 struct __uniq_ptr_data<_Tp, _Dp, true, false> : __uniq_ptr_impl<_Tp, _Dp>
217 {
218 using __uniq_ptr_impl<_Tp, _Dp>::__uniq_ptr_impl;
219 __uniq_ptr_data(__uniq_ptr_data&&) = default;
220 __uniq_ptr_data& operator=(__uniq_ptr_data&&) = delete;
221 };
222
223 template <typename _Tp, typename _Dp>
224 struct __uniq_ptr_data<_Tp, _Dp, false, true> : __uniq_ptr_impl<_Tp, _Dp>
225 {
226 using __uniq_ptr_impl<_Tp, _Dp>::__uniq_ptr_impl;
227 __uniq_ptr_data(__uniq_ptr_data&&) = delete;
228 __uniq_ptr_data& operator=(__uniq_ptr_data&&) = default;
229 };
230
231 template <typename _Tp, typename _Dp>
232 struct __uniq_ptr_data<_Tp, _Dp, false, false> : __uniq_ptr_impl<_Tp, _Dp>
233 {
234 using __uniq_ptr_impl<_Tp, _Dp>::__uniq_ptr_impl;
235 __uniq_ptr_data(__uniq_ptr_data&&) = delete;
236 __uniq_ptr_data& operator=(__uniq_ptr_data&&) = delete;
237 };
238 /// @endcond
239
240 /// 20.7.1.2 unique_ptr for single objects.
241 template <typename _Tp, typename _Dp = default_delete<_Tp>>
242 class unique_ptr
243 {
244 template <typename _Up>
245 using _DeleterConstraint =
246 typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type;
247
248 __uniq_ptr_data<_Tp, _Dp> _M_t;
249
250 public:
251 using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer;
252 using element_type = _Tp;
253 using deleter_type = _Dp;
254
255 private:
256 // helper template for detecting a safe conversion from another
257 // unique_ptr
258 template<typename _Up, typename _Ep>
259 using __safe_conversion_up = __and_<
260 is_convertible<typename unique_ptr<_Up, _Ep>::pointer, pointer>,
261 __not_<is_array<_Up>>
262 >;
263
264 public:
265 // Constructors.
266
267 /// Default constructor, creates a unique_ptr that owns nothing.
268 template<typename _Del = _Dp, typename = _DeleterConstraint<_Del>>
269 constexpr unique_ptr() noexcept
270 : _M_t()
271 { }
272
273 /** Takes ownership of a pointer.
274 *
275 * @param __p A pointer to an object of @c element_type
276 *
277 * The deleter will be value-initialized.
278 */
279 template<typename _Del = _Dp, typename = _DeleterConstraint<_Del>>
280 explicit
281 unique_ptr(pointer __p) noexcept
282 : _M_t(__p)
283 { }
284
285 /** Takes ownership of a pointer.
286 *
287 * @param __p A pointer to an object of @c element_type
288 * @param __d A reference to a deleter.
289 *
290 * The deleter will be initialized with @p __d
291 */
292 template<typename _Del = deleter_type,
293 typename = _Require<is_copy_constructible<_Del>>>
294 unique_ptr(pointer __p, const deleter_type& __d) noexcept
295 : _M_t(__p, __d) { }
296
297 /** Takes ownership of a pointer.
298 *
299 * @param __p A pointer to an object of @c element_type
300 * @param __d An rvalue reference to a (non-reference) deleter.
301 *
302 * The deleter will be initialized with @p std::move(__d)
303 */
304 template<typename _Del = deleter_type,
305 typename = _Require<is_move_constructible<_Del>>>
306 unique_ptr(pointer __p,
307 __enable_if_t<!is_lvalue_reference<_Del>::value,
308 _Del&&> __d) noexcept
309 : _M_t(__p, std::move(__d))
310 { }
311
312 template<typename _Del = deleter_type,
313 typename _DelUnref = typename remove_reference<_Del>::type>
314 unique_ptr(pointer,
315 __enable_if_t<is_lvalue_reference<_Del>::value,
316 _DelUnref&&>) = delete;
317
318 /// Creates a unique_ptr that owns nothing.
319 template<typename _Del = _Dp, typename = _DeleterConstraint<_Del>>
320 constexpr unique_ptr(nullptr_t) noexcept
321 : _M_t()
322 { }
323
324 // Move constructors.
325
326 /// Move constructor.
327 unique_ptr(unique_ptr&&) = default;
328
329 /** @brief Converting constructor from another type
330 *
331 * Requires that the pointer owned by @p __u is convertible to the
332 * type of pointer owned by this object, @p __u does not own an array,
333 * and @p __u has a compatible deleter type.
334 */
335 template<typename _Up, typename _Ep, typename = _Require<
336 __safe_conversion_up<_Up, _Ep>,
337 typename conditional<is_reference<_Dp>::value,
338 is_same<_Ep, _Dp>,
339 is_convertible<_Ep, _Dp>>::type>>
340 unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept
341 : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter()))
342 { }
343
344#if _GLIBCXX_USE_DEPRECATED1
345#pragma GCC diagnostic push
346#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
347 /// Converting constructor from @c auto_ptr
348 template<typename _Up, typename = _Require<
349 is_convertible<_Up*, _Tp*>, is_same<_Dp, default_delete<_Tp>>>>
350 unique_ptr(auto_ptr<_Up>&& __u) noexcept;
351#pragma GCC diagnostic pop
352#endif
353
354 /// Destructor, invokes the deleter if the stored pointer is not null.
355 ~unique_ptr() noexcept
356 {
357 static_assert(__is_invocable<deleter_type&, pointer>::value,
358 "unique_ptr's deleter must be invocable with a pointer");
359 auto& __ptr = _M_t._M_ptr();
360 if (__ptr != nullptr)
361 get_deleter()(std::move(__ptr));
362 __ptr = pointer();
363 }
364
365 // Assignment.
366
367 /** @brief Move assignment operator.
368 *
369 * Invokes the deleter if this object owns a pointer.
370 */
371 unique_ptr& operator=(unique_ptr&&) = default;
372
373 /** @brief Assignment from another type.
374 *
375 * @param __u The object to transfer ownership from, which owns a
376 * convertible pointer to a non-array object.
377 *
378 * Invokes the deleter if this object owns a pointer.
379 */
380 template<typename _Up, typename _Ep>
381 typename enable_if< __and_<
382 __safe_conversion_up<_Up, _Ep>,
383 is_assignable<deleter_type&, _Ep&&>
384 >::value,
385 unique_ptr&>::type
386 operator=(unique_ptr<_Up, _Ep>&& __u) noexcept
387 {
388 reset(__u.release());
389 get_deleter() = std::forward<_Ep>(__u.get_deleter());
390 return *this;
391 }
392
393 /// Reset the %unique_ptr to empty, invoking the deleter if necessary.
394 unique_ptr&
395 operator=(nullptr_t) noexcept
396 {
397 reset();
398 return *this;
399 }
400
401 // Observers.
402
403 /// Dereference the stored pointer.
404 typename add_lvalue_reference<element_type>::type
405 operator*() const
406 {
407 __glibcxx_assert(get() != pointer())do { if (! (get() != pointer())) std::__replacement_assert("/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/unique_ptr.h"
, 407, __PRETTY_FUNCTION__, "get() != pointer()"); } while (false
)
;
408 return *get();
409 }
410
411 /// Return the stored pointer.
412 pointer
413 operator->() const noexcept
414 {
415 _GLIBCXX_DEBUG_PEDASSERT(get() != pointer());
416 return get();
417 }
418
419 /// Return the stored pointer.
420 pointer
421 get() const noexcept
422 { return _M_t._M_ptr(); }
423
424 /// Return a reference to the stored deleter.
425 deleter_type&
426 get_deleter() noexcept
427 { return _M_t._M_deleter(); }
428
429 /// Return a reference to the stored deleter.
430 const deleter_type&
431 get_deleter() const noexcept
432 { return _M_t._M_deleter(); }
433
434 /// Return @c true if the stored pointer is not null.
435 explicit operator bool() const noexcept
436 { return get() == pointer() ? false : true; }
437
438 // Modifiers.
439
440 /// Release ownership of any stored pointer.
441 pointer
442 release() noexcept
443 { return _M_t.release(); }
444
445 /** @brief Replace the stored pointer.
446 *
447 * @param __p The new pointer to store.
448 *
449 * The deleter will be invoked if a pointer is already owned.
450 */
451 void
452 reset(pointer __p = pointer()) noexcept
453 {
454 static_assert(__is_invocable<deleter_type&, pointer>::value,
455 "unique_ptr's deleter must be invocable with a pointer");
456 _M_t.reset(std::move(__p));
457 }
458
459 /// Exchange the pointer and deleter with another object.
460 void
461 swap(unique_ptr& __u) noexcept
462 {
463 static_assert(__is_swappable<_Dp>::value, "deleter must be swappable");
464 _M_t.swap(__u._M_t);
465 }
466
467 // Disable copy from lvalue.
468 unique_ptr(const unique_ptr&) = delete;
469 unique_ptr& operator=(const unique_ptr&) = delete;
470 };
471
472 /// 20.7.1.3 unique_ptr for array objects with a runtime length
473 // [unique.ptr.runtime]
474 // _GLIBCXX_RESOLVE_LIB_DEFECTS
475 // DR 740 - omit specialization for array objects with a compile time length
476 template<typename _Tp, typename _Dp>
477 class unique_ptr<_Tp[], _Dp>
478 {
479 template <typename _Up>
480 using _DeleterConstraint =
481 typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type;
482
483 __uniq_ptr_data<_Tp, _Dp> _M_t;
484
485 template<typename _Up>
486 using __remove_cv = typename remove_cv<_Up>::type;
487
488 // like is_base_of<_Tp, _Up> but false if unqualified types are the same
489 template<typename _Up>
490 using __is_derived_Tp
491 = __and_< is_base_of<_Tp, _Up>,
492 __not_<is_same<__remove_cv<_Tp>, __remove_cv<_Up>>> >;
493
494 public:
495 using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer;
496 using element_type = _Tp;
497 using deleter_type = _Dp;
498
499 // helper template for detecting a safe conversion from another
500 // unique_ptr
501 template<typename _Up, typename _Ep,
502 typename _UPtr = unique_ptr<_Up, _Ep>,
503 typename _UP_pointer = typename _UPtr::pointer,
504 typename _UP_element_type = typename _UPtr::element_type>
505 using __safe_conversion_up = __and_<
506 is_array<_Up>,
507 is_same<pointer, element_type*>,
508 is_same<_UP_pointer, _UP_element_type*>,
509 is_convertible<_UP_element_type(*)[], element_type(*)[]>
510 >;
511
512 // helper template for detecting a safe conversion from a raw pointer
513 template<typename _Up>
514 using __safe_conversion_raw = __and_<
515 __or_<__or_<is_same<_Up, pointer>,
516 is_same<_Up, nullptr_t>>,
517 __and_<is_pointer<_Up>,
518 is_same<pointer, element_type*>,
519 is_convertible<
520 typename remove_pointer<_Up>::type(*)[],
521 element_type(*)[]>
522 >
523 >
524 >;
525
526 // Constructors.
527
528 /// Default constructor, creates a unique_ptr that owns nothing.
529 template<typename _Del = _Dp, typename = _DeleterConstraint<_Del>>
530 constexpr unique_ptr() noexcept
531 : _M_t()
532 { }
533
534 /** Takes ownership of a pointer.
535 *
536 * @param __p A pointer to an array of a type safely convertible
537 * to an array of @c element_type
538 *
539 * The deleter will be value-initialized.
540 */
541 template<typename _Up,
542 typename _Vp = _Dp,
543 typename = _DeleterConstraint<_Vp>,
544 typename = typename enable_if<
545 __safe_conversion_raw<_Up>::value, bool>::type>
546 explicit
547 unique_ptr(_Up __p) noexcept
548 : _M_t(__p)
549 { }
550
551 /** Takes ownership of a pointer.
552 *
553 * @param __p A pointer to an array of a type safely convertible
554 * to an array of @c element_type
555 * @param __d A reference to a deleter.
556 *
557 * The deleter will be initialized with @p __d
558 */
559 template<typename _Up, typename _Del = deleter_type,
560 typename = _Require<__safe_conversion_raw<_Up>,
561 is_copy_constructible<_Del>>>
562 unique_ptr(_Up __p, const deleter_type& __d) noexcept
563 : _M_t(__p, __d) { }
564
565 /** Takes ownership of a pointer.
566 *
567 * @param __p A pointer to an array of a type safely convertible
568 * to an array of @c element_type
569 * @param __d A reference to a deleter.
570 *
571 * The deleter will be initialized with @p std::move(__d)
572 */
573 template<typename _Up, typename _Del = deleter_type,
574 typename = _Require<__safe_conversion_raw<_Up>,
575 is_move_constructible<_Del>>>
576 unique_ptr(_Up __p,
577 __enable_if_t<!is_lvalue_reference<_Del>::value,
578 _Del&&> __d) noexcept
579 : _M_t(std::move(__p), std::move(__d))
580 { }
581
582 template<typename _Up, typename _Del = deleter_type,
583 typename _DelUnref = typename remove_reference<_Del>::type,
584 typename = _Require<__safe_conversion_raw<_Up>>>
585 unique_ptr(_Up,
586 __enable_if_t<is_lvalue_reference<_Del>::value,
587 _DelUnref&&>) = delete;
588
589 /// Move constructor.
590 unique_ptr(unique_ptr&&) = default;
591
592 /// Creates a unique_ptr that owns nothing.
593 template<typename _Del = _Dp, typename = _DeleterConstraint<_Del>>
594 constexpr unique_ptr(nullptr_t) noexcept
595 : _M_t()
596 { }
597
598 template<typename _Up, typename _Ep, typename = _Require<
599 __safe_conversion_up<_Up, _Ep>,
600 typename conditional<is_reference<_Dp>::value,
601 is_same<_Ep, _Dp>,
602 is_convertible<_Ep, _Dp>>::type>>
603 unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept
604 : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter()))
605 { }
606
607 /// Destructor, invokes the deleter if the stored pointer is not null.
608 ~unique_ptr()
609 {
610 auto& __ptr = _M_t._M_ptr();
611 if (__ptr != nullptr)
612 get_deleter()(__ptr);
613 __ptr = pointer();
614 }
615
616 // Assignment.
617
618 /** @brief Move assignment operator.
619 *
620 * Invokes the deleter if this object owns a pointer.
621 */
622 unique_ptr&
623 operator=(unique_ptr&&) = default;
624
625 /** @brief Assignment from another type.
626 *
627 * @param __u The object to transfer ownership from, which owns a
628 * convertible pointer to an array object.
629 *
630 * Invokes the deleter if this object owns a pointer.
631 */
632 template<typename _Up, typename _Ep>
633 typename
634 enable_if<__and_<__safe_conversion_up<_Up, _Ep>,
635 is_assignable<deleter_type&, _Ep&&>
636 >::value,
637 unique_ptr&>::type
638 operator=(unique_ptr<_Up, _Ep>&& __u) noexcept
639 {
640 reset(__u.release());
641 get_deleter() = std::forward<_Ep>(__u.get_deleter());
642 return *this;
643 }
644
645 /// Reset the %unique_ptr to empty, invoking the deleter if necessary.
646 unique_ptr&
647 operator=(nullptr_t) noexcept
648 {
649 reset();
650 return *this;
651 }
652
653 // Observers.
654
655 /// Access an element of owned array.
656 typename std::add_lvalue_reference<element_type>::type
657 operator[](size_t __i) const
658 {
659 __glibcxx_assert(get() != pointer())do { if (! (get() != pointer())) std::__replacement_assert("/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/unique_ptr.h"
, 659, __PRETTY_FUNCTION__, "get() != pointer()"); } while (false
)
;
660 return get()[__i];
661 }
662
663 /// Return the stored pointer.
664 pointer
665 get() const noexcept
666 { return _M_t._M_ptr(); }
667
668 /// Return a reference to the stored deleter.
669 deleter_type&
670 get_deleter() noexcept
671 { return _M_t._M_deleter(); }
672
673 /// Return a reference to the stored deleter.
674 const deleter_type&
675 get_deleter() const noexcept
676 { return _M_t._M_deleter(); }
677
678 /// Return @c true if the stored pointer is not null.
679 explicit operator bool() const noexcept
680 { return get() == pointer() ? false : true; }
681
682 // Modifiers.
683
684 /// Release ownership of any stored pointer.
685 pointer
686 release() noexcept
687 { return _M_t.release(); }
688
689 /** @brief Replace the stored pointer.
690 *
691 * @param __p The new pointer to store.
692 *
693 * The deleter will be invoked if a pointer is already owned.
694 */
695 template <typename _Up,
696 typename = _Require<
697 __or_<is_same<_Up, pointer>,
698 __and_<is_same<pointer, element_type*>,
699 is_pointer<_Up>,
700 is_convertible<
701 typename remove_pointer<_Up>::type(*)[],
702 element_type(*)[]
703 >
704 >
705 >
706 >>
707 void
708 reset(_Up __p) noexcept
709 { _M_t.reset(std::move(__p)); }
710
711 void reset(nullptr_t = nullptr) noexcept
712 { reset(pointer()); }
713
714 /// Exchange the pointer and deleter with another object.
715 void
716 swap(unique_ptr& __u) noexcept
717 {
718 static_assert(__is_swappable<_Dp>::value, "deleter must be swappable");
719 _M_t.swap(__u._M_t);
720 }
721
722 // Disable copy from lvalue.
723 unique_ptr(const unique_ptr&) = delete;
724 unique_ptr& operator=(const unique_ptr&) = delete;
725 };
726
727 /// @relates unique_ptr @{
728
729 /// Swap overload for unique_ptr
730 template<typename _Tp, typename _Dp>
731 inline
732#if __cplusplus201703L > 201402L || !defined(__STRICT_ANSI__1) // c++1z or gnu++11
733 // Constrained free swap overload, see p0185r1
734 typename enable_if<__is_swappable<_Dp>::value>::type
735#else
736 void
737#endif
738 swap(unique_ptr<_Tp, _Dp>& __x,
739 unique_ptr<_Tp, _Dp>& __y) noexcept
740 { __x.swap(__y); }
741
742#if __cplusplus201703L > 201402L || !defined(__STRICT_ANSI__1) // c++1z or gnu++11
743 template<typename _Tp, typename _Dp>
744 typename enable_if<!__is_swappable<_Dp>::value>::type
745 swap(unique_ptr<_Tp, _Dp>&,
746 unique_ptr<_Tp, _Dp>&) = delete;
747#endif
748
749 /// Equality operator for unique_ptr objects, compares the owned pointers
750 template<typename _Tp, typename _Dp,
751 typename _Up, typename _Ep>
752 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
753 operator==(const unique_ptr<_Tp, _Dp>& __x,
754 const unique_ptr<_Up, _Ep>& __y)
755 { return __x.get() == __y.get(); }
756
757 /// unique_ptr comparison with nullptr
758 template<typename _Tp, typename _Dp>
759 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
760 operator==(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept
761 { return !__x; }
762
763#ifndef __cpp_lib_three_way_comparison
764 /// unique_ptr comparison with nullptr
765 template<typename _Tp, typename _Dp>
766 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
767 operator==(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept
768 { return !__x; }
769
770 /// Inequality operator for unique_ptr objects, compares the owned pointers
771 template<typename _Tp, typename _Dp,
772 typename _Up, typename _Ep>
773 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
774 operator!=(const unique_ptr<_Tp, _Dp>& __x,
775 const unique_ptr<_Up, _Ep>& __y)
776 { return __x.get() != __y.get(); }
777
778 /// unique_ptr comparison with nullptr
779 template<typename _Tp, typename _Dp>
780 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
781 operator!=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept
782 { return (bool)__x; }
783
784 /// unique_ptr comparison with nullptr
785 template<typename _Tp, typename _Dp>
786 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
787 operator!=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept
788 { return (bool)__x; }
789#endif // three way comparison
790
791 /// Relational operator for unique_ptr objects, compares the owned pointers
792 template<typename _Tp, typename _Dp,
793 typename _Up, typename _Ep>
794 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
795 operator<(const unique_ptr<_Tp, _Dp>& __x,
796 const unique_ptr<_Up, _Ep>& __y)
797 {
798 typedef typename
799 std::common_type<typename unique_ptr<_Tp, _Dp>::pointer,
800 typename unique_ptr<_Up, _Ep>::pointer>::type _CT;
801 return std::less<_CT>()(__x.get(), __y.get());
802 }
803
804 /// unique_ptr comparison with nullptr
805 template<typename _Tp, typename _Dp>
806 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
807 operator<(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
808 {
809 return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(__x.get(),
810 nullptr);
811 }
812
813 /// unique_ptr comparison with nullptr
814 template<typename _Tp, typename _Dp>
815 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
816 operator<(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
817 {
818 return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(nullptr,
819 __x.get());
820 }
821
822 /// Relational operator for unique_ptr objects, compares the owned pointers
823 template<typename _Tp, typename _Dp,
824 typename _Up, typename _Ep>
825 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
826 operator<=(const unique_ptr<_Tp, _Dp>& __x,
827 const unique_ptr<_Up, _Ep>& __y)
828 { return !(__y < __x); }
829
830 /// unique_ptr comparison with nullptr
831 template<typename _Tp, typename _Dp>
832 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
833 operator<=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
834 { return !(nullptr < __x); }
835
836 /// unique_ptr comparison with nullptr
837 template<typename _Tp, typename _Dp>
838 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
839 operator<=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
840 { return !(__x < nullptr); }
841
842 /// Relational operator for unique_ptr objects, compares the owned pointers
843 template<typename _Tp, typename _Dp,
844 typename _Up, typename _Ep>
845 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
846 operator>(const unique_ptr<_Tp, _Dp>& __x,
847 const unique_ptr<_Up, _Ep>& __y)
848 { return (__y < __x); }
849
850 /// unique_ptr comparison with nullptr
851 template<typename _Tp, typename _Dp>
852 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
853 operator>(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
854 {
855 return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(nullptr,
856 __x.get());
857 }
858
859 /// unique_ptr comparison with nullptr
860 template<typename _Tp, typename _Dp>
861 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
862 operator>(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
863 {
864 return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(__x.get(),
865 nullptr);
866 }
867
868 /// Relational operator for unique_ptr objects, compares the owned pointers
869 template<typename _Tp, typename _Dp,
870 typename _Up, typename _Ep>
871 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
872 operator>=(const unique_ptr<_Tp, _Dp>& __x,
873 const unique_ptr<_Up, _Ep>& __y)
874 { return !(__x < __y); }
875
876 /// unique_ptr comparison with nullptr
877 template<typename _Tp, typename _Dp>
878 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
879 operator>=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
880 { return !(__x < nullptr); }
881
882 /// unique_ptr comparison with nullptr
883 template<typename _Tp, typename _Dp>
884 _GLIBCXX_NODISCARD[[__nodiscard__]] inline bool
885 operator>=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
886 { return !(nullptr < __x); }
887
888#ifdef __cpp_lib_three_way_comparison
889 template<typename _Tp, typename _Dp, typename _Up, typename _Ep>
890 requires three_way_comparable_with<typename unique_ptr<_Tp, _Dp>::pointer,
891 typename unique_ptr<_Up, _Ep>::pointer>
892 inline
893 compare_three_way_result_t<typename unique_ptr<_Tp, _Dp>::pointer,
894 typename unique_ptr<_Up, _Ep>::pointer>
895 operator<=>(const unique_ptr<_Tp, _Dp>& __x,
896 const unique_ptr<_Up, _Ep>& __y)
897 { return compare_three_way()(__x.get(), __y.get()); }
898
899 template<typename _Tp, typename _Dp>
900 requires three_way_comparable<typename unique_ptr<_Tp, _Dp>::pointer>
901 inline
902 compare_three_way_result_t<typename unique_ptr<_Tp, _Dp>::pointer>
903 operator<=>(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
904 {
905 using pointer = typename unique_ptr<_Tp, _Dp>::pointer;
906 return compare_three_way()(__x.get(), static_cast<pointer>(nullptr));
907 }
908#endif
909 // @} relates unique_ptr
910
911 /// @cond undocumented
912 template<typename _Up, typename _Ptr = typename _Up::pointer,
913 bool = __poison_hash<_Ptr>::__enable_hash_call>
914 struct __uniq_ptr_hash
915#if ! _GLIBCXX_INLINE_VERSION0
916 : private __poison_hash<_Ptr>
917#endif
918 {
919 size_t
920 operator()(const _Up& __u) const
921 noexcept(noexcept(std::declval<hash<_Ptr>>()(std::declval<_Ptr>())))
922 { return hash<_Ptr>()(__u.get()); }
923 };
924
925 template<typename _Up, typename _Ptr>
926 struct __uniq_ptr_hash<_Up, _Ptr, false>
927 : private __poison_hash<_Ptr>
928 { };
929 /// @endcond
930
931 /// std::hash specialization for unique_ptr.
932 template<typename _Tp, typename _Dp>
933 struct hash<unique_ptr<_Tp, _Dp>>
934 : public __hash_base<size_t, unique_ptr<_Tp, _Dp>>,
935 public __uniq_ptr_hash<unique_ptr<_Tp, _Dp>>
936 { };
937
938#if __cplusplus201703L >= 201402L
939 /// @relates unique_ptr @{
940#define __cpp_lib_make_unique201304 201304
941
942 /// @cond undocumented
943
944 template<typename _Tp>
945 struct _MakeUniq
946 { typedef unique_ptr<_Tp> __single_object; };
947
948 template<typename _Tp>
949 struct _MakeUniq<_Tp[]>
950 { typedef unique_ptr<_Tp[]> __array; };
951
952 template<typename _Tp, size_t _Bound>
953 struct _MakeUniq<_Tp[_Bound]>
954 { struct __invalid_type { }; };
955
956 /// @endcond
957
958 /// std::make_unique for single objects
959 template<typename _Tp, typename... _Args>
960 inline typename _MakeUniq<_Tp>::__single_object
961 make_unique(_Args&&... __args)
962 { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
4
Calling constructor for 'ACLEIntrinsic'
963
964 /// std::make_unique for arrays of unknown bound
965 template<typename _Tp>
966 inline typename _MakeUniq<_Tp>::__array
967 make_unique(size_t __num)
968 { return unique_ptr<_Tp>(new remove_extent_t<_Tp>[__num]()); }
969
970 /// Disable std::make_unique for arrays of known bound
971 template<typename _Tp, typename... _Args>
972 inline typename _MakeUniq<_Tp>::__invalid_type
973 make_unique(_Args&&...) = delete;
974 // @} relates unique_ptr
975#endif // C++14
976
977#if __cplusplus201703L > 201703L && __cpp_concepts
978 // _GLIBCXX_RESOLVE_LIB_DEFECTS
979 // 2948. unique_ptr does not define operator<< for stream output
980 /// Stream output operator for unique_ptr
981 template<typename _CharT, typename _Traits, typename _Tp, typename _Dp>
982 inline basic_ostream<_CharT, _Traits>&
983 operator<<(basic_ostream<_CharT, _Traits>& __os,
984 const unique_ptr<_Tp, _Dp>& __p)
985 requires requires { __os << __p.get(); }
986 {
987 __os << __p.get();
988 return __os;
989 }
990#endif // C++20
991
992 // @} group pointer_abstractions
993
994#if __cplusplus201703L >= 201703L
995 namespace __detail::__variant
996 {
997 template<typename> struct _Never_valueless_alt; // see <variant>
998
999 // Provide the strong exception-safety guarantee when emplacing a
1000 // unique_ptr into a variant.
1001 template<typename _Tp, typename _Del>
1002 struct _Never_valueless_alt<std::unique_ptr<_Tp, _Del>>
1003 : std::true_type
1004 { };
1005 } // namespace __detail::__variant
1006#endif // C++17
1007
1008_GLIBCXX_END_NAMESPACE_VERSION
1009} // namespace
1010
1011#endif /* _UNIQUE_PTR_H */

/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/basic_string.h

1// Components for manipulating sequences of characters -*- C++ -*-
2
3// Copyright (C) 1997-2020 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/basic_string.h
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{string}
28 */
29
30//
31// ISO C++ 14882: 21 Strings library
32//
33
34#ifndef _BASIC_STRING_H1
35#define _BASIC_STRING_H1 1
36
37#pragma GCC system_header
38
39#include <ext/atomicity.h>
40#include <ext/alloc_traits.h>
41#include <debug/debug.h>
42
43#if __cplusplus201703L >= 201103L
44#include <initializer_list>
45#endif
46
47#if __cplusplus201703L >= 201703L
48# include <string_view>
49#endif
50
51
52namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
53{
54_GLIBCXX_BEGIN_NAMESPACE_VERSION
55
56#if _GLIBCXX_USE_CXX11_ABI1
57_GLIBCXX_BEGIN_NAMESPACE_CXX11namespace __cxx11 {
58 /**
59 * @class basic_string basic_string.h <string>
60 * @brief Managing sequences of characters and character-like objects.
61 *
62 * @ingroup strings
63 * @ingroup sequences
64 *
65 * @tparam _CharT Type of character
66 * @tparam _Traits Traits for character type, defaults to
67 * char_traits<_CharT>.
68 * @tparam _Alloc Allocator type, defaults to allocator<_CharT>.
69 *
70 * Meets the requirements of a <a href="tables.html#65">container</a>, a
71 * <a href="tables.html#66">reversible container</a>, and a
72 * <a href="tables.html#67">sequence</a>. Of the
73 * <a href="tables.html#68">optional sequence requirements</a>, only
74 * @c push_back, @c at, and @c %array access are supported.
75 */
76 template<typename _CharT, typename _Traits, typename _Alloc>
77 class basic_string
78 {
79 typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template
80 rebind<_CharT>::other _Char_alloc_type;
81 typedef __gnu_cxx::__alloc_traits<_Char_alloc_type> _Alloc_traits;
82
83 // Types:
84 public:
85 typedef _Traits traits_type;
86 typedef typename _Traits::char_type value_type;
87 typedef _Char_alloc_type allocator_type;
88 typedef typename _Alloc_traits::size_type size_type;
89 typedef typename _Alloc_traits::difference_type difference_type;
90 typedef typename _Alloc_traits::reference reference;
91 typedef typename _Alloc_traits::const_reference const_reference;
92 typedef typename _Alloc_traits::pointer pointer;
93 typedef typename _Alloc_traits::const_pointer const_pointer;
94 typedef __gnu_cxx::__normal_iterator<pointer, basic_string> iterator;
95 typedef __gnu_cxx::__normal_iterator<const_pointer, basic_string>
96 const_iterator;
97 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
98 typedef std::reverse_iterator<iterator> reverse_iterator;
99
100 /// Value returned by various member functions when they fail.
101 static const size_type npos = static_cast<size_type>(-1);
102
103 protected:
104 // type used for positions in insert, erase etc.
105#if __cplusplus201703L < 201103L
106 typedef iterator __const_iterator;
107#else
108 typedef const_iterator __const_iterator;
109#endif
110
111 private:
112#if __cplusplus201703L >= 201703L
113 // A helper type for avoiding boiler-plate.
114 typedef basic_string_view<_CharT, _Traits> __sv_type;
115
116 template<typename _Tp, typename _Res>
117 using _If_sv = enable_if_t<
118 __and_<is_convertible<const _Tp&, __sv_type>,
119 __not_<is_convertible<const _Tp*, const basic_string*>>,
120 __not_<is_convertible<const _Tp&, const _CharT*>>>::value,
121 _Res>;
122
123 // Allows an implicit conversion to __sv_type.
124 static __sv_type
125 _S_to_string_view(__sv_type __svt) noexcept
126 { return __svt; }
127
128 // Wraps a string_view by explicit conversion and thus
129 // allows to add an internal constructor that does not
130 // participate in overload resolution when a string_view
131 // is provided.
132 struct __sv_wrapper
133 {
134 explicit __sv_wrapper(__sv_type __sv) noexcept : _M_sv(__sv) { }
135 __sv_type _M_sv;
136 };
137
138 /**
139 * @brief Only internally used: Construct string from a string view
140 * wrapper.
141 * @param __svw string view wrapper.
142 * @param __a Allocator to use.
143 */
144 explicit
145 basic_string(__sv_wrapper __svw, const _Alloc& __a)
146 : basic_string(__svw._M_sv.data(), __svw._M_sv.size(), __a) { }
147#endif
148
149 // Use empty-base optimization: http://www.cantrip.org/emptyopt.html
150 struct _Alloc_hider : allocator_type // TODO check __is_final
151 {
152#if __cplusplus201703L < 201103L
153 _Alloc_hider(pointer __dat, const _Alloc& __a = _Alloc())
154 : allocator_type(__a), _M_p(__dat) { }
155#else
156 _Alloc_hider(pointer __dat, const _Alloc& __a)
157 : allocator_type(__a), _M_p(__dat) { }
158
159 _Alloc_hider(pointer __dat, _Alloc&& __a = _Alloc())
160 : allocator_type(std::move(__a)), _M_p(__dat) { }
161#endif
162
163 pointer _M_p; // The actual data.
164 };
165
166 _Alloc_hider _M_dataplus;
167 size_type _M_string_length;
168
169 enum { _S_local_capacity = 15 / sizeof(_CharT) };
170
171 union
172 {
173 _CharT _M_local_buf[_S_local_capacity + 1];
174 size_type _M_allocated_capacity;
175 };
176
177 void
178 _M_data(pointer __p)
179 { _M_dataplus._M_p = __p; }
180
181 void
182 _M_length(size_type __length)
183 { _M_string_length = __length; }
184
185 pointer
186 _M_data() const
187 { return _M_dataplus._M_p; }
188
189 pointer
190 _M_local_data()
191 {
192#if __cplusplus201703L >= 201103L
193 return std::pointer_traits<pointer>::pointer_to(*_M_local_buf);
194#else
195 return pointer(_M_local_buf);
196#endif
197 }
198
199 const_pointer
200 _M_local_data() const
201 {
202#if __cplusplus201703L >= 201103L
203 return std::pointer_traits<const_pointer>::pointer_to(*_M_local_buf);
204#else
205 return const_pointer(_M_local_buf);
206#endif
207 }
208
209 void
210 _M_capacity(size_type __capacity)
211 { _M_allocated_capacity = __capacity; }
212
213 void
214 _M_set_length(size_type __n)
215 {
216 _M_length(__n);
217 traits_type::assign(_M_data()[__n], _CharT());
218 }
219
220 bool
221 _M_is_local() const
222 { return _M_data() == _M_local_data(); }
223
224 // Create & Destroy
225 pointer
226 _M_create(size_type&, size_type);
227
228 void
229 _M_dispose()
230 {
231 if (!_M_is_local())
232 _M_destroy(_M_allocated_capacity);
233 }
234
235 void
236 _M_destroy(size_type __size) throw()
237 { _Alloc_traits::deallocate(_M_get_allocator(), _M_data(), __size + 1); }
238
239 // _M_construct_aux is used to implement the 21.3.1 para 15 which
240 // requires special behaviour if _InIterator is an integral type
241 template<typename _InIterator>
242 void
243 _M_construct_aux(_InIterator __beg, _InIterator __end,
244 std::__false_type)
245 {
246 typedef typename iterator_traits<_InIterator>::iterator_category _Tag;
247 _M_construct(__beg, __end, _Tag());
248 }
249
250 // _GLIBCXX_RESOLVE_LIB_DEFECTS
251 // 438. Ambiguity in the "do the right thing" clause
252 template<typename _Integer>
253 void
254 _M_construct_aux(_Integer __beg, _Integer __end, std::__true_type)
255 { _M_construct_aux_2(static_cast<size_type>(__beg), __end); }
256
257 void
258 _M_construct_aux_2(size_type __req, _CharT __c)
259 { _M_construct(__req, __c); }
260
261 template<typename _InIterator>
262 void
263 _M_construct(_InIterator __beg, _InIterator __end)
264 {
265 typedef typename std::__is_integer<_InIterator>::__type _Integral;
266 _M_construct_aux(__beg, __end, _Integral());
267 }
268
269 // For Input Iterators, used in istreambuf_iterators, etc.
270 template<typename _InIterator>
271 void
272 _M_construct(_InIterator __beg, _InIterator __end,
273 std::input_iterator_tag);
274
275 // For forward_iterators up to random_access_iterators, used for
276 // string::iterator, _CharT*, etc.
277 template<typename _FwdIterator>
278 void
279 _M_construct(_FwdIterator __beg, _FwdIterator __end,
280 std::forward_iterator_tag);
281
282 void
283 _M_construct(size_type __req, _CharT __c);
284
285 allocator_type&
286 _M_get_allocator()
287 { return _M_dataplus; }
288
289 const allocator_type&
290 _M_get_allocator() const
291 { return _M_dataplus; }
292
293 private:
294
295#ifdef _GLIBCXX_DISAMBIGUATE_REPLACE_INST
296 // The explicit instantiations in misc-inst.cc require this due to
297 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64063
298 template<typename _Tp, bool _Requires =
299 !__are_same<_Tp, _CharT*>::__value
300 && !__are_same<_Tp, const _CharT*>::__value
301 && !__are_same<_Tp, iterator>::__value
302 && !__are_same<_Tp, const_iterator>::__value>
303 struct __enable_if_not_native_iterator
304 { typedef basic_string& __type; };
305 template<typename _Tp>
306 struct __enable_if_not_native_iterator<_Tp, false> { };
307#endif
308
309 size_type
310 _M_check(size_type __pos, const char* __s) const
311 {
312 if (__pos > this->size())
313 __throw_out_of_range_fmt(__N("%s: __pos (which is %zu) > "("%s: __pos (which is %zu) > " "this->size() (which is %zu)"
)
314 "this->size() (which is %zu)")("%s: __pos (which is %zu) > " "this->size() (which is %zu)"
)
,
315 __s, __pos, this->size());
316 return __pos;
317 }
318
319 void
320 _M_check_length(size_type __n1, size_type __n2, const char* __s) const
321 {
322 if (this->max_size() - (this->size() - __n1) < __n2)
323 __throw_length_error(__N(__s)(__s));
324 }
325
326
327 // NB: _M_limit doesn't check for a bad __pos value.
328 size_type
329 _M_limit(size_type __pos, size_type __off) const _GLIBCXX_NOEXCEPTnoexcept
330 {
331 const bool __testoff = __off < this->size() - __pos;
332 return __testoff ? __off : this->size() - __pos;
333 }
334
335 // True if _Rep and source do not overlap.
336 bool
337 _M_disjunct(const _CharT* __s) const _GLIBCXX_NOEXCEPTnoexcept
338 {
339 return (less<const _CharT*>()(__s, _M_data())
340 || less<const _CharT*>()(_M_data() + this->size(), __s));
341 }
342
343 // When __n = 1 way faster than the general multichar
344 // traits_type::copy/move/assign.
345 static void
346 _S_copy(_CharT* __d, const _CharT* __s, size_type __n)
347 {
348 if (__n == 1)
349 traits_type::assign(*__d, *__s);
350 else
351 traits_type::copy(__d, __s, __n);
352 }
353
354 static void
355 _S_move(_CharT* __d, const _CharT* __s, size_type __n)
356 {
357 if (__n == 1)
358 traits_type::assign(*__d, *__s);
359 else
360 traits_type::move(__d, __s, __n);
361 }
362
363 static void
364 _S_assign(_CharT* __d, size_type __n, _CharT __c)
365 {
366 if (__n == 1)
367 traits_type::assign(*__d, __c);
368 else
369 traits_type::assign(__d, __n, __c);
370 }
371
372 // _S_copy_chars is a separate template to permit specialization
373 // to optimize for the common case of pointers as iterators.
374 template<class _Iterator>
375 static void
376 _S_copy_chars(_CharT* __p, _Iterator __k1, _Iterator __k2)
377 {
378 for (; __k1 != __k2; ++__k1, (void)++__p)
379 traits_type::assign(*__p, *__k1); // These types are off.
380 }
381
382 static void
383 _S_copy_chars(_CharT* __p, iterator __k1, iterator __k2) _GLIBCXX_NOEXCEPTnoexcept
384 { _S_copy_chars(__p, __k1.base(), __k2.base()); }
385
386 static void
387 _S_copy_chars(_CharT* __p, const_iterator __k1, const_iterator __k2)
388 _GLIBCXX_NOEXCEPTnoexcept
389 { _S_copy_chars(__p, __k1.base(), __k2.base()); }
390
391 static void
392 _S_copy_chars(_CharT* __p, _CharT* __k1, _CharT* __k2) _GLIBCXX_NOEXCEPTnoexcept
393 { _S_copy(__p, __k1, __k2 - __k1); }
394
395 static void
396 _S_copy_chars(_CharT* __p, const _CharT* __k1, const _CharT* __k2)
397 _GLIBCXX_NOEXCEPTnoexcept
398 { _S_copy(__p, __k1, __k2 - __k1); }
399
400 static int
401 _S_compare(size_type __n1, size_type __n2) _GLIBCXX_NOEXCEPTnoexcept
402 {
403 const difference_type __d = difference_type(__n1 - __n2);
404
405 if (__d > __gnu_cxx::__numeric_traits<int>::__max)
406 return __gnu_cxx::__numeric_traits<int>::__max;
407 else if (__d < __gnu_cxx::__numeric_traits<int>::__min)
408 return __gnu_cxx::__numeric_traits<int>::__min;
409 else
410 return int(__d);
411 }
412
413 void
414 _M_assign(const basic_string&);
415
416 void
417 _M_mutate(size_type __pos, size_type __len1, const _CharT* __s,
418 size_type __len2);
419
420 void
421 _M_erase(size_type __pos, size_type __n);
422
423 public:
424 // Construct/copy/destroy:
425 // NB: We overload ctors in some cases instead of using default
426 // arguments, per 17.4.4.4 para. 2 item 2.
427
428 /**
429 * @brief Default constructor creates an empty string.
430 */
431 basic_string()
432 _GLIBCXX_NOEXCEPT_IF(is_nothrow_default_constructible<_Alloc>::value)noexcept(is_nothrow_default_constructible<_Alloc>::value
)
433 : _M_dataplus(_M_local_data())
434 { _M_set_length(0); }
435
436 /**
437 * @brief Construct an empty string using allocator @a a.
438 */
439 explicit
440 basic_string(const _Alloc& __a) _GLIBCXX_NOEXCEPTnoexcept
441 : _M_dataplus(_M_local_data(), __a)
442 { _M_set_length(0); }
443
444 /**
445 * @brief Construct string with copy of value of @a __str.
446 * @param __str Source string.
447 */
448 basic_string(const basic_string& __str)
449 : _M_dataplus(_M_local_data(),
450 _Alloc_traits::_S_select_on_copy(__str._M_get_allocator()))
451 { _M_construct(__str._M_data(), __str._M_data() + __str.length()); }
452
453 // _GLIBCXX_RESOLVE_LIB_DEFECTS
454 // 2583. no way to supply an allocator for basic_string(str, pos)
455 /**
456 * @brief Construct string as copy of a substring.
457 * @param __str Source string.
458 * @param __pos Index of first character to copy from.
459 * @param __a Allocator to use.
460 */
461 basic_string(const basic_string& __str, size_type __pos,
462 const _Alloc& __a = _Alloc())
463 : _M_dataplus(_M_local_data(), __a)
464 {
465 const _CharT* __start = __str._M_data()
466 + __str._M_check(__pos, "basic_string::basic_string");
467 _M_construct(__start, __start + __str._M_limit(__pos, npos));
468 }
469
470 /**
471 * @brief Construct string as copy of a substring.
472 * @param __str Source string.
473 * @param __pos Index of first character to copy from.
474 * @param __n Number of characters to copy.
475 */
476 basic_string(const basic_string& __str, size_type __pos,
477 size_type __n)
478 : _M_dataplus(_M_local_data())
479 {
480 const _CharT* __start = __str._M_data()
481 + __str._M_check(__pos, "basic_string::basic_string");
482 _M_construct(__start, __start + __str._M_limit(__pos, __n));
483 }
484
485 /**
486 * @brief Construct string as copy of a substring.
487 * @param __str Source string.
488 * @param __pos Index of first character to copy from.
489 * @param __n Number of characters to copy.
490 * @param __a Allocator to use.
491 */
492 basic_string(const basic_string& __str, size_type __pos,
493 size_type __n, const _Alloc& __a)
494 : _M_dataplus(_M_local_data(), __a)
495 {
496 const _CharT* __start
497 = __str._M_data() + __str._M_check(__pos, "string::string");
498 _M_construct(__start, __start + __str._M_limit(__pos, __n));
499 }
500
501 /**
502 * @brief Construct string initialized by a character %array.
503 * @param __s Source character %array.
504 * @param __n Number of characters to copy.
505 * @param __a Allocator to use (default is default allocator).
506 *
507 * NB: @a __s must have at least @a __n characters, &apos;\\0&apos;
508 * has no special meaning.
509 */
510 basic_string(const _CharT* __s, size_type __n,
511 const _Alloc& __a = _Alloc())
512 : _M_dataplus(_M_local_data(), __a)
513 { _M_construct(__s, __s + __n); }
514
515 /**
516 * @brief Construct string as copy of a C string.
517 * @param __s Source C string.
518 * @param __a Allocator to use (default is default allocator).
519 */
520#if __cpp_deduction_guides201703L && ! defined _GLIBCXX_DEFINING_STRING_INSTANTIATIONS
521 // _GLIBCXX_RESOLVE_LIB_DEFECTS
522 // 3076. basic_string CTAD ambiguity
523 template<typename = _RequireAllocator<_Alloc>>
524#endif
525 basic_string(const _CharT* __s, const _Alloc& __a = _Alloc())
526 : _M_dataplus(_M_local_data(), __a)
527 { _M_construct(__s, __s ? __s + traits_type::length(__s) : __s+npos); }
528
529 /**
530 * @brief Construct string as multiple characters.
531 * @param __n Number of characters.
532 * @param __c Character to use.
533 * @param __a Allocator to use (default is default allocator).
534 */
535#if __cpp_deduction_guides201703L && ! defined _GLIBCXX_DEFINING_STRING_INSTANTIATIONS
536 // _GLIBCXX_RESOLVE_LIB_DEFECTS
537 // 3076. basic_string CTAD ambiguity
538 template<typename = _RequireAllocator<_Alloc>>
539#endif
540 basic_string(size_type __n, _CharT __c, const _Alloc& __a = _Alloc())
541 : _M_dataplus(_M_local_data(), __a)
542 { _M_construct(__n, __c); }
543
544#if __cplusplus201703L >= 201103L
545 /**
546 * @brief Move construct string.
547 * @param __str Source string.
548 *
549 * The newly-created string contains the exact contents of @a __str.
550 * @a __str is a valid, but unspecified string.
551 **/
552 basic_string(basic_string&& __str) noexcept
553 : _M_dataplus(_M_local_data(), std::move(__str._M_get_allocator()))
554 {
555 if (__str._M_is_local())
556 {
557 traits_type::copy(_M_local_buf, __str._M_local_buf,
558 _S_local_capacity + 1);
559 }
560 else
561 {
562 _M_data(__str._M_data());
563 _M_capacity(__str._M_allocated_capacity);
564 }
565
566 // Must use _M_length() here not _M_set_length() because
567 // basic_stringbuf relies on writing into unallocated capacity so
568 // we mess up the contents if we put a '\0' in the string.
569 _M_length(__str.length());
570 __str._M_data(__str._M_local_data());
571 __str._M_set_length(0);
572 }
573
574 /**
575 * @brief Construct string from an initializer %list.
576 * @param __l std::initializer_list of characters.
577 * @param __a Allocator to use (default is default allocator).
578 */
579 basic_string(initializer_list<_CharT> __l, const _Alloc& __a = _Alloc())
580 : _M_dataplus(_M_local_data(), __a)
581 { _M_construct(__l.begin(), __l.end()); }
582
583 basic_string(const basic_string& __str, const _Alloc& __a)
584 : _M_dataplus(_M_local_data(), __a)
585 { _M_construct(__str.begin(), __str.end()); }
586
587 basic_string(basic_string&& __str, const _Alloc& __a)
588 noexcept(_Alloc_traits::_S_always_equal())
589 : _M_dataplus(_M_local_data(), __a)
590 {
591 if (__str._M_is_local())
592 {
593 traits_type::copy(_M_local_buf, __str._M_local_buf,
594 _S_local_capacity + 1);
595 _M_length(__str.length());
596 __str._M_set_length(0);
597 }
598 else if (_Alloc_traits::_S_always_equal()
599 || __str.get_allocator() == __a)
600 {
601 _M_data(__str._M_data());
602 _M_length(__str.length());
603 _M_capacity(__str._M_allocated_capacity);
604 __str._M_data(__str._M_local_buf);
605 __str._M_set_length(0);
606 }
607 else
608 _M_construct(__str.begin(), __str.end());
609 }
610
611#endif // C++11
612
613 /**
614 * @brief Construct string as copy of a range.
615 * @param __beg Start of range.
616 * @param __end End of range.
617 * @param __a Allocator to use (default is default allocator).
618 */
619#if __cplusplus201703L >= 201103L
620 template<typename _InputIterator,
621 typename = std::_RequireInputIter<_InputIterator>>
622#else
623 template<typename _InputIterator>
624#endif
625 basic_string(_InputIterator __beg, _InputIterator __end,
626 const _Alloc& __a = _Alloc())
627 : _M_dataplus(_M_local_data(), __a)
628 { _M_construct(__beg, __end); }
629
630#if __cplusplus201703L >= 201703L
631 /**
632 * @brief Construct string from a substring of a string_view.
633 * @param __t Source object convertible to string view.
634 * @param __pos The index of the first character to copy from __t.
635 * @param __n The number of characters to copy from __t.
636 * @param __a Allocator to use.
637 */
638 template<typename _Tp, typename = _If_sv<_Tp, void>>
639 basic_string(const _Tp& __t, size_type __pos, size_type __n,
640 const _Alloc& __a = _Alloc())
641 : basic_string(_S_to_string_view(__t).substr(__pos, __n), __a) { }
642
643 /**
644 * @brief Construct string from a string_view.
645 * @param __t Source object convertible to string view.
646 * @param __a Allocator to use (default is default allocator).
647 */
648 template<typename _Tp, typename = _If_sv<_Tp, void>>
649 explicit
650 basic_string(const _Tp& __t, const _Alloc& __a = _Alloc())
651 : basic_string(__sv_wrapper(_S_to_string_view(__t)), __a) { }
652#endif // C++17
653
654 /**
655 * @brief Destroy the string instance.
656 */
657 ~basic_string()
658 { _M_dispose(); }
659
660 /**
661 * @brief Assign the value of @a str to this string.
662 * @param __str Source string.
663 */
664 basic_string&
665 operator=(const basic_string& __str)
666 {
667 return this->assign(__str);
668 }
669
670 /**
671 * @brief Copy contents of @a s into this string.
672 * @param __s Source null-terminated string.
673 */
674 basic_string&
675 operator=(const _CharT* __s)
676 { return this->assign(__s); }
677
678 /**
679 * @brief Set value to string of length 1.
680 * @param __c Source character.
681 *
682 * Assigning to a character makes this string length 1 and
683 * (*this)[0] == @a c.
684 */
685 basic_string&
686 operator=(_CharT __c)
687 {
688 this->assign(1, __c);
689 return *this;
690 }
691
692#if __cplusplus201703L >= 201103L
693 /**
694 * @brief Move assign the value of @a str to this string.
695 * @param __str Source string.
696 *
697 * The contents of @a str are moved into this string (without copying).
698 * @a str is a valid, but unspecified string.
699 **/
700 // _GLIBCXX_RESOLVE_LIB_DEFECTS
701 // 2063. Contradictory requirements for string move assignment
702 basic_string&
703 operator=(basic_string&& __str)
704 noexcept(_Alloc_traits::_S_nothrow_move())
705 {
706 if (!_M_is_local() && _Alloc_traits::_S_propagate_on_move_assign()
707 && !_Alloc_traits::_S_always_equal()
708 && _M_get_allocator() != __str._M_get_allocator())
709 {
710 // Destroy existing storage before replacing allocator.
711 _M_destroy(_M_allocated_capacity);
712 _M_data(_M_local_data());
713 _M_set_length(0);
714 }
715 // Replace allocator if POCMA is true.
716 std::__alloc_on_move(_M_get_allocator(), __str._M_get_allocator());
717
718 if (__str._M_is_local())
719 {
720 // We've always got room for a short string, just copy it.
721 if (__str.size())
722 this->_S_copy(_M_data(), __str._M_data(), __str.size());
723 _M_set_length(__str.size());
724 }
725 else if (_Alloc_traits::_S_propagate_on_move_assign()
726 || _Alloc_traits::_S_always_equal()
727 || _M_get_allocator() == __str._M_get_allocator())
728 {
729 // Just move the allocated pointer, our allocator can free it.
730 pointer __data = nullptr;
731 size_type __capacity;
732 if (!_M_is_local())
733 {
734 if (_Alloc_traits::_S_always_equal())
735 {
736 // __str can reuse our existing storage.
737 __data = _M_data();
738 __capacity = _M_allocated_capacity;
739 }
740 else // __str can't use it, so free it.
741 _M_destroy(_M_allocated_capacity);
742 }
743
744 _M_data(__str._M_data());
745 _M_length(__str.length());
746 _M_capacity(__str._M_allocated_capacity);
747 if (__data)
748 {
749 __str._M_data(__data);
750 __str._M_capacity(__capacity);
751 }
752 else
753 __str._M_data(__str._M_local_buf);
754 }
755 else // Need to do a deep copy
756 assign(__str);
757 __str.clear();
758 return *this;
759 }
760
761 /**
762 * @brief Set value to string constructed from initializer %list.
763 * @param __l std::initializer_list.
764 */
765 basic_string&
766 operator=(initializer_list<_CharT> __l)
767 {
768 this->assign(__l.begin(), __l.size());
769 return *this;
770 }
771#endif // C++11
772
773#if __cplusplus201703L >= 201703L
774 /**
775 * @brief Set value to string constructed from a string_view.
776 * @param __svt An object convertible to string_view.
777 */
778 template<typename _Tp>
779 _If_sv<_Tp, basic_string&>
780 operator=(const _Tp& __svt)
781 { return this->assign(__svt); }
782
783 /**
784 * @brief Convert to a string_view.
785 * @return A string_view.
786 */
787 operator __sv_type() const noexcept
788 { return __sv_type(data(), size()); }
789#endif // C++17
790
791 // Iterators:
792 /**
793 * Returns a read/write iterator that points to the first character in
794 * the %string.
795 */
796 iterator
797 begin() _GLIBCXX_NOEXCEPTnoexcept
798 { return iterator(_M_data()); }
799
800 /**
801 * Returns a read-only (constant) iterator that points to the first
802 * character in the %string.
803 */
804 const_iterator
805 begin() const _GLIBCXX_NOEXCEPTnoexcept
806 { return const_iterator(_M_data()); }
807
808 /**
809 * Returns a read/write iterator that points one past the last
810 * character in the %string.
811 */
812 iterator
813 end() _GLIBCXX_NOEXCEPTnoexcept
814 { return iterator(_M_data() + this->size()); }
815
816 /**
817 * Returns a read-only (constant) iterator that points one past the
818 * last character in the %string.
819 */
820 const_iterator
821 end() const _GLIBCXX_NOEXCEPTnoexcept
822 { return const_iterator(_M_data() + this->size()); }
823
824 /**
825 * Returns a read/write reverse iterator that points to the last
826 * character in the %string. Iteration is done in reverse element
827 * order.
828 */
829 reverse_iterator
830 rbegin() _GLIBCXX_NOEXCEPTnoexcept
831 { return reverse_iterator(this->end()); }
832
833 /**
834 * Returns a read-only (constant) reverse iterator that points
835 * to the last character in the %string. Iteration is done in
836 * reverse element order.
837 */
838 const_reverse_iterator
839 rbegin() const _GLIBCXX_NOEXCEPTnoexcept
840 { return const_reverse_iterator(this->end()); }
841
842 /**
843 * Returns a read/write reverse iterator that points to one before the
844 * first character in the %string. Iteration is done in reverse
845 * element order.
846 */
847 reverse_iterator
848 rend() _GLIBCXX_NOEXCEPTnoexcept
849 { return reverse_iterator(this->begin()); }
850
851 /**
852 * Returns a read-only (constant) reverse iterator that points
853 * to one before the first character in the %string. Iteration
854 * is done in reverse element order.
855 */
856 const_reverse_iterator
857 rend() const _GLIBCXX_NOEXCEPTnoexcept
858 { return const_reverse_iterator(this->begin()); }
859
860#if __cplusplus201703L >= 201103L
861 /**
862 * Returns a read-only (constant) iterator that points to the first
863 * character in the %string.
864 */
865 const_iterator
866 cbegin() const noexcept
867 { return const_iterator(this->_M_data()); }
868
869 /**
870 * Returns a read-only (constant) iterator that points one past the
871 * last character in the %string.
872 */
873 const_iterator
874 cend() const noexcept
875 { return const_iterator(this->_M_data() + this->size()); }
876
877 /**
878 * Returns a read-only (constant) reverse iterator that points
879 * to the last character in the %string. Iteration is done in
880 * reverse element order.
881 */
882 const_reverse_iterator
883 crbegin() const noexcept
884 { return const_reverse_iterator(this->end()); }
885
886 /**
887 * Returns a read-only (constant) reverse iterator that points
888 * to one before the first character in the %string. Iteration
889 * is done in reverse element order.
890 */
891 const_reverse_iterator
892 crend() const noexcept
893 { return const_reverse_iterator(this->begin()); }
894#endif
895
896 public:
897 // Capacity:
898 /// Returns the number of characters in the string, not including any
899 /// null-termination.
900 size_type
901 size() const _GLIBCXX_NOEXCEPTnoexcept
902 { return _M_string_length; }
903
904 /// Returns the number of characters in the string, not including any
905 /// null-termination.
906 size_type
907 length() const _GLIBCXX_NOEXCEPTnoexcept
908 { return _M_string_length; }
909
910 /// Returns the size() of the largest possible %string.
911 size_type
912 max_size() const _GLIBCXX_NOEXCEPTnoexcept
913 { return (_Alloc_traits::max_size(_M_get_allocator()) - 1) / 2; }
914
915 /**
916 * @brief Resizes the %string to the specified number of characters.
917 * @param __n Number of characters the %string should contain.
918 * @param __c Character to fill any new elements.
919 *
920 * This function will %resize the %string to the specified
921 * number of characters. If the number is smaller than the
922 * %string's current size the %string is truncated, otherwise
923 * the %string is extended and new elements are %set to @a __c.
924 */
925 void
926 resize(size_type __n, _CharT __c);
927
928 /**
929 * @brief Resizes the %string to the specified number of characters.
930 * @param __n Number of characters the %string should contain.
931 *
932 * This function will resize the %string to the specified length. If
933 * the new size is smaller than the %string's current size the %string
934 * is truncated, otherwise the %string is extended and new characters
935 * are default-constructed. For basic types such as char, this means
936 * setting them to 0.
937 */
938 void
939 resize(size_type __n)
940 { this->resize(__n, _CharT()); }
941
942#if __cplusplus201703L >= 201103L
943 /// A non-binding request to reduce capacity() to size().
944 void
945 shrink_to_fit() noexcept
946 {
947#if __cpp_exceptions
948 if (capacity() > size())
949 {
950 try
951 { reserve(0); }
952 catch(...)
953 { }
954 }
955#endif
956 }
957#endif
958
959 /**
960 * Returns the total number of characters that the %string can hold
961 * before needing to allocate more memory.
962 */
963 size_type
964 capacity() const _GLIBCXX_NOEXCEPTnoexcept
965 {
966 return _M_is_local() ? size_type(_S_local_capacity)
967 : _M_allocated_capacity;
968 }
969
970 /**
971 * @brief Attempt to preallocate enough memory for specified number of
972 * characters.
973 * @param __res_arg Number of characters required.
974 * @throw std::length_error If @a __res_arg exceeds @c max_size().
975 *
976 * This function attempts to reserve enough memory for the
977 * %string to hold the specified number of characters. If the
978 * number requested is more than max_size(), length_error is
979 * thrown.
980 *
981 * The advantage of this function is that if optimal code is a
982 * necessity and the user can determine the string length that will be
983 * required, the user can reserve the memory in %advance, and thus
984 * prevent a possible reallocation of memory and copying of %string
985 * data.
986 */
987 void
988 reserve(size_type __res_arg = 0);
989
990 /**
991 * Erases the string, making it empty.
992 */
993 void
994 clear() _GLIBCXX_NOEXCEPTnoexcept
995 { _M_set_length(0); }
996
997 /**
998 * Returns true if the %string is empty. Equivalent to
999 * <code>*this == ""</code>.
1000 */
1001 _GLIBCXX_NODISCARD[[__nodiscard__]] bool
1002 empty() const _GLIBCXX_NOEXCEPTnoexcept
1003 { return this->size() == 0; }
1004
1005 // Element access:
1006 /**
1007 * @brief Subscript access to the data contained in the %string.
1008 * @param __pos The index of the character to access.
1009 * @return Read-only (constant) reference to the character.
1010 *
1011 * This operator allows for easy, array-style, data access.
1012 * Note that data access with this operator is unchecked and
1013 * out_of_range lookups are not defined. (For checked lookups
1014 * see at().)
1015 */
1016 const_reference
1017 operator[] (size_type __pos) const _GLIBCXX_NOEXCEPTnoexcept
1018 {
1019 __glibcxx_assert(__pos <= size())do { if (! (__pos <= size())) std::__replacement_assert("/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/basic_string.h"
, 1019, __PRETTY_FUNCTION__, "__pos <= size()"); } while (
false)
;
1020 return _M_data()[__pos];
1021 }
1022
1023 /**
1024 * @brief Subscript access to the data contained in the %string.
1025 * @param __pos The index of the character to access.
1026 * @return Read/write reference to the character.
1027 *
1028 * This operator allows for easy, array-style, data access.
1029 * Note that data access with this operator is unchecked and
1030 * out_of_range lookups are not defined. (For checked lookups
1031 * see at().)
1032 */
1033 reference
1034 operator[](size_type __pos)
1035 {
1036 // Allow pos == size() both in C++98 mode, as v3 extension,
1037 // and in C++11 mode.
1038 __glibcxx_assert(__pos <= size())do { if (! (__pos <= size())) std::__replacement_assert("/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/basic_string.h"
, 1038, __PRETTY_FUNCTION__, "__pos <= size()"); } while (
false)
;
1039 // In pedantic mode be strict in C++98 mode.
1040 _GLIBCXX_DEBUG_PEDASSERT(__cplusplus >= 201103L || __pos < size());
1041 return _M_data()[__pos];
1042 }
1043
1044 /**
1045 * @brief Provides access to the data contained in the %string.
1046 * @param __n The index of the character to access.
1047 * @return Read-only (const) reference to the character.
1048 * @throw std::out_of_range If @a n is an invalid index.
1049 *
1050 * This function provides for safer data access. The parameter is
1051 * first checked that it is in the range of the string. The function
1052 * throws out_of_range if the check fails.
1053 */
1054 const_reference
1055 at(size_type __n) const
1056 {
1057 if (__n >= this->size())
1058 __throw_out_of_range_fmt(__N("basic_string::at: __n "("basic_string::at: __n " "(which is %zu) >= this->size() "
"(which is %zu)")
1059 "(which is %zu) >= this->size() "("basic_string::at: __n " "(which is %zu) >= this->size() "
"(which is %zu)")
1060 "(which is %zu)")("basic_string::at: __n " "(which is %zu) >= this->size() "
"(which is %zu)")
,
1061 __n, this->size());
1062 return _M_data()[__n];
1063 }
1064
1065 /**
1066 * @brief Provides access to the data contained in the %string.
1067 * @param __n The index of the character to access.
1068 * @return Read/write reference to the character.
1069 * @throw std::out_of_range If @a n is an invalid index.
1070 *
1071 * This function provides for safer data access. The parameter is
1072 * first checked that it is in the range of the string. The function
1073 * throws out_of_range if the check fails.
1074 */
1075 reference
1076 at(size_type __n)
1077 {
1078 if (__n >= size())
1079 __throw_out_of_range_fmt(__N("basic_string::at: __n "("basic_string::at: __n " "(which is %zu) >= this->size() "
"(which is %zu)")
1080 "(which is %zu) >= this->size() "("basic_string::at: __n " "(which is %zu) >= this->size() "
"(which is %zu)")
1081 "(which is %zu)")("basic_string::at: __n " "(which is %zu) >= this->size() "
"(which is %zu)")
,
1082 __n, this->size());
1083 return _M_data()[__n];
1084 }
1085
1086#if __cplusplus201703L >= 201103L
1087 /**
1088 * Returns a read/write reference to the data at the first
1089 * element of the %string.
1090 */
1091 reference
1092 front() noexcept
1093 {
1094 __glibcxx_assert(!empty())do { if (! (!empty())) std::__replacement_assert("/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/basic_string.h"
, 1094, __PRETTY_FUNCTION__, "!empty()"); } while (false)
;
1095 return operator[](0);
1096 }
1097
1098 /**
1099 * Returns a read-only (constant) reference to the data at the first
1100 * element of the %string.
1101 */
1102 const_reference
1103 front() const noexcept
1104 {
1105 __glibcxx_assert(!empty())do { if (! (!empty())) std::__replacement_assert("/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/basic_string.h"
, 1105, __PRETTY_FUNCTION__, "!empty()"); } while (false)
;
1106 return operator[](0);
1107 }
1108
1109 /**
1110 * Returns a read/write reference to the data at the last
1111 * element of the %string.
1112 */
1113 reference
1114 back() noexcept
1115 {
1116 __glibcxx_assert(!empty())do { if (! (!empty())) std::__replacement_assert("/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/basic_string.h"
, 1116, __PRETTY_FUNCTION__, "!empty()"); } while (false)
;
1117 return operator[](this->size() - 1);
1118 }
1119
1120 /**
1121 * Returns a read-only (constant) reference to the data at the
1122 * last element of the %string.
1123 */
1124 const_reference
1125 back() const noexcept
1126 {
1127 __glibcxx_assert(!empty())do { if (! (!empty())) std::__replacement_assert("/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/basic_string.h"
, 1127, __PRETTY_FUNCTION__, "!empty()"); } while (false)
;
1128 return operator[](this->size() - 1);
1129 }
1130#endif
1131
1132 // Modifiers:
1133 /**
1134 * @brief Append a string to this string.
1135 * @param __str The string to append.
1136 * @return Reference to this string.
1137 */
1138 basic_string&
1139 operator+=(const basic_string& __str)
1140 { return this->append(__str); }
1141
1142 /**
1143 * @brief Append a C string.
1144 * @param __s The C string to append.
1145 * @return Reference to this string.
1146 */
1147 basic_string&
1148 operator+=(const _CharT* __s)
1149 { return this->append(__s); }
1150
1151 /**
1152 * @brief Append a character.
1153 * @param __c The character to append.
1154 * @return Reference to this string.
1155 */
1156 basic_string&
1157 operator+=(_CharT __c)
1158 {
1159 this->push_back(__c);
1160 return *this;
1161 }
1162
1163#if __cplusplus201703L >= 201103L
1164 /**
1165 * @brief Append an initializer_list of characters.
1166 * @param __l The initializer_list of characters to be appended.
1167 * @return Reference to this string.
1168 */
1169 basic_string&
1170 operator+=(initializer_list<_CharT> __l)
1171 { return this->append(__l.begin(), __l.size()); }
1172#endif // C++11
1173
1174#if __cplusplus201703L >= 201703L
1175 /**
1176 * @brief Append a string_view.
1177 * @param __svt An object convertible to string_view to be appended.
1178 * @return Reference to this string.
1179 */
1180 template<typename _Tp>
1181 _If_sv<_Tp, basic_string&>
1182 operator+=(const _Tp& __svt)
1183 { return this->append(__svt); }
1184#endif // C++17
1185
1186 /**
1187 * @brief Append a string to this string.
1188 * @param __str The string to append.
1189 * @return Reference to this string.
1190 */
1191 basic_string&
1192 append(const basic_string& __str)
1193 { return _M_append(__str._M_data(), __str.size()); }
1194
1195 /**
1196 * @brief Append a substring.
1197 * @param __str The string to append.
1198 * @param __pos Index of the first character of str to append.
1199 * @param __n The number of characters to append.
1200 * @return Reference to this string.
1201 * @throw std::out_of_range if @a __pos is not a valid index.
1202 *
1203 * This function appends @a __n characters from @a __str
1204 * starting at @a __pos to this string. If @a __n is is larger
1205 * than the number of available characters in @a __str, the
1206 * remainder of @a __str is appended.
1207 */
1208 basic_string&
1209 append(const basic_string& __str, size_type __pos, size_type __n = npos)
1210 { return _M_append(__str._M_data()
1211 + __str._M_check(__pos, "basic_string::append"),
1212 __str._M_limit(__pos, __n)); }
1213
1214 /**
1215 * @brief Append a C substring.
1216 * @param __s The C string to append.
1217 * @param __n The number of characters to append.
1218 * @return Reference to this string.
1219 */
1220 basic_string&
1221 append(const _CharT* __s, size_type __n)
1222 {
1223 __glibcxx_requires_string_len(__s, __n);
1224 _M_check_length(size_type(0), __n, "basic_string::append");
1225 return _M_append(__s, __n);
1226 }
1227
1228 /**
1229 * @brief Append a C string.
1230 * @param __s The C string to append.
1231 * @return Reference to this string.
1232 */
1233 basic_string&
1234 append(const _CharT* __s)
1235 {
1236 __glibcxx_requires_string(__s);
1237 const size_type __n = traits_type::length(__s);
1238 _M_check_length(size_type(0), __n, "basic_string::append");
1239 return _M_append(__s, __n);
1240 }
1241
1242 /**
1243 * @brief Append multiple characters.
1244 * @param __n The number of characters to append.
1245 * @param __c The character to use.
1246 * @return Reference to this string.
1247 *
1248 * Appends __n copies of __c to this string.
1249 */
1250 basic_string&
1251 append(size_type __n, _CharT __c)
1252 { return _M_replace_aux(this->size(), size_type(0), __n, __c); }
1253
1254#if __cplusplus201703L >= 201103L
1255 /**
1256 * @brief Append an initializer_list of characters.
1257 * @param __l The initializer_list of characters to append.
1258 * @return Reference to this string.
1259 */
1260 basic_string&
1261 append(initializer_list<_CharT> __l)
1262 { return this->append(__l.begin(), __l.size()); }
1263#endif // C++11
1264
1265 /**
1266 * @brief Append a range of characters.
1267 * @param __first Iterator referencing the first character to append.
1268 * @param __last Iterator marking the end of the range.
1269 * @return Reference to this string.
1270 *
1271 * Appends characters in the range [__first,__last) to this string.
1272 */
1273#if __cplusplus201703L >= 201103L
1274 template<class _InputIterator,
1275 typename = std::_RequireInputIter<_InputIterator>>
1276#else
1277 template<class _InputIterator>
1278#endif
1279 basic_string&
1280 append(_InputIterator __first, _InputIterator __last)
1281 { return this->replace(end(), end(), __first, __last); }
1282
1283#if __cplusplus201703L >= 201703L
1284 /**
1285 * @brief Append a string_view.
1286 * @param __svt An object convertible to string_view to be appended.
1287 * @return Reference to this string.
1288 */
1289 template<typename _Tp>
1290 _If_sv<_Tp, basic_string&>
1291 append(const _Tp& __svt)
1292 {
1293 __sv_type __sv = __svt;
1294 return this->append(__sv.data(), __sv.size());
1295 }
1296
1297 /**
1298 * @brief Append a range of characters from a string_view.
1299 * @param __svt An object convertible to string_view to be appended from.
1300 * @param __pos The position in the string_view to append from.
1301 * @param __n The number of characters to append from the string_view.
1302 * @return Reference to this string.
1303 */
1304 template<typename _Tp>
1305 _If_sv<_Tp, basic_string&>
1306 append(const _Tp& __svt, size_type __pos, size_type __n = npos)
1307 {
1308 __sv_type __sv = __svt;
1309 return _M_append(__sv.data()
1310 + std::__sv_check(__sv.size(), __pos, "basic_string::append"),
1311 std::__sv_limit(__sv.size(), __pos, __n));
1312 }
1313#endif // C++17
1314
1315 /**
1316 * @brief Append a single character.
1317 * @param __c Character to append.
1318 */
1319 void
1320 push_back(_CharT __c)
1321 {
1322 const size_type __size = this->size();
1323 if (__size + 1 > this->capacity())
1324 this->_M_mutate(__size, size_type(0), 0, size_type(1));
1325 traits_type::assign(this->_M_data()[__size], __c);
1326 this->_M_set_length(__size + 1);
1327 }
1328
1329 /**
1330 * @brief Set value to contents of another string.
1331 * @param __str Source string to use.
1332 * @return Reference to this string.
1333 */
1334 basic_string&
1335 assign(const basic_string& __str)
1336 {
1337#if __cplusplus201703L >= 201103L
1338 if (_Alloc_traits::_S_propagate_on_copy_assign())
1339 {
1340 if (!_Alloc_traits::_S_always_equal() && !_M_is_local()
1341 && _M_get_allocator() != __str._M_get_allocator())
1342 {
1343 // Propagating allocator cannot free existing storage so must
1344 // deallocate it before replacing current allocator.
1345 if (__str.size() <= _S_local_capacity)
1346 {
1347 _M_destroy(_M_allocated_capacity);
1348 _M_data(_M_local_data());
1349 _M_set_length(0);
1350 }
1351 else
1352 {
1353 const auto __len = __str.size();
1354 auto __alloc = __str._M_get_allocator();
1355 // If this allocation throws there are no effects:
1356 auto __ptr = _Alloc_traits::allocate(__alloc, __len + 1);
1357 _M_destroy(_M_allocated_capacity);
1358 _M_data(__ptr);
1359 _M_capacity(__len);
1360 _M_set_length(__len);
1361 }
1362 }
1363 std::__alloc_on_copy(_M_get_allocator(), __str._M_get_allocator());
1364 }
1365#endif
1366 this->_M_assign(__str);
1367 return *this;
1368 }
1369
1370#if __cplusplus201703L >= 201103L
1371 /**
1372 * @brief Set value to contents of another string.
1373 * @param __str Source string to use.
1374 * @return Reference to this string.
1375 *
1376 * This function sets this string to the exact contents of @a __str.
1377 * @a __str is a valid, but unspecified string.
1378 */
1379 basic_string&
1380 assign(basic_string&& __str)
1381 noexcept(_Alloc_traits::_S_nothrow_move())
1382 {
1383 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1384 // 2063. Contradictory requirements for string move assignment
1385 return *this = std::move(__str);
1386 }
1387#endif // C++11
1388
1389 /**
1390 * @brief Set value to a substring of a string.
1391 * @param __str The string to use.
1392 * @param __pos Index of the first character of str.
1393 * @param __n Number of characters to use.
1394 * @return Reference to this string.
1395 * @throw std::out_of_range if @a pos is not a valid index.
1396 *
1397 * This function sets this string to the substring of @a __str
1398 * consisting of @a __n characters at @a __pos. If @a __n is
1399 * is larger than the number of available characters in @a
1400 * __str, the remainder of @a __str is used.
1401 */
1402 basic_string&
1403 assign(const basic_string& __str, size_type __pos, size_type __n = npos)
1404 { return _M_replace(size_type(0), this->size(), __str._M_data()
1405 + __str._M_check(__pos, "basic_string::assign"),
1406 __str._M_limit(__pos, __n)); }
1407
1408 /**
1409 * @brief Set value to a C substring.
1410 * @param __s The C string to use.
1411 * @param __n Number of characters to use.
1412 * @return Reference to this string.
1413 *
1414 * This function sets the value of this string to the first @a __n
1415 * characters of @a __s. If @a __n is is larger than the number of
1416 * available characters in @a __s, the remainder of @a __s is used.
1417 */
1418 basic_string&
1419 assign(const _CharT* __s, size_type __n)
1420 {
1421 __glibcxx_requires_string_len(__s, __n);
1422 return _M_replace(size_type(0), this->size(), __s, __n);
1423 }
1424
1425 /**
1426 * @brief Set value to contents of a C string.
1427 * @param __s The C string to use.
1428 * @return Reference to this string.
1429 *
1430 * This function sets the value of this string to the value of @a __s.
1431 * The data is copied, so there is no dependence on @a __s once the
1432 * function returns.
1433 */
1434 basic_string&
1435 assign(const _CharT* __s)
1436 {
1437 __glibcxx_requires_string(__s);
1438 return _M_replace(size_type(0), this->size(), __s,
1439 traits_type::length(__s));
1440 }
1441
1442 /**
1443 * @brief Set value to multiple characters.
1444 * @param __n Length of the resulting string.
1445 * @param __c The character to use.
1446 * @return Reference to this string.
1447 *
1448 * This function sets the value of this string to @a __n copies of
1449 * character @a __c.
1450 */
1451 basic_string&
1452 assign(size_type __n, _CharT __c)
1453 { return _M_replace_aux(size_type(0), this->size(), __n, __c); }
1454
1455 /**
1456 * @brief Set value to a range of characters.
1457 * @param __first Iterator referencing the first character to append.
1458 * @param __last Iterator marking the end of the range.
1459 * @return Reference to this string.
1460 *
1461 * Sets value of string to characters in the range [__first,__last).
1462 */
1463#if __cplusplus201703L >= 201103L
1464 template<class _InputIterator,
1465 typename = std::_RequireInputIter<_InputIterator>>
1466#else
1467 template<class _InputIterator>
1468#endif
1469 basic_string&
1470 assign(_InputIterator __first, _InputIterator __last)
1471 { return this->replace(begin(), end(), __first, __last); }
1472
1473#if __cplusplus201703L >= 201103L
1474 /**
1475 * @brief Set value to an initializer_list of characters.
1476 * @param __l The initializer_list of characters to assign.
1477 * @return Reference to this string.
1478 */
1479 basic_string&
1480 assign(initializer_list<_CharT> __l)
1481 { return this->assign(__l.begin(), __l.size()); }
1482#endif // C++11
1483
1484#if __cplusplus201703L >= 201703L
1485 /**
1486 * @brief Set value from a string_view.
1487 * @param __svt The source object convertible to string_view.
1488 * @return Reference to this string.
1489 */
1490 template<typename _Tp>
1491 _If_sv<_Tp, basic_string&>
1492 assign(const _Tp& __svt)
1493 {
1494 __sv_type __sv = __svt;
1495 return this->assign(__sv.data(), __sv.size());
1496 }
1497
1498 /**
1499 * @brief Set value from a range of characters in a string_view.
1500 * @param __svt The source object convertible to string_view.
1501 * @param __pos The position in the string_view to assign from.
1502 * @param __n The number of characters to assign.
1503 * @return Reference to this string.
1504 */
1505 template<typename _Tp>
1506 _If_sv<_Tp, basic_string&>
1507 assign(const _Tp& __svt, size_type __pos, size_type __n = npos)
1508 {
1509 __sv_type __sv = __svt;
1510 return _M_replace(size_type(0), this->size(),
1511 __sv.data()
1512 + std::__sv_check(__sv.size(), __pos, "basic_string::assign"),
1513 std::__sv_limit(__sv.size(), __pos, __n));
1514 }
1515#endif // C++17
1516
1517#if __cplusplus201703L >= 201103L
1518 /**
1519 * @brief Insert multiple characters.
1520 * @param __p Const_iterator referencing location in string to
1521 * insert at.
1522 * @param __n Number of characters to insert
1523 * @param __c The character to insert.
1524 * @return Iterator referencing the first inserted char.
1525 * @throw std::length_error If new length exceeds @c max_size().
1526 *
1527 * Inserts @a __n copies of character @a __c starting at the
1528 * position referenced by iterator @a __p. If adding
1529 * characters causes the length to exceed max_size(),
1530 * length_error is thrown. The value of the string doesn't
1531 * change if an error is thrown.
1532 */
1533 iterator
1534 insert(const_iterator __p, size_type __n, _CharT __c)
1535 {
1536 _GLIBCXX_DEBUG_PEDASSERT(__p >= begin() && __p <= end());
1537 const size_type __pos = __p - begin();
1538 this->replace(__p, __p, __n, __c);
1539 return iterator(this->_M_data() + __pos);
1540 }
1541#else
1542 /**
1543 * @brief Insert multiple characters.
1544 * @param __p Iterator referencing location in string to insert at.
1545 * @param __n Number of characters to insert
1546 * @param __c The character to insert.
1547 * @throw std::length_error If new length exceeds @c max_size().
1548 *
1549 * Inserts @a __n copies of character @a __c starting at the
1550 * position referenced by iterator @a __p. If adding
1551 * characters causes the length to exceed max_size(),
1552 * length_error is thrown. The value of the string doesn't
1553 * change if an error is thrown.
1554 */
1555 void
1556 insert(iterator __p, size_type __n, _CharT __c)
1557 { this->replace(__p, __p, __n, __c); }
1558#endif
1559
1560#if __cplusplus201703L >= 201103L
1561 /**
1562 * @brief Insert a range of characters.
1563 * @param __p Const_iterator referencing location in string to
1564 * insert at.
1565 * @param __beg Start of range.
1566 * @param __end End of range.
1567 * @return Iterator referencing the first inserted char.
1568 * @throw std::length_error If new length exceeds @c max_size().
1569 *
1570 * Inserts characters in range [beg,end). If adding characters
1571 * causes the length to exceed max_size(), length_error is
1572 * thrown. The value of the string doesn't change if an error
1573 * is thrown.
1574 */
1575 template<class _InputIterator,
1576 typename = std::_RequireInputIter<_InputIterator>>
1577 iterator
1578 insert(const_iterator __p, _InputIterator __beg, _InputIterator __end)
1579 {
1580 _GLIBCXX_DEBUG_PEDASSERT(__p >= begin() && __p <= end());
1581 const size_type __pos = __p - begin();
1582 this->replace(__p, __p, __beg, __end);
1583 return iterator(this->_M_data() + __pos);
1584 }
1585#else
1586 /**
1587 * @brief Insert a range of characters.
1588 * @param __p Iterator referencing location in string to insert at.
1589 * @param __beg Start of range.
1590 * @param __end End of range.
1591 * @throw std::length_error If new length exceeds @c max_size().
1592 *
1593 * Inserts characters in range [__beg,__end). If adding
1594 * characters causes the length to exceed max_size(),
1595 * length_error is thrown. The value of the string doesn't
1596 * change if an error is thrown.
1597 */
1598 template<class _InputIterator>
1599 void
1600 insert(iterator __p, _InputIterator __beg, _InputIterator __end)
1601 { this->replace(__p, __p, __beg, __end); }
1602#endif
1603
1604#if __cplusplus201703L >= 201103L
1605 /**
1606 * @brief Insert an initializer_list of characters.
1607 * @param __p Iterator referencing location in string to insert at.
1608 * @param __l The initializer_list of characters to insert.
1609 * @throw std::length_error If new length exceeds @c max_size().
1610 */
1611 iterator
1612 insert(const_iterator __p, initializer_list<_CharT> __l)
1613 { return this->insert(__p, __l.begin(), __l.end()); }
1614
1615#ifdef _GLIBCXX_DEFINING_STRING_INSTANTIATIONS
1616 // See PR libstdc++/83328
1617 void
1618 insert(iterator __p, initializer_list<_CharT> __l)
1619 {
1620 _GLIBCXX_DEBUG_PEDASSERT(__p >= begin() && __p <= end());
1621 this->insert(__p - begin(), __l.begin(), __l.size());
1622 }
1623#endif
1624#endif // C++11
1625
1626 /**
1627 * @brief Insert value of a string.
1628 * @param __pos1 Position in string to insert at.
1629 * @param __str The string to insert.
1630 * @return Reference to this string.
1631 * @throw std::length_error If new length exceeds @c max_size().
1632 *
1633 * Inserts value of @a __str starting at @a __pos1. If adding
1634 * characters causes the length to exceed max_size(),
1635 * length_error is thrown. The value of the string doesn't
1636 * change if an error is thrown.
1637 */
1638 basic_string&
1639 insert(size_type __pos1, const basic_string& __str)
1640 { return this->replace(__pos1, size_type(0),
1641 __str._M_data(), __str.size()); }
1642
1643 /**
1644 * @brief Insert a substring.
1645 * @param __pos1 Position in string to insert at.
1646 * @param __str The string to insert.
1647 * @param __pos2 Start of characters in str to insert.
1648 * @param __n Number of characters to insert.
1649 * @return Reference to this string.
1650 * @throw std::length_error If new length exceeds @c max_size().
1651 * @throw std::out_of_range If @a pos1 > size() or
1652 * @a __pos2 > @a str.size().
1653 *
1654 * Starting at @a pos1, insert @a __n character of @a __str
1655 * beginning with @a __pos2. If adding characters causes the
1656 * length to exceed max_size(), length_error is thrown. If @a
1657 * __pos1 is beyond the end of this string or @a __pos2 is
1658 * beyond the end of @a __str, out_of_range is thrown. The
1659 * value of the string doesn't change if an error is thrown.
1660 */
1661 basic_string&
1662 insert(size_type __pos1, const basic_string& __str,
1663 size_type __pos2, size_type __n = npos)
1664 { return this->replace(__pos1, size_type(0), __str._M_data()
1665 + __str._M_check(__pos2, "basic_string::insert"),
1666 __str._M_limit(__pos2, __n)); }
1667
1668 /**
1669 * @brief Insert a C substring.
1670 * @param __pos Position in string to insert at.
1671 * @param __s The C string to insert.
1672 * @param __n The number of characters to insert.
1673 * @return Reference to this string.
1674 * @throw std::length_error If new length exceeds @c max_size().
1675 * @throw std::out_of_range If @a __pos is beyond the end of this
1676 * string.
1677 *
1678 * Inserts the first @a __n characters of @a __s starting at @a
1679 * __pos. If adding characters causes the length to exceed
1680 * max_size(), length_error is thrown. If @a __pos is beyond
1681 * end(), out_of_range is thrown. The value of the string
1682 * doesn't change if an error is thrown.
1683 */
1684 basic_string&
1685 insert(size_type __pos, const _CharT* __s, size_type __n)
1686 { return this->replace(__pos, size_type(0), __s, __n); }
1687
1688 /**
1689 * @brief Insert a C string.
1690 * @param __pos Position in string to insert at.
1691 * @param __s The C string to insert.
1692 * @return Reference to this string.
1693 * @throw std::length_error If new length exceeds @c max_size().
1694 * @throw std::out_of_range If @a pos is beyond the end of this
1695 * string.
1696 *
1697 * Inserts the first @a n characters of @a __s starting at @a __pos. If
1698 * adding characters causes the length to exceed max_size(),
1699 * length_error is thrown. If @a __pos is beyond end(), out_of_range is
1700 * thrown. The value of the string doesn't change if an error is
1701 * thrown.
1702 */
1703 basic_string&
1704 insert(size_type __pos, const _CharT* __s)
1705 {
1706 __glibcxx_requires_string(__s);
1707 return this->replace(__pos, size_type(0), __s,
1708 traits_type::length(__s));
1709 }
1710
1711 /**
1712 * @brief Insert multiple characters.
1713 * @param __pos Index in string to insert at.
1714 * @param __n Number of characters to insert
1715 * @param __c The character to insert.
1716 * @return Reference to this string.
1717 * @throw std::length_error If new length exceeds @c max_size().
1718 * @throw std::out_of_range If @a __pos is beyond the end of this
1719 * string.
1720 *
1721 * Inserts @a __n copies of character @a __c starting at index
1722 * @a __pos. If adding characters causes the length to exceed
1723 * max_size(), length_error is thrown. If @a __pos > length(),
1724 * out_of_range is thrown. The value of the string doesn't
1725 * change if an error is thrown.
1726 */
1727 basic_string&
1728 insert(size_type __pos, size_type __n, _CharT __c)
1729 { return _M_replace_aux(_M_check(__pos, "basic_string::insert"),
1730 size_type(0), __n, __c); }
1731
1732 /**
1733 * @brief Insert one character.
1734 * @param __p Iterator referencing position in string to insert at.
1735 * @param __c The character to insert.
1736 * @return Iterator referencing newly inserted char.
1737 * @throw std::length_error If new length exceeds @c max_size().
1738 *
1739 * Inserts character @a __c at position referenced by @a __p.
1740 * If adding character causes the length to exceed max_size(),
1741 * length_error is thrown. If @a __p is beyond end of string,
1742 * out_of_range is thrown. The value of the string doesn't
1743 * change if an error is thrown.
1744 */
1745 iterator
1746 insert(__const_iterator __p, _CharT __c)
1747 {
1748 _GLIBCXX_DEBUG_PEDASSERT(__p >= begin() && __p <= end());
1749 const size_type __pos = __p - begin();
1750 _M_replace_aux(__pos, size_type(0), size_type(1), __c);
1751 return iterator(_M_data() + __pos);
1752 }
1753
1754#if __cplusplus201703L >= 201703L
1755 /**
1756 * @brief Insert a string_view.
1757 * @param __pos Position in string to insert at.
1758 * @param __svt The object convertible to string_view to insert.
1759 * @return Reference to this string.
1760 */
1761 template<typename _Tp>
1762 _If_sv<_Tp, basic_string&>
1763 insert(size_type __pos, const _Tp& __svt)
1764 {
1765 __sv_type __sv = __svt;
1766 return this->insert(__pos, __sv.data(), __sv.size());
1767 }
1768
1769 /**
1770 * @brief Insert a string_view.
1771 * @param __pos1 Position in string to insert at.
1772 * @param __svt The object convertible to string_view to insert from.
1773 * @param __pos2 Start of characters in str to insert.
1774 * @param __n The number of characters to insert.
1775 * @return Reference to this string.
1776 */
1777 template<typename _Tp>
1778 _If_sv<_Tp, basic_string&>
1779 insert(size_type __pos1, const _Tp& __svt,
1780 size_type __pos2, size_type __n = npos)
1781 {
1782 __sv_type __sv = __svt;
1783 return this->replace(__pos1, size_type(0),
1784 __sv.data()
1785 + std::__sv_check(__sv.size(), __pos2, "basic_string::insert"),
1786 std::__sv_limit(__sv.size(), __pos2, __n));
1787 }
1788#endif // C++17
1789
1790 /**
1791 * @brief Remove characters.
1792 * @param __pos Index of first character to remove (default 0).
1793 * @param __n Number of characters to remove (default remainder).
1794 * @return Reference to this string.
1795 * @throw std::out_of_range If @a pos is beyond the end of this
1796 * string.
1797 *
1798 * Removes @a __n characters from this string starting at @a
1799 * __pos. The length of the string is reduced by @a __n. If
1800 * there are < @a __n characters to remove, the remainder of
1801 * the string is truncated. If @a __p is beyond end of string,
1802 * out_of_range is thrown. The value of the string doesn't
1803 * change if an error is thrown.
1804 */
1805 basic_string&
1806 erase(size_type __pos = 0, size_type __n = npos)
1807 {
1808 _M_check(__pos, "basic_string::erase");
1809 if (__n == npos)
1810 this->_M_set_length(__pos);
1811 else if (__n != 0)
1812 this->_M_erase(__pos, _M_limit(__pos, __n));
1813 return *this;
1814 }
1815
1816 /**
1817 * @brief Remove one character.
1818 * @param __position Iterator referencing the character to remove.
1819 * @return iterator referencing same location after removal.
1820 *
1821 * Removes the character at @a __position from this string. The value
1822 * of the string doesn't change if an error is thrown.
1823 */
1824 iterator
1825 erase(__const_iterator __position)
1826 {
1827 _GLIBCXX_DEBUG_PEDASSERT(__position >= begin()
1828 && __position < end());
1829 const size_type __pos = __position - begin();
1830 this->_M_erase(__pos, size_type(1));
1831 return iterator(_M_data() + __pos);
1832 }
1833
1834 /**
1835 * @brief Remove a range of characters.
1836 * @param __first Iterator referencing the first character to remove.
1837 * @param __last Iterator referencing the end of the range.
1838 * @return Iterator referencing location of first after removal.
1839 *
1840 * Removes the characters in the range [first,last) from this string.
1841 * The value of the string doesn't change if an error is thrown.
1842 */
1843 iterator
1844 erase(__const_iterator __first, __const_iterator __last)
1845 {
1846 _GLIBCXX_DEBUG_PEDASSERT(__first >= begin() && __first <= __last
1847 && __last <= end());
1848 const size_type __pos = __first - begin();
1849 if (__last == end())
1850 this->_M_set_length(__pos);
1851 else
1852 this->_M_erase(__pos, __last - __first);
1853 return iterator(this->_M_data() + __pos);
1854 }
1855
1856#if __cplusplus201703L >= 201103L
1857 /**
1858 * @brief Remove the last character.
1859 *
1860 * The string must be non-empty.
1861 */
1862 void
1863 pop_back() noexcept
1864 {
1865 __glibcxx_assert(!empty())do { if (! (!empty())) std::__replacement_assert("/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/basic_string.h"
, 1865, __PRETTY_FUNCTION__, "!empty()"); } while (false)
;
1866 _M_erase(size() - 1, 1);
1867 }
1868#endif // C++11
1869
1870 /**
1871 * @brief Replace characters with value from another string.
1872 * @param __pos Index of first character to replace.
1873 * @param __n Number of characters to be replaced.
1874 * @param __str String to insert.
1875 * @return Reference to this string.
1876 * @throw std::out_of_range If @a pos is beyond the end of this
1877 * string.
1878 * @throw std::length_error If new length exceeds @c max_size().
1879 *
1880 * Removes the characters in the range [__pos,__pos+__n) from
1881 * this string. In place, the value of @a __str is inserted.
1882 * If @a __pos is beyond end of string, out_of_range is thrown.
1883 * If the length of the result exceeds max_size(), length_error
1884 * is thrown. The value of the string doesn't change if an
1885 * error is thrown.
1886 */
1887 basic_string&
1888 replace(size_type __pos, size_type __n, const basic_string& __str)
1889 { return this->replace(__pos, __n, __str._M_data(), __str.size()); }
1890
1891 /**
1892 * @brief Replace characters with value from another string.
1893 * @param __pos1 Index of first character to replace.
1894 * @param __n1 Number of characters to be replaced.
1895 * @param __str String to insert.
1896 * @param __pos2 Index of first character of str to use.
1897 * @param __n2 Number of characters from str to use.
1898 * @return Reference to this string.
1899 * @throw std::out_of_range If @a __pos1 > size() or @a __pos2 >
1900 * __str.size().
1901 * @throw std::length_error If new length exceeds @c max_size().
1902 *
1903 * Removes the characters in the range [__pos1,__pos1 + n) from this
1904 * string. In place, the value of @a __str is inserted. If @a __pos is
1905 * beyond end of string, out_of_range is thrown. If the length of the
1906 * result exceeds max_size(), length_error is thrown. The value of the
1907 * string doesn't change if an error is thrown.
1908 */
1909 basic_string&
1910 replace(size_type __pos1, size_type __n1, const basic_string& __str,
1911 size_type __pos2, size_type __n2 = npos)
1912 { return this->replace(__pos1, __n1, __str._M_data()
1913 + __str._M_check(__pos2, "basic_string::replace"),
1914 __str._M_limit(__pos2, __n2)); }
1915
1916 /**
1917 * @brief Replace characters with value of a C substring.
1918 * @param __pos Index of first character to replace.
1919 * @param __n1 Number of characters to be replaced.
1920 * @param __s C string to insert.
1921 * @param __n2 Number of characters from @a s to use.
1922 * @return Reference to this string.
1923 * @throw std::out_of_range If @a pos1 > size().
1924 * @throw std::length_error If new length exceeds @c max_size().
1925 *
1926 * Removes the characters in the range [__pos,__pos + __n1)
1927 * from this string. In place, the first @a __n2 characters of
1928 * @a __s are inserted, or all of @a __s if @a __n2 is too large. If
1929 * @a __pos is beyond end of string, out_of_range is thrown. If
1930 * the length of result exceeds max_size(), length_error is
1931 * thrown. The value of the string doesn't change if an error
1932 * is thrown.
1933 */
1934 basic_string&
1935 replace(size_type __pos, size_type __n1, const _CharT* __s,
1936 size_type __n2)
1937 {
1938 __glibcxx_requires_string_len(__s, __n2);
1939 return _M_replace(_M_check(__pos, "basic_string::replace"),
1940 _M_limit(__pos, __n1), __s, __n2);
1941 }
1942
1943 /**
1944 * @brief Replace characters with value of a C string.
1945 * @param __pos Index of first character to replace.
1946 * @param __n1 Number of characters to be replaced.
1947 * @param __s C string to insert.
1948 * @return Reference to this string.
1949 * @throw std::out_of_range If @a pos > size().
1950 * @throw std::length_error If new length exceeds @c max_size().
1951 *
1952 * Removes the characters in the range [__pos,__pos + __n1)
1953 * from this string. In place, the characters of @a __s are
1954 * inserted. If @a __pos is beyond end of string, out_of_range
1955 * is thrown. If the length of result exceeds max_size(),
1956 * length_error is thrown. The value of the string doesn't
1957 * change if an error is thrown.
1958 */
1959 basic_string&
1960 replace(size_type __pos, size_type __n1, const _CharT* __s)
1961 {
1962 __glibcxx_requires_string(__s);
1963 return this->replace(__pos, __n1, __s, traits_type::length(__s));
1964 }
1965
1966 /**
1967 * @brief Replace characters with multiple characters.
1968 * @param __pos Index of first character to replace.
1969 * @param __n1 Number of characters to be replaced.
1970 * @param __n2 Number of characters to insert.
1971 * @param __c Character to insert.
1972 * @return Reference to this string.
1973 * @throw std::out_of_range If @a __pos > size().
1974 * @throw std::length_error If new length exceeds @c max_size().
1975 *
1976 * Removes the characters in the range [pos,pos + n1) from this
1977 * string. In place, @a __n2 copies of @a __c are inserted.
1978 * If @a __pos is beyond end of string, out_of_range is thrown.
1979 * If the length of result exceeds max_size(), length_error is
1980 * thrown. The value of the string doesn't change if an error
1981 * is thrown.
1982 */
1983 basic_string&
1984 replace(size_type __pos, size_type __n1, size_type __n2, _CharT __c)
1985 { return _M_replace_aux(_M_check(__pos, "basic_string::replace"),
1986 _M_limit(__pos, __n1), __n2, __c); }
1987
1988 /**
1989 * @brief Replace range of characters with string.
1990 * @param __i1 Iterator referencing start of range to replace.
1991 * @param __i2 Iterator referencing end of range to replace.
1992 * @param __str String value to insert.
1993 * @return Reference to this string.
1994 * @throw std::length_error If new length exceeds @c max_size().
1995 *
1996 * Removes the characters in the range [__i1,__i2). In place,
1997 * the value of @a __str is inserted. If the length of result
1998 * exceeds max_size(), length_error is thrown. The value of
1999 * the string doesn't change if an error is thrown.
2000 */
2001 basic_string&
2002 replace(__const_iterator __i1, __const_iterator __i2,
2003 const basic_string& __str)
2004 { return this->replace(__i1, __i2, __str._M_data(), __str.size()); }
2005
2006 /**
2007 * @brief Replace range of characters with C substring.
2008 * @param __i1 Iterator referencing start of range to replace.
2009 * @param __i2 Iterator referencing end of range to replace.
2010 * @param __s C string value to insert.
2011 * @param __n Number of characters from s to insert.
2012 * @return Reference to this string.
2013 * @throw std::length_error If new length exceeds @c max_size().
2014 *
2015 * Removes the characters in the range [__i1,__i2). In place,
2016 * the first @a __n characters of @a __s are inserted. If the
2017 * length of result exceeds max_size(), length_error is thrown.
2018 * The value of the string doesn't change if an error is
2019 * thrown.
2020 */
2021 basic_string&
2022 replace(__const_iterator __i1, __const_iterator __i2,
2023 const _CharT* __s, size_type __n)
2024 {
2025 _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2
2026 && __i2 <= end());
2027 return this->replace(__i1 - begin(), __i2 - __i1, __s, __n);
2028 }
2029
2030 /**
2031 * @brief Replace range of characters with C string.
2032 * @param __i1 Iterator referencing start of range to replace.
2033 * @param __i2 Iterator referencing end of range to replace.
2034 * @param __s C string value to insert.
2035 * @return Reference to this string.
2036 * @throw std::length_error If new length exceeds @c max_size().
2037 *
2038 * Removes the characters in the range [__i1,__i2). In place,
2039 * the characters of @a __s are inserted. If the length of
2040 * result exceeds max_size(), length_error is thrown. The
2041 * value of the string doesn't change if an error is thrown.
2042 */
2043 basic_string&
2044 replace(__const_iterator __i1, __const_iterator __i2, const _CharT* __s)
2045 {
2046 __glibcxx_requires_string(__s);
2047 return this->replace(__i1, __i2, __s, traits_type::length(__s));
2048 }
2049
2050 /**
2051 * @brief Replace range of characters with multiple characters
2052 * @param __i1 Iterator referencing start of range to replace.
2053 * @param __i2 Iterator referencing end of range to replace.
2054 * @param __n Number of characters to insert.
2055 * @param __c Character to insert.
2056 * @return Reference to this string.
2057 * @throw std::length_error If new length exceeds @c max_size().
2058 *
2059 * Removes the characters in the range [__i1,__i2). In place,
2060 * @a __n copies of @a __c are inserted. If the length of
2061 * result exceeds max_size(), length_error is thrown. The
2062 * value of the string doesn't change if an error is thrown.
2063 */
2064 basic_string&
2065 replace(__const_iterator __i1, __const_iterator __i2, size_type __n,
2066 _CharT __c)
2067 {
2068 _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2
2069 && __i2 <= end());
2070 return _M_replace_aux(__i1 - begin(), __i2 - __i1, __n, __c);
2071 }
2072
2073 /**
2074 * @brief Replace range of characters with range.
2075 * @param __i1 Iterator referencing start of range to replace.
2076 * @param __i2 Iterator referencing end of range to replace.
2077 * @param __k1 Iterator referencing start of range to insert.
2078 * @param __k2 Iterator referencing end of range to insert.
2079 * @return Reference to this string.
2080 * @throw std::length_error If new length exceeds @c max_size().
2081 *
2082 * Removes the characters in the range [__i1,__i2). In place,
2083 * characters in the range [__k1,__k2) are inserted. If the
2084 * length of result exceeds max_size(), length_error is thrown.
2085 * The value of the string doesn't change if an error is
2086 * thrown.
2087 */
2088#if __cplusplus201703L >= 201103L
2089 template<class _InputIterator,
2090 typename = std::_RequireInputIter<_InputIterator>>
2091 basic_string&
2092 replace(const_iterator __i1, const_iterator __i2,
2093 _InputIterator __k1, _InputIterator __k2)
2094 {
2095 _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2
2096 && __i2 <= end());
2097 __glibcxx_requires_valid_range(__k1, __k2);
2098 return this->_M_replace_dispatch(__i1, __i2, __k1, __k2,
2099 std::__false_type());
2100 }
2101#else
2102 template<class _InputIterator>
2103#ifdef _GLIBCXX_DISAMBIGUATE_REPLACE_INST
2104 typename __enable_if_not_native_iterator<_InputIterator>::__type
2105#else
2106 basic_string&
2107#endif
2108 replace(iterator __i1, iterator __i2,
2109 _InputIterator __k1, _InputIterator __k2)
2110 {
2111 _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2
2112 && __i2 <= end());
2113 __glibcxx_requires_valid_range(__k1, __k2);
2114 typedef typename std::__is_integer<_InputIterator>::__type _Integral;
2115 return _M_replace_dispatch(__i1, __i2, __k1, __k2, _Integral());
2116 }
2117#endif
2118
2119 // Specializations for the common case of pointer and iterator:
2120 // useful to avoid the overhead of temporary buffering in _M_replace.
2121 basic_string&
2122 replace(__const_iterator __i1, __const_iterator __i2,
2123 _CharT* __k1, _CharT* __k2)
2124 {
2125 _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2
2126 && __i2 <= end());
2127 __glibcxx_requires_valid_range(__k1, __k2);
2128 return this->replace(__i1 - begin(), __i2 - __i1,
2129 __k1, __k2 - __k1);
2130 }
2131
2132 basic_string&
2133 replace(__const_iterator __i1, __const_iterator __i2,
2134 const _CharT* __k1, const _CharT* __k2)
2135 {
2136 _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2
2137 && __i2 <= end());
2138 __glibcxx_requires_valid_range(__k1, __k2);
2139 return this->replace(__i1 - begin(), __i2 - __i1,
2140 __k1, __k2 - __k1);
2141 }
2142
2143 basic_string&
2144 replace(__const_iterator __i1, __const_iterator __i2,
2145 iterator __k1, iterator __k2)
2146 {
2147 _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2
2148 && __i2 <= end());
2149 __glibcxx_requires_valid_range(__k1, __k2);
2150 return this->replace(__i1 - begin(), __i2 - __i1,
2151 __k1.base(), __k2 - __k1);
2152 }
2153
2154 basic_string&
2155 replace(__const_iterator __i1, __const_iterator __i2,
2156 const_iterator __k1, const_iterator __k2)
2157 {
2158 _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2
2159 && __i2 <= end());
2160 __glibcxx_requires_valid_range(__k1, __k2);
2161 return this->replace(__i1 - begin(), __i2 - __i1,
2162 __k1.base(), __k2 - __k1);
2163 }
2164
2165#if __cplusplus201703L >= 201103L
2166 /**
2167 * @brief Replace range of characters with initializer_list.
2168 * @param __i1 Iterator referencing start of range to replace.
2169 * @param __i2 Iterator referencing end of range to replace.
2170 * @param __l The initializer_list of characters to insert.
2171 * @return Reference to this string.
2172 * @throw std::length_error If new length exceeds @c max_size().
2173 *
2174 * Removes the characters in the range [__i1,__i2). In place,
2175 * characters in the range [__k1,__k2) are inserted. If the
2176 * length of result exceeds max_size(), length_error is thrown.
2177 * The value of the string doesn't change if an error is
2178 * thrown.
2179 */
2180 basic_string& replace(const_iterator __i1, const_iterator __i2,
2181 initializer_list<_CharT> __l)
2182 { return this->replace(__i1, __i2, __l.begin(), __l.size()); }
2183#endif // C++11
2184
2185#if __cplusplus201703L >= 201703L
2186 /**
2187 * @brief Replace range of characters with string_view.
2188 * @param __pos The position to replace at.
2189 * @param __n The number of characters to replace.
2190 * @param __svt The object convertible to string_view to insert.
2191 * @return Reference to this string.
2192 */
2193 template<typename _Tp>
2194 _If_sv<_Tp, basic_string&>
2195 replace(size_type __pos, size_type __n, const _Tp& __svt)
2196 {
2197 __sv_type __sv = __svt;
2198 return this->replace(__pos, __n, __sv.data(), __sv.size());
2199 }
2200
2201 /**
2202 * @brief Replace range of characters with string_view.
2203 * @param __pos1 The position to replace at.
2204 * @param __n1 The number of characters to replace.
2205 * @param __svt The object convertible to string_view to insert from.
2206 * @param __pos2 The position in the string_view to insert from.
2207 * @param __n2 The number of characters to insert.
2208 * @return Reference to this string.
2209 */
2210 template<typename _Tp>
2211 _If_sv<_Tp, basic_string&>
2212 replace(size_type __pos1, size_type __n1, const _Tp& __svt,
2213 size_type __pos2, size_type __n2 = npos)
2214 {
2215 __sv_type __sv = __svt;
2216 return this->replace(__pos1, __n1,
2217 __sv.data()
2218 + std::__sv_check(__sv.size(), __pos2, "basic_string::replace"),
2219 std::__sv_limit(__sv.size(), __pos2, __n2));
2220 }
2221
2222 /**
2223 * @brief Replace range of characters with string_view.
2224 * @param __i1 An iterator referencing the start position
2225 to replace at.
2226 * @param __i2 An iterator referencing the end position
2227 for the replace.
2228 * @param __svt The object convertible to string_view to insert from.
2229 * @return Reference to this string.
2230 */
2231 template<typename _Tp>
2232 _If_sv<_Tp, basic_string&>
2233 replace(const_iterator __i1, const_iterator __i2, const _Tp& __svt)
2234 {
2235 __sv_type __sv = __svt;
2236 return this->replace(__i1 - begin(), __i2 - __i1, __sv);
2237 }
2238#endif // C++17
2239
2240 private:
2241 template<class _Integer>
2242 basic_string&
2243 _M_replace_dispatch(const_iterator __i1, const_iterator __i2,
2244 _Integer __n, _Integer __val, __true_type)
2245 { return _M_replace_aux(__i1 - begin(), __i2 - __i1, __n, __val); }
2246
2247 template<class _InputIterator>
2248 basic_string&
2249 _M_replace_dispatch(const_iterator __i1, const_iterator __i2,
2250 _InputIterator __k1, _InputIterator __k2,
2251 __false_type);
2252
2253 basic_string&
2254 _M_replace_aux(size_type __pos1, size_type __n1, size_type __n2,
2255 _CharT __c);
2256
2257 basic_string&
2258 _M_replace(size_type __pos, size_type __len1, const _CharT* __s,
2259 const size_type __len2);
2260
2261 basic_string&
2262 _M_append(const _CharT* __s, size_type __n);
2263
2264 public:
2265
2266 /**
2267 * @brief Copy substring into C string.
2268 * @param __s C string to copy value into.
2269 * @param __n Number of characters to copy.
2270 * @param __pos Index of first character to copy.
2271 * @return Number of characters actually copied
2272 * @throw std::out_of_range If __pos > size().
2273 *
2274 * Copies up to @a __n characters starting at @a __pos into the
2275 * C string @a __s. If @a __pos is %greater than size(),
2276 * out_of_range is thrown.
2277 */
2278 size_type
2279 copy(_CharT* __s, size_type __n, size_type __pos = 0) const;
2280
2281 /**
2282 * @brief Swap contents with another string.
2283 * @param __s String to swap with.
2284 *
2285 * Exchanges the contents of this string with that of @a __s in constant
2286 * time.
2287 */
2288 void
2289 swap(basic_string& __s) _GLIBCXX_NOEXCEPTnoexcept;
2290
2291 // String operations:
2292 /**
2293 * @brief Return const pointer to null-terminated contents.
2294 *
2295 * This is a handle to internal data. Do not modify or dire things may
2296 * happen.
2297 */
2298 const _CharT*
2299 c_str() const _GLIBCXX_NOEXCEPTnoexcept
2300 { return _M_data(); }
2301
2302 /**
2303 * @brief Return const pointer to contents.
2304 *
2305 * This is a pointer to internal data. It is undefined to modify
2306 * the contents through the returned pointer. To get a pointer that
2307 * allows modifying the contents use @c &str[0] instead,
2308 * (or in C++17 the non-const @c str.data() overload).
2309 */
2310 const _CharT*
2311 data() const _GLIBCXX_NOEXCEPTnoexcept
2312 { return _M_data(); }
2313
2314#if __cplusplus201703L >= 201703L
2315 /**
2316 * @brief Return non-const pointer to contents.
2317 *
2318 * This is a pointer to the character sequence held by the string.
2319 * Modifying the characters in the sequence is allowed.
2320 */
2321 _CharT*
2322 data() noexcept
2323 { return _M_data(); }
2324#endif
2325
2326 /**
2327 * @brief Return copy of allocator used to construct this string.
2328 */
2329 allocator_type
2330 get_allocator() const _GLIBCXX_NOEXCEPTnoexcept
2331 { return _M_get_allocator(); }
2332
2333 /**
2334 * @brief Find position of a C substring.
2335 * @param __s C string to locate.
2336 * @param __pos Index of character to search from.
2337 * @param __n Number of characters from @a s to search for.
2338 * @return Index of start of first occurrence.
2339 *
2340 * Starting from @a __pos, searches forward for the first @a
2341 * __n characters in @a __s within this string. If found,
2342 * returns the index where it begins. If not found, returns
2343 * npos.
2344 */
2345 size_type
2346 find(const _CharT* __s, size_type __pos, size_type __n) const
2347 _GLIBCXX_NOEXCEPTnoexcept;
2348
2349 /**
2350 * @brief Find position of a string.
2351 * @param __str String to locate.
2352 * @param __pos Index of character to search from (default 0).
2353 * @return Index of start of first occurrence.
2354 *
2355 * Starting from @a __pos, searches forward for value of @a __str within
2356 * this string. If found, returns the index where it begins. If not
2357 * found, returns npos.
2358 */
2359 size_type
2360 find(const basic_string& __str, size_type __pos = 0) const
2361 _GLIBCXX_NOEXCEPTnoexcept
2362 { return this->find(__str.data(), __pos, __str.size()); }
2363
2364#if __cplusplus201703L >= 201703L
2365 /**
2366 * @brief Find position of a string_view.
2367 * @param __svt The object convertible to string_view to locate.
2368 * @param __pos Index of character to search from (default 0).
2369 * @return Index of start of first occurrence.
2370 */
2371 template<typename _Tp>
2372 _If_sv<_Tp, size_type>
2373 find(const _Tp& __svt, size_type __pos = 0) const
2374 noexcept(is_same<_Tp, __sv_type>::value)
2375 {
2376 __sv_type __sv = __svt;
2377 return this->find(__sv.data(), __pos, __sv.size());
2378 }
2379#endif // C++17
2380
2381 /**
2382 * @brief Find position of a C string.
2383 * @param __s C string to locate.
2384 * @param __pos Index of character to search from (default 0).
2385 * @return Index of start of first occurrence.
2386 *
2387 * Starting from @a __pos, searches forward for the value of @a
2388 * __s within this string. If found, returns the index where
2389 * it begins. If not found, returns npos.
2390 */
2391 size_type
2392 find(const _CharT* __s, size_type __pos = 0) const _GLIBCXX_NOEXCEPTnoexcept
2393 {
2394 __glibcxx_requires_string(__s);
2395 return this->find(__s, __pos, traits_type::length(__s));
2396 }
2397
2398 /**
2399 * @brief Find position of a character.
2400 * @param __c Character to locate.
2401 * @param __pos Index of character to search from (default 0).
2402 * @return Index of first occurrence.
2403 *
2404 * Starting from @a __pos, searches forward for @a __c within
2405 * this string. If found, returns the index where it was
2406 * found. If not found, returns npos.
2407 */
2408 size_type
2409 find(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPTnoexcept;
2410
2411 /**
2412 * @brief Find last position of a string.
2413 * @param __str String to locate.
2414 * @param __pos Index of character to search back from (default end).
2415 * @return Index of start of last occurrence.
2416 *
2417 * Starting from @a __pos, searches backward for value of @a
2418 * __str within this string. If found, returns the index where
2419 * it begins. If not found, returns npos.
2420 */
2421 size_type
2422 rfind(const basic_string& __str, size_type __pos = npos) const
2423 _GLIBCXX_NOEXCEPTnoexcept
2424 { return this->rfind(__str.data(), __pos, __str.size()); }
2425
2426#if __cplusplus201703L >= 201703L
2427 /**
2428 * @brief Find last position of a string_view.
2429 * @param __svt The object convertible to string_view to locate.
2430 * @param __pos Index of character to search back from (default end).
2431 * @return Index of start of last occurrence.
2432 */
2433 template<typename _Tp>
2434 _If_sv<_Tp, size_type>
2435 rfind(const _Tp& __svt, size_type __pos = npos) const
2436 noexcept(is_same<_Tp, __sv_type>::value)
2437 {
2438 __sv_type __sv = __svt;
2439 return this->rfind(__sv.data(), __pos, __sv.size());
2440 }
2441#endif // C++17
2442
2443 /**
2444 * @brief Find last position of a C substring.
2445 * @param __s C string to locate.
2446 * @param __pos Index of character to search back from.
2447 * @param __n Number of characters from s to search for.
2448 * @return Index of start of last occurrence.
2449 *
2450 * Starting from @a __pos, searches backward for the first @a
2451 * __n characters in @a __s within this string. If found,
2452 * returns the index where it begins. If not found, returns
2453 * npos.
2454 */
2455 size_type
2456 rfind(const _CharT* __s, size_type __pos, size_type __n) const
2457 _GLIBCXX_NOEXCEPTnoexcept;
2458
2459 /**
2460 * @brief Find last position of a C string.
2461 * @param __s C string to locate.
2462 * @param __pos Index of character to start search at (default end).
2463 * @return Index of start of last occurrence.
2464 *
2465 * Starting from @a __pos, searches backward for the value of
2466 * @a __s within this string. If found, returns the index
2467 * where it begins. If not found, returns npos.
2468 */
2469 size_type
2470 rfind(const _CharT* __s, size_type __pos = npos) const
2471 {
2472 __glibcxx_requires_string(__s);
2473 return this->rfind(__s, __pos, traits_type::length(__s));
2474 }
2475
2476 /**
2477 * @brief Find last position of a character.
2478 * @param __c Character to locate.
2479 * @param __pos Index of character to search back from (default end).
2480 * @return Index of last occurrence.
2481 *
2482 * Starting from @a __pos, searches backward for @a __c within
2483 * this string. If found, returns the index where it was
2484 * found. If not found, returns npos.
2485 */
2486 size_type
2487 rfind(_CharT __c, size_type __pos = npos) const _GLIBCXX_NOEXCEPTnoexcept;
2488
2489 /**
2490 * @brief Find position of a character of string.
2491 * @param __str String containing characters to locate.
2492 * @param __pos Index of character to search from (default 0).
2493 * @return Index of first occurrence.
2494 *
2495 * Starting from @a __pos, searches forward for one of the
2496 * characters of @a __str within this string. If found,
2497 * returns the index where it was found. If not found, returns
2498 * npos.
2499 */
2500 size_type
2501 find_first_of(const basic_string& __str, size_type __pos = 0) const
2502 _GLIBCXX_NOEXCEPTnoexcept
2503 { return this->find_first_of(__str.data(), __pos, __str.size()); }
2504
2505#if __cplusplus201703L >= 201703L
2506 /**
2507 * @brief Find position of a character of a string_view.
2508 * @param __svt An object convertible to string_view containing
2509 * characters to locate.
2510 * @param __pos Index of character to search from (default 0).
2511 * @return Index of first occurrence.
2512 */
2513 template<typename _Tp>
2514 _If_sv<_Tp, size_type>
2515 find_first_of(const _Tp& __svt, size_type __pos = 0) const
2516 noexcept(is_same<_Tp, __sv_type>::value)
2517 {
2518 __sv_type __sv = __svt;
2519 return this->find_first_of(__sv.data(), __pos, __sv.size());
2520 }
2521#endif // C++17
2522
2523 /**
2524 * @brief Find position of a character of C substring.
2525 * @param __s String containing characters to locate.
2526 * @param __pos Index of character to search from.
2527 * @param __n Number of characters from s to search for.
2528 * @return Index of first occurrence.
2529 *
2530 * Starting from @a __pos, searches forward for one of the
2531 * first @a __n characters of @a __s within this string. If
2532 * found, returns the index where it was found. If not found,
2533 * returns npos.
2534 */
2535 size_type
2536 find_first_of(const _CharT* __s, size_type __pos, size_type __n) const
2537 _GLIBCXX_NOEXCEPTnoexcept;
2538
2539 /**
2540 * @brief Find position of a character of C string.
2541 * @param __s String containing characters to locate.
2542 * @param __pos Index of character to search from (default 0).
2543 * @return Index of first occurrence.
2544 *
2545 * Starting from @a __pos, searches forward for one of the
2546 * characters of @a __s within this string. If found, returns
2547 * the index where it was found. If not found, returns npos.
2548 */
2549 size_type
2550 find_first_of(const _CharT* __s, size_type __pos = 0) const
2551 _GLIBCXX_NOEXCEPTnoexcept
2552 {
2553 __glibcxx_requires_string(__s);
2554 return this->find_first_of(__s, __pos, traits_type::length(__s));
2555 }
2556
2557 /**
2558 * @brief Find position of a character.
2559 * @param __c Character to locate.
2560 * @param __pos Index of character to search from (default 0).
2561 * @return Index of first occurrence.
2562 *
2563 * Starting from @a __pos, searches forward for the character
2564 * @a __c within this string. If found, returns the index
2565 * where it was found. If not found, returns npos.
2566 *
2567 * Note: equivalent to find(__c, __pos).
2568 */
2569 size_type
2570 find_first_of(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPTnoexcept
2571 { return this->find(__c, __pos); }
2572
2573 /**
2574 * @brief Find last position of a character of string.
2575 * @param __str String cont