Bug Summary

File:clang/lib/CodeGen/CGObjC.cpp
Warning:line 477, column 35
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CGObjC.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-07-102640-14763-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp

1//===---- CGObjC.cpp - Emit LLVM Code for Objective-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 contains code to emit Objective-C code as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGDebugInfo.h"
14#include "CGObjCRuntime.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "ConstantEmitter.h"
18#include "TargetInfo.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/StmtObjC.h"
22#include "clang/Basic/Diagnostic.h"
23#include "clang/CodeGen/CGFunctionInfo.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/InlineAsm.h"
27using namespace clang;
28using namespace CodeGen;
29
30typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
31static TryEmitResult
32tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
33static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
34 QualType ET,
35 RValue Result);
36
37/// Given the address of a variable of pointer type, find the correct
38/// null to store into it.
39static llvm::Constant *getNullForVariable(Address addr) {
40 llvm::Type *type = addr.getElementType();
41 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
42}
43
44/// Emits an instance of NSConstantString representing the object.
45llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
46{
47 llvm::Constant *C =
48 CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
49 // FIXME: This bitcast should just be made an invariant on the Runtime.
50 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
51}
52
53/// EmitObjCBoxedExpr - This routine generates code to call
54/// the appropriate expression boxing method. This will either be
55/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
56/// or [NSValue valueWithBytes:objCType:].
57///
58llvm::Value *
59CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
60 // Generate the correct selector for this literal's concrete type.
61 // Get the method.
62 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
63 const Expr *SubExpr = E->getSubExpr();
64
65 if (E->isExpressibleAsConstantInitializer()) {
66 ConstantEmitter ConstEmitter(CGM);
67 return ConstEmitter.tryEmitAbstract(E, E->getType());
68 }
69
70 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method")((BoxingMethod->isClassMethod() && "BoxingMethod must be a class method"
) ? static_cast<void> (0) : __assert_fail ("BoxingMethod->isClassMethod() && \"BoxingMethod must be a class method\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 70, __PRETTY_FUNCTION__))
;
71 Selector Sel = BoxingMethod->getSelector();
72
73 // Generate a reference to the class pointer, which will be the receiver.
74 // Assumes that the method was introduced in the class that should be
75 // messaged (avoids pulling it out of the result type).
76 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
77 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
78 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
79
80 CallArgList Args;
81 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
82 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
83
84 // ObjCBoxedExpr supports boxing of structs and unions
85 // via [NSValue valueWithBytes:objCType:]
86 const QualType ValueType(SubExpr->getType().getCanonicalType());
87 if (ValueType->isObjCBoxableRecordType()) {
88 // Emit CodeGen for first parameter
89 // and cast value to correct type
90 Address Temporary = CreateMemTemp(SubExpr->getType());
91 EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
92 Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
93 Args.add(RValue::get(BitCast.getPointer()), ArgQT);
94
95 // Create char array to store type encoding
96 std::string Str;
97 getContext().getObjCEncodingForType(ValueType, Str);
98 llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
99
100 // Cast type encoding to correct type
101 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
102 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
103 llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
104
105 Args.add(RValue::get(Cast), EncodingQT);
106 } else {
107 Args.add(EmitAnyExpr(SubExpr), ArgQT);
108 }
109
110 RValue result = Runtime.GenerateMessageSend(
111 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
112 Args, ClassDecl, BoxingMethod);
113 return Builder.CreateBitCast(result.getScalarVal(),
114 ConvertType(E->getType()));
115}
116
117llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
118 const ObjCMethodDecl *MethodWithObjects) {
119 ASTContext &Context = CGM.getContext();
120 const ObjCDictionaryLiteral *DLE = nullptr;
121 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
122 if (!ALE)
123 DLE = cast<ObjCDictionaryLiteral>(E);
124
125 // Optimize empty collections by referencing constants, when available.
126 uint64_t NumElements =
127 ALE ? ALE->getNumElements() : DLE->getNumElements();
128 if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
129 StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
130 QualType IdTy(CGM.getContext().getObjCIdType());
131 llvm::Constant *Constant =
132 CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
133 LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
134 llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());
135 cast<llvm::LoadInst>(Ptr)->setMetadata(
136 CGM.getModule().getMDKindID("invariant.load"),
137 llvm::MDNode::get(getLLVMContext(), None));
138 return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
139 }
140
141 // Compute the type of the array we're initializing.
142 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
143 NumElements);
144 QualType ElementType = Context.getObjCIdType().withConst();
145 QualType ElementArrayType
146 = Context.getConstantArrayType(ElementType, APNumElements, nullptr,
147 ArrayType::Normal, /*IndexTypeQuals=*/0);
148
149 // Allocate the temporary array(s).
150 Address Objects = CreateMemTemp(ElementArrayType, "objects");
151 Address Keys = Address::invalid();
152 if (DLE)
153 Keys = CreateMemTemp(ElementArrayType, "keys");
154
155 // In ARC, we may need to do extra work to keep all the keys and
156 // values alive until after the call.
157 SmallVector<llvm::Value *, 16> NeededObjects;
158 bool TrackNeededObjects =
159 (getLangOpts().ObjCAutoRefCount &&
160 CGM.getCodeGenOpts().OptimizationLevel != 0);
161
162 // Perform the actual initialialization of the array(s).
163 for (uint64_t i = 0; i < NumElements; i++) {
164 if (ALE) {
165 // Emit the element and store it to the appropriate array slot.
166 const Expr *Rhs = ALE->getElement(i);
167 LValue LV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
168 ElementType, AlignmentSource::Decl);
169
170 llvm::Value *value = EmitScalarExpr(Rhs);
171 EmitStoreThroughLValue(RValue::get(value), LV, true);
172 if (TrackNeededObjects) {
173 NeededObjects.push_back(value);
174 }
175 } else {
176 // Emit the key and store it to the appropriate array slot.
177 const Expr *Key = DLE->getKeyValueElement(i).Key;
178 LValue KeyLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Keys, i),
179 ElementType, AlignmentSource::Decl);
180 llvm::Value *keyValue = EmitScalarExpr(Key);
181 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
182
183 // Emit the value and store it to the appropriate array slot.
184 const Expr *Value = DLE->getKeyValueElement(i).Value;
185 LValue ValueLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
186 ElementType, AlignmentSource::Decl);
187 llvm::Value *valueValue = EmitScalarExpr(Value);
188 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
189 if (TrackNeededObjects) {
190 NeededObjects.push_back(keyValue);
191 NeededObjects.push_back(valueValue);
192 }
193 }
194 }
195
196 // Generate the argument list.
197 CallArgList Args;
198 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
199 const ParmVarDecl *argDecl = *PI++;
200 QualType ArgQT = argDecl->getType().getUnqualifiedType();
201 Args.add(RValue::get(Objects.getPointer()), ArgQT);
202 if (DLE) {
203 argDecl = *PI++;
204 ArgQT = argDecl->getType().getUnqualifiedType();
205 Args.add(RValue::get(Keys.getPointer()), ArgQT);
206 }
207 argDecl = *PI;
208 ArgQT = argDecl->getType().getUnqualifiedType();
209 llvm::Value *Count =
210 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
211 Args.add(RValue::get(Count), ArgQT);
212
213 // Generate a reference to the class pointer, which will be the receiver.
214 Selector Sel = MethodWithObjects->getSelector();
215 QualType ResultType = E->getType();
216 const ObjCObjectPointerType *InterfacePointerType
217 = ResultType->getAsObjCInterfacePointerType();
218 ObjCInterfaceDecl *Class
219 = InterfacePointerType->getObjectType()->getInterface();
220 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
221 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
222
223 // Generate the message send.
224 RValue result = Runtime.GenerateMessageSend(
225 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
226 Receiver, Args, Class, MethodWithObjects);
227
228 // The above message send needs these objects, but in ARC they are
229 // passed in a buffer that is essentially __unsafe_unretained.
230 // Therefore we must prevent the optimizer from releasing them until
231 // after the call.
232 if (TrackNeededObjects) {
233 EmitARCIntrinsicUse(NeededObjects);
234 }
235
236 return Builder.CreateBitCast(result.getScalarVal(),
237 ConvertType(E->getType()));
238}
239
240llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
241 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
242}
243
244llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
245 const ObjCDictionaryLiteral *E) {
246 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
247}
248
249/// Emit a selector.
250llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
251 // Untyped selector.
252 // Note that this implementation allows for non-constant strings to be passed
253 // as arguments to @selector(). Currently, the only thing preventing this
254 // behaviour is the type checking in the front end.
255 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
256}
257
258llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
259 // FIXME: This should pass the Decl not the name.
260 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
261}
262
263/// Adjust the type of an Objective-C object that doesn't match up due
264/// to type erasure at various points, e.g., related result types or the use
265/// of parameterized classes.
266static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
267 RValue Result) {
268 if (!ExpT->isObjCRetainableType())
269 return Result;
270
271 // If the converted types are the same, we're done.
272 llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
273 if (ExpLLVMTy == Result.getScalarVal()->getType())
274 return Result;
275
276 // We have applied a substitution. Cast the rvalue appropriately.
277 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
278 ExpLLVMTy));
279}
280
281/// Decide whether to extend the lifetime of the receiver of a
282/// returns-inner-pointer message.
283static bool
284shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
285 switch (message->getReceiverKind()) {
286
287 // For a normal instance message, we should extend unless the
288 // receiver is loaded from a variable with precise lifetime.
289 case ObjCMessageExpr::Instance: {
290 const Expr *receiver = message->getInstanceReceiver();
291
292 // Look through OVEs.
293 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
294 if (opaque->getSourceExpr())
295 receiver = opaque->getSourceExpr()->IgnoreParens();
296 }
297
298 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
299 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
300 receiver = ice->getSubExpr()->IgnoreParens();
301
302 // Look through OVEs.
303 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
304 if (opaque->getSourceExpr())
305 receiver = opaque->getSourceExpr()->IgnoreParens();
306 }
307
308 // Only __strong variables.
309 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
310 return true;
311
312 // All ivars and fields have precise lifetime.
313 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
314 return false;
315
316 // Otherwise, check for variables.
317 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
318 if (!declRef) return true;
319 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
320 if (!var) return true;
321
322 // All variables have precise lifetime except local variables with
323 // automatic storage duration that aren't specially marked.
324 return (var->hasLocalStorage() &&
325 !var->hasAttr<ObjCPreciseLifetimeAttr>());
326 }
327
328 case ObjCMessageExpr::Class:
329 case ObjCMessageExpr::SuperClass:
330 // It's never necessary for class objects.
331 return false;
332
333 case ObjCMessageExpr::SuperInstance:
334 // We generally assume that 'self' lives throughout a method call.
335 return false;
336 }
337
338 llvm_unreachable("invalid receiver kind")::llvm::llvm_unreachable_internal("invalid receiver kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 338)
;
339}
340
341/// Given an expression of ObjC pointer type, check whether it was
342/// immediately loaded from an ARC __weak l-value.
343static const Expr *findWeakLValue(const Expr *E) {
344 assert(E->getType()->isObjCRetainableType())((E->getType()->isObjCRetainableType()) ? static_cast<
void> (0) : __assert_fail ("E->getType()->isObjCRetainableType()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 344, __PRETTY_FUNCTION__))
;
345 E = E->IgnoreParens();
346 if (auto CE = dyn_cast<CastExpr>(E)) {
347 if (CE->getCastKind() == CK_LValueToRValue) {
348 if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
349 return CE->getSubExpr();
350 }
351 }
352
353 return nullptr;
354}
355
356/// The ObjC runtime may provide entrypoints that are likely to be faster
357/// than an ordinary message send of the appropriate selector.
358///
359/// The entrypoints are guaranteed to be equivalent to just sending the
360/// corresponding message. If the entrypoint is implemented naively as just a
361/// message send, using it is a trade-off: it sacrifices a few cycles of
362/// overhead to save a small amount of code. However, it's possible for
363/// runtimes to detect and special-case classes that use "standard"
364/// behavior; if that's dynamically a large proportion of all objects, using
365/// the entrypoint will also be faster than using a message send.
366///
367/// If the runtime does support a required entrypoint, then this method will
368/// generate a call and return the resulting value. Otherwise it will return
369/// None and the caller can generate a msgSend instead.
370static Optional<llvm::Value *>
371tryGenerateSpecializedMessageSend(CodeGenFunction &CGF, QualType ResultType,
372 llvm::Value *Receiver,
373 const CallArgList& Args, Selector Sel,
374 const ObjCMethodDecl *method,
375 bool isClassMessage) {
376 auto &CGM = CGF.CGM;
377 if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
378 return None;
379
380 auto &Runtime = CGM.getLangOpts().ObjCRuntime;
381 switch (Sel.getMethodFamily()) {
382 case OMF_alloc:
383 if (isClassMessage &&
384 Runtime.shouldUseRuntimeFunctionsForAlloc() &&
385 ResultType->isObjCObjectPointerType()) {
386 // [Foo alloc] -> objc_alloc(Foo) or
387 // [self alloc] -> objc_alloc(self)
388 if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")
389 return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
390 // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo) or
391 // [self allocWithZone:nil] -> objc_allocWithZone(self)
392 if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
393 Args.size() == 1 && Args.front().getType()->isPointerType() &&
394 Sel.getNameForSlot(0) == "allocWithZone") {
395 const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
396 if (isa<llvm::ConstantPointerNull>(arg))
397 return CGF.EmitObjCAllocWithZone(Receiver,
398 CGF.ConvertType(ResultType));
399 return None;
400 }
401 }
402 break;
403
404 case OMF_autorelease:
405 if (ResultType->isObjCObjectPointerType() &&
406 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
407 Runtime.shouldUseARCFunctionsForRetainRelease())
408 return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));
409 break;
410
411 case OMF_retain:
412 if (ResultType->isObjCObjectPointerType() &&
413 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
414 Runtime.shouldUseARCFunctionsForRetainRelease())
415 return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));
416 break;
417
418 case OMF_release:
419 if (ResultType->isVoidType() &&
420 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
421 Runtime.shouldUseARCFunctionsForRetainRelease()) {
422 CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);
423 return nullptr;
424 }
425 break;
426
427 default:
428 break;
429 }
430 return None;
431}
432
433/// Instead of '[[MyClass alloc] init]', try to generate
434/// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the
435/// caller side, as well as the optimized objc_alloc.
436static Optional<llvm::Value *>
437tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME) {
438 auto &Runtime = CGF.getLangOpts().ObjCRuntime;
439 if (!Runtime.shouldUseRuntimeFunctionForCombinedAllocInit())
2
Calling 'ObjCRuntime::shouldUseRuntimeFunctionForCombinedAllocInit'
20
Returning from 'ObjCRuntime::shouldUseRuntimeFunctionForCombinedAllocInit'
21
Taking false branch
440 return None;
441
442 // Match the exact pattern '[[MyClass alloc] init]'.
443 Selector Sel = OME->getSelector();
444 if (OME->getReceiverKind() != ObjCMessageExpr::Instance ||
22
Assuming the condition is false
23
Taking false branch
445 !OME->getType()->isObjCObjectPointerType() || !Sel.isUnarySelector() ||
446 Sel.getNameForSlot(0) != "init")
447 return None;
448
449 // Okay, this is '[receiver init]', check if 'receiver' is '[cls alloc]' or
450 // we are in an ObjC class method and 'receiver' is '[self alloc]'.
451 auto *SubOME =
452 dyn_cast<ObjCMessageExpr>(OME->getInstanceReceiver()->IgnoreParenCasts());
24
Assuming the object is a 'ObjCMessageExpr'
453 if (!SubOME
24.1
'SubOME' is non-null
24.1
'SubOME' is non-null
24.1
'SubOME' is non-null
24.1
'SubOME' is non-null
)
25
Taking false branch
454 return None;
455 Selector SubSel = SubOME->getSelector();
456
457 // Check if we are in an ObjC class method and the receiver expression is
458 // 'self'.
459 const Expr *SelfInClassMethod = nullptr;
460 if (const auto *CurMD
26.1
'CurMD' is null
26.1
'CurMD' is null
26.1
'CurMD' is null
26.1
'CurMD' is null
= dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl))
26
Assuming null pointer is passed into cast
27
Taking false branch
461 if (CurMD->isClassMethod())
462 if ((SelfInClassMethod = SubOME->getInstanceReceiver()))
463 if (!SelfInClassMethod->isObjCSelfExpr())
464 SelfInClassMethod = nullptr;
465
466 if ((SubOME->getReceiverKind() != ObjCMessageExpr::Class &&
28
Assuming the condition is false
29
Taking false branch
467 !SelfInClassMethod) || !SubOME->getType()->isObjCObjectPointerType() ||
468 !SubSel.isUnarySelector() || SubSel.getNameForSlot(0) != "alloc")
469 return None;
470
471 llvm::Value *Receiver;
472 if (SelfInClassMethod
29.1
'SelfInClassMethod' is null
29.1
'SelfInClassMethod' is null
29.1
'SelfInClassMethod' is null
29.1
'SelfInClassMethod' is null
) {
30
Taking false branch
473 Receiver = CGF.EmitScalarExpr(SelfInClassMethod);
474 } else {
475 QualType ReceiverType = SubOME->getClassReceiver();
476 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
31
Assuming the object is not a 'ObjCObjectType'
32
'ObjTy' initialized to a null pointer value
477 const ObjCInterfaceDecl *ID = ObjTy->getInterface();
33
Called C++ object pointer is null
478 assert(ID && "null interface should be impossible here")((ID && "null interface should be impossible here") ?
static_cast<void> (0) : __assert_fail ("ID && \"null interface should be impossible here\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 478, __PRETTY_FUNCTION__))
;
479 Receiver = CGF.CGM.getObjCRuntime().GetClass(CGF, ID);
480 }
481 return CGF.EmitObjCAllocInit(Receiver, CGF.ConvertType(OME->getType()));
482}
483
484RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
485 ReturnValueSlot Return) {
486 // Only the lookup mechanism and first two arguments of the method
487 // implementation vary between runtimes. We can get the receiver and
488 // arguments in generic code.
489
490 bool isDelegateInit = E->isDelegateInitCall();
491
492 const ObjCMethodDecl *method = E->getMethodDecl();
493
494 // If the method is -retain, and the receiver's being loaded from
495 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
496 if (method
0.1
'method' is null
0.1
'method' is null
0.1
'method' is null
0.1
'method' is null
&& E->getReceiverKind() == ObjCMessageExpr::Instance &&
497 method->getMethodFamily() == OMF_retain) {
498 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
499 LValue lvalue = EmitLValue(lvalueExpr);
500 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress());
501 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
502 }
503 }
504
505 if (Optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(*this, E))
1
Calling 'tryEmitSpecializedAllocInit'
506 return AdjustObjCObjectType(*this, E->getType(), RValue::get(*Val));
507
508 // We don't retain the receiver in delegate init calls, and this is
509 // safe because the receiver value is always loaded from 'self',
510 // which we zero out. We don't want to Block_copy block receivers,
511 // though.
512 bool retainSelf =
513 (!isDelegateInit &&
514 CGM.getLangOpts().ObjCAutoRefCount &&
515 method &&
516 method->hasAttr<NSConsumesSelfAttr>());
517
518 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
519 bool isSuperMessage = false;
520 bool isClassMessage = false;
521 ObjCInterfaceDecl *OID = nullptr;
522 // Find the receiver
523 QualType ReceiverType;
524 llvm::Value *Receiver = nullptr;
525 switch (E->getReceiverKind()) {
526 case ObjCMessageExpr::Instance:
527 ReceiverType = E->getInstanceReceiver()->getType();
528 if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl))
529 if (OMD->isClassMethod())
530 if (E->getInstanceReceiver()->isObjCSelfExpr())
531 isClassMessage = true;
532 if (retainSelf) {
533 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
534 E->getInstanceReceiver());
535 Receiver = ter.getPointer();
536 if (ter.getInt()) retainSelf = false;
537 } else
538 Receiver = EmitScalarExpr(E->getInstanceReceiver());
539 break;
540
541 case ObjCMessageExpr::Class: {
542 ReceiverType = E->getClassReceiver();
543 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
544 assert(ObjTy && "Invalid Objective-C class message send")((ObjTy && "Invalid Objective-C class message send") ?
static_cast<void> (0) : __assert_fail ("ObjTy && \"Invalid Objective-C class message send\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 544, __PRETTY_FUNCTION__))
;
545 OID = ObjTy->getInterface();
546 assert(OID && "Invalid Objective-C class message send")((OID && "Invalid Objective-C class message send") ? static_cast
<void> (0) : __assert_fail ("OID && \"Invalid Objective-C class message send\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 546, __PRETTY_FUNCTION__))
;
547 Receiver = Runtime.GetClass(*this, OID);
548 isClassMessage = true;
549 break;
550 }
551
552 case ObjCMessageExpr::SuperInstance:
553 ReceiverType = E->getSuperType();
554 Receiver = LoadObjCSelf();
555 isSuperMessage = true;
556 break;
557
558 case ObjCMessageExpr::SuperClass:
559 ReceiverType = E->getSuperType();
560 Receiver = LoadObjCSelf();
561 isSuperMessage = true;
562 isClassMessage = true;
563 break;
564 }
565
566 if (retainSelf)
567 Receiver = EmitARCRetainNonBlock(Receiver);
568
569 // In ARC, we sometimes want to "extend the lifetime"
570 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
571 // messages.
572 if (getLangOpts().ObjCAutoRefCount && method &&
573 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
574 shouldExtendReceiverForInnerPointerMessage(E))
575 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
576
577 QualType ResultType = method ? method->getReturnType() : E->getType();
578
579 CallArgList Args;
580 EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
581
582 // For delegate init calls in ARC, do an unsafe store of null into
583 // self. This represents the call taking direct ownership of that
584 // value. We have to do this after emitting the other call
585 // arguments because they might also reference self, but we don't
586 // have to worry about any of them modifying self because that would
587 // be an undefined read and write of an object in unordered
588 // expressions.
589 if (isDelegateInit) {
590 assert(getLangOpts().ObjCAutoRefCount &&((getLangOpts().ObjCAutoRefCount && "delegate init calls should only be marked in ARC"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().ObjCAutoRefCount && \"delegate init calls should only be marked in ARC\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 591, __PRETTY_FUNCTION__))
591 "delegate init calls should only be marked in ARC")((getLangOpts().ObjCAutoRefCount && "delegate init calls should only be marked in ARC"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().ObjCAutoRefCount && \"delegate init calls should only be marked in ARC\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 591, __PRETTY_FUNCTION__))
;
592
593 // Do an unsafe store of null into self.
594 Address selfAddr =
595 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
596 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
597 }
598
599 RValue result;
600 if (isSuperMessage) {
601 // super is only valid in an Objective-C method
602 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
603 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
604 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
605 E->getSelector(),
606 OMD->getClassInterface(),
607 isCategoryImpl,
608 Receiver,
609 isClassMessage,
610 Args,
611 method);
612 } else {
613 // Call runtime methods directly if we can.
614 if (Optional<llvm::Value *> SpecializedResult =
615 tryGenerateSpecializedMessageSend(*this, ResultType, Receiver, Args,
616 E->getSelector(), method,
617 isClassMessage)) {
618 result = RValue::get(SpecializedResult.getValue());
619 } else {
620 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
621 E->getSelector(), Receiver, Args,
622 OID, method);
623 }
624 }
625
626 // For delegate init calls in ARC, implicitly store the result of
627 // the call back into self. This takes ownership of the value.
628 if (isDelegateInit) {
629 Address selfAddr =
630 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
631 llvm::Value *newSelf = result.getScalarVal();
632
633 // The delegate return type isn't necessarily a matching type; in
634 // fact, it's quite likely to be 'id'.
635 llvm::Type *selfTy = selfAddr.getElementType();
636 newSelf = Builder.CreateBitCast(newSelf, selfTy);
637
638 Builder.CreateStore(newSelf, selfAddr);
639 }
640
641 return AdjustObjCObjectType(*this, E->getType(), result);
642}
643
644namespace {
645struct FinishARCDealloc final : EHScopeStack::Cleanup {
646 void Emit(CodeGenFunction &CGF, Flags flags) override {
647 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
648
649 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
650 const ObjCInterfaceDecl *iface = impl->getClassInterface();
651 if (!iface->getSuperClass()) return;
652
653 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
654
655 // Call [super dealloc] if we have a superclass.
656 llvm::Value *self = CGF.LoadObjCSelf();
657
658 CallArgList args;
659 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
660 CGF.getContext().VoidTy,
661 method->getSelector(),
662 iface,
663 isCategory,
664 self,
665 /*is class msg*/ false,
666 args,
667 method);
668 }
669};
670}
671
672/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
673/// the LLVM function and sets the other context used by
674/// CodeGenFunction.
675void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
676 const ObjCContainerDecl *CD) {
677 SourceLocation StartLoc = OMD->getBeginLoc();
678 FunctionArgList args;
679 // Check if we should generate debug info for this method.
680 if (OMD->hasAttr<NoDebugAttr>())
681 DebugInfo = nullptr; // disable debug info indefinitely for this function
682
683 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
684
685 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
686 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
687
688 args.push_back(OMD->getSelfDecl());
689 args.push_back(OMD->getCmdDecl());
690
691 args.append(OMD->param_begin(), OMD->param_end());
692
693 CurGD = OMD;
694 CurEHLocation = OMD->getEndLoc();
695
696 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
697 OMD->getLocation(), StartLoc);
698
699 // In ARC, certain methods get an extra cleanup.
700 if (CGM.getLangOpts().ObjCAutoRefCount &&
701 OMD->isInstanceMethod() &&
702 OMD->getSelector().isUnarySelector()) {
703 const IdentifierInfo *ident =
704 OMD->getSelector().getIdentifierInfoForSlot(0);
705 if (ident->isStr("dealloc"))
706 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
707 }
708}
709
710static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
711 LValue lvalue, QualType type);
712
713/// Generate an Objective-C method. An Objective-C method is a C function with
714/// its pointer, name, and types registered in the class structure.
715void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
716 StartObjCMethod(OMD, OMD->getClassInterface());
717 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
718 assert(isa<CompoundStmt>(OMD->getBody()))((isa<CompoundStmt>(OMD->getBody())) ? static_cast<
void> (0) : __assert_fail ("isa<CompoundStmt>(OMD->getBody())"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 718, __PRETTY_FUNCTION__))
;
719 incrementProfileCounter(OMD->getBody());
720 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
721 FinishFunction(OMD->getBodyRBrace());
722}
723
724/// emitStructGetterCall - Call the runtime function to load a property
725/// into the return value slot.
726static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
727 bool isAtomic, bool hasStrong) {
728 ASTContext &Context = CGF.getContext();
729
730 Address src =
731 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
732 .getAddress();
733
734 // objc_copyStruct (ReturnValue, &structIvar,
735 // sizeof (Type of Ivar), isAtomic, false);
736 CallArgList args;
737
738 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
739 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
740
741 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
742 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
743
744 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
745 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
746 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
747 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
748
749 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
750 CGCallee callee = CGCallee::forDirect(fn);
751 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
752 callee, ReturnValueSlot(), args);
753}
754
755/// Determine whether the given architecture supports unaligned atomic
756/// accesses. They don't have to be fast, just faster than a function
757/// call and a mutex.
758static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
759 // FIXME: Allow unaligned atomic load/store on x86. (It is not
760 // currently supported by the backend.)
761 return 0;
762}
763
764/// Return the maximum size that permits atomic accesses for the given
765/// architecture.
766static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
767 llvm::Triple::ArchType arch) {
768 // ARM has 8-byte atomic accesses, but it's not clear whether we
769 // want to rely on them here.
770
771 // In the default case, just assume that any size up to a pointer is
772 // fine given adequate alignment.
773 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
774}
775
776namespace {
777 class PropertyImplStrategy {
778 public:
779 enum StrategyKind {
780 /// The 'native' strategy is to use the architecture's provided
781 /// reads and writes.
782 Native,
783
784 /// Use objc_setProperty and objc_getProperty.
785 GetSetProperty,
786
787 /// Use objc_setProperty for the setter, but use expression
788 /// evaluation for the getter.
789 SetPropertyAndExpressionGet,
790
791 /// Use objc_copyStruct.
792 CopyStruct,
793
794 /// The 'expression' strategy is to emit normal assignment or
795 /// lvalue-to-rvalue expressions.
796 Expression
797 };
798
799 StrategyKind getKind() const { return StrategyKind(Kind); }
800
801 bool hasStrongMember() const { return HasStrong; }
802 bool isAtomic() const { return IsAtomic; }
803 bool isCopy() const { return IsCopy; }
804
805 CharUnits getIvarSize() const { return IvarSize; }
806 CharUnits getIvarAlignment() const { return IvarAlignment; }
807
808 PropertyImplStrategy(CodeGenModule &CGM,
809 const ObjCPropertyImplDecl *propImpl);
810
811 private:
812 unsigned Kind : 8;
813 unsigned IsAtomic : 1;
814 unsigned IsCopy : 1;
815 unsigned HasStrong : 1;
816
817 CharUnits IvarSize;
818 CharUnits IvarAlignment;
819 };
820}
821
822/// Pick an implementation strategy for the given property synthesis.
823PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
824 const ObjCPropertyImplDecl *propImpl) {
825 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
826 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
827
828 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
829 IsAtomic = prop->isAtomic();
830 HasStrong = false; // doesn't matter here.
831
832 // Evaluate the ivar's size and alignment.
833 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
834 QualType ivarType = ivar->getType();
835 std::tie(IvarSize, IvarAlignment) =
836 CGM.getContext().getTypeInfoInChars(ivarType);
837
838 // If we have a copy property, we always have to use getProperty/setProperty.
839 // TODO: we could actually use setProperty and an expression for non-atomics.
840 if (IsCopy) {
841 Kind = GetSetProperty;
842 return;
843 }
844
845 // Handle retain.
846 if (setterKind == ObjCPropertyDecl::Retain) {
847 // In GC-only, there's nothing special that needs to be done.
848 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
849 // fallthrough
850
851 // In ARC, if the property is non-atomic, use expression emission,
852 // which translates to objc_storeStrong. This isn't required, but
853 // it's slightly nicer.
854 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
855 // Using standard expression emission for the setter is only
856 // acceptable if the ivar is __strong, which won't be true if
857 // the property is annotated with __attribute__((NSObject)).
858 // TODO: falling all the way back to objc_setProperty here is
859 // just laziness, though; we could still use objc_storeStrong
860 // if we hacked it right.
861 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
862 Kind = Expression;
863 else
864 Kind = SetPropertyAndExpressionGet;
865 return;
866
867 // Otherwise, we need to at least use setProperty. However, if
868 // the property isn't atomic, we can use normal expression
869 // emission for the getter.
870 } else if (!IsAtomic) {
871 Kind = SetPropertyAndExpressionGet;
872 return;
873
874 // Otherwise, we have to use both setProperty and getProperty.
875 } else {
876 Kind = GetSetProperty;
877 return;
878 }
879 }
880
881 // If we're not atomic, just use expression accesses.
882 if (!IsAtomic) {
883 Kind = Expression;
884 return;
885 }
886
887 // Properties on bitfield ivars need to be emitted using expression
888 // accesses even if they're nominally atomic.
889 if (ivar->isBitField()) {
890 Kind = Expression;
891 return;
892 }
893
894 // GC-qualified or ARC-qualified ivars need to be emitted as
895 // expressions. This actually works out to being atomic anyway,
896 // except for ARC __strong, but that should trigger the above code.
897 if (ivarType.hasNonTrivialObjCLifetime() ||
898 (CGM.getLangOpts().getGC() &&
899 CGM.getContext().getObjCGCAttrKind(ivarType))) {
900 Kind = Expression;
901 return;
902 }
903
904 // Compute whether the ivar has strong members.
905 if (CGM.getLangOpts().getGC())
906 if (const RecordType *recordType = ivarType->getAs<RecordType>())
907 HasStrong = recordType->getDecl()->hasObjectMember();
908
909 // We can never access structs with object members with a native
910 // access, because we need to use write barriers. This is what
911 // objc_copyStruct is for.
912 if (HasStrong) {
913 Kind = CopyStruct;
914 return;
915 }
916
917 // Otherwise, this is target-dependent and based on the size and
918 // alignment of the ivar.
919
920 // If the size of the ivar is not a power of two, give up. We don't
921 // want to get into the business of doing compare-and-swaps.
922 if (!IvarSize.isPowerOfTwo()) {
923 Kind = CopyStruct;
924 return;
925 }
926
927 llvm::Triple::ArchType arch =
928 CGM.getTarget().getTriple().getArch();
929
930 // Most architectures require memory to fit within a single cache
931 // line, so the alignment has to be at least the size of the access.
932 // Otherwise we have to grab a lock.
933 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
934 Kind = CopyStruct;
935 return;
936 }
937
938 // If the ivar's size exceeds the architecture's maximum atomic
939 // access size, we have to use CopyStruct.
940 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
941 Kind = CopyStruct;
942 return;
943 }
944
945 // Otherwise, we can use native loads and stores.
946 Kind = Native;
947}
948
949/// Generate an Objective-C property getter function.
950///
951/// The given Decl must be an ObjCImplementationDecl. \@synthesize
952/// is illegal within a category.
953void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
954 const ObjCPropertyImplDecl *PID) {
955 llvm::Constant *AtomicHelperFn =
956 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
957 ObjCMethodDecl *OMD = PID->getGetterMethodDecl();
958 assert(OMD && "Invalid call to generate getter (empty method)")((OMD && "Invalid call to generate getter (empty method)"
) ? static_cast<void> (0) : __assert_fail ("OMD && \"Invalid call to generate getter (empty method)\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 958, __PRETTY_FUNCTION__))
;
959 StartObjCMethod(OMD, IMP->getClassInterface());
960
961 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
962
963 FinishFunction();
964}
965
966static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
967 const Expr *getter = propImpl->getGetterCXXConstructor();
968 if (!getter) return true;
969
970 // Sema only makes only of these when the ivar has a C++ class type,
971 // so the form is pretty constrained.
972
973 // If the property has a reference type, we might just be binding a
974 // reference, in which case the result will be a gl-value. We should
975 // treat this as a non-trivial operation.
976 if (getter->isGLValue())
977 return false;
978
979 // If we selected a trivial copy-constructor, we're okay.
980 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
981 return (construct->getConstructor()->isTrivial());
982
983 // The constructor might require cleanups (in which case it's never
984 // trivial).
985 assert(isa<ExprWithCleanups>(getter))((isa<ExprWithCleanups>(getter)) ? static_cast<void>
(0) : __assert_fail ("isa<ExprWithCleanups>(getter)", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 985, __PRETTY_FUNCTION__))
;
986 return false;
987}
988
989/// emitCPPObjectAtomicGetterCall - Call the runtime function to
990/// copy the ivar into the resturn slot.
991static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
992 llvm::Value *returnAddr,
993 ObjCIvarDecl *ivar,
994 llvm::Constant *AtomicHelperFn) {
995 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
996 // AtomicHelperFn);
997 CallArgList args;
998
999 // The 1st argument is the return Slot.
1000 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
1001
1002 // The 2nd argument is the address of the ivar.
1003 llvm::Value *ivarAddr =
1004 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1005 CGF.LoadObjCSelf(), ivar, 0).getPointer();
1006 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1007 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1008
1009 // Third argument is the helper function.
1010 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1011
1012 llvm::FunctionCallee copyCppAtomicObjectFn =
1013 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
1014 CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
1015 CGF.EmitCall(
1016 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1017 callee, ReturnValueSlot(), args);
1018}
1019
1020void
1021CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1022 const ObjCPropertyImplDecl *propImpl,
1023 const ObjCMethodDecl *GetterMethodDecl,
1024 llvm::Constant *AtomicHelperFn) {
1025 // If there's a non-trivial 'get' expression, we just have to emit that.
1026 if (!hasTrivialGetExpr(propImpl)) {
1027 if (!AtomicHelperFn) {
1028 auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
1029 propImpl->getGetterCXXConstructor(),
1030 /* NRVOCandidate=*/nullptr);
1031 EmitReturnStmt(*ret);
1032 }
1033 else {
1034 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1035 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
1036 ivar, AtomicHelperFn);
1037 }
1038 return;
1039 }
1040
1041 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1042 QualType propType = prop->getType();
1043 ObjCMethodDecl *getterMethod = propImpl->getGetterMethodDecl();
1044
1045 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1046
1047 // Pick an implementation strategy.
1048 PropertyImplStrategy strategy(CGM, propImpl);
1049 switch (strategy.getKind()) {
1050 case PropertyImplStrategy::Native: {
1051 // We don't need to do anything for a zero-size struct.
1052 if (strategy.getIvarSize().isZero())
1053 return;
1054
1055 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1056
1057 // Currently, all atomic accesses have to be through integer
1058 // types, so there's no point in trying to pick a prettier type.
1059 uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
1060 llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
1061 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1062
1063 // Perform an atomic load. This does not impose ordering constraints.
1064 Address ivarAddr = LV.getAddress();
1065 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1066 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
1067 load->setAtomic(llvm::AtomicOrdering::Unordered);
1068
1069 // Store that value into the return address. Doing this with a
1070 // bitcast is likely to produce some pretty ugly IR, but it's not
1071 // the *most* terrible thing in the world.
1072 llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1073 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1074 llvm::Value *ivarVal = load;
1075 if (ivarSize > retTySize) {
1076 llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1077 ivarVal = Builder.CreateTrunc(load, newTy);
1078 bitcastType = newTy->getPointerTo();
1079 }
1080 Builder.CreateStore(ivarVal,
1081 Builder.CreateBitCast(ReturnValue, bitcastType));
1082
1083 // Make sure we don't do an autorelease.
1084 AutoreleaseResult = false;
1085 return;
1086 }
1087
1088 case PropertyImplStrategy::GetSetProperty: {
1089 llvm::FunctionCallee getPropertyFn =
1090 CGM.getObjCRuntime().GetPropertyGetFunction();
1091 if (!getPropertyFn) {
1092 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
1093 return;
1094 }
1095 CGCallee callee = CGCallee::forDirect(getPropertyFn);
1096
1097 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1098 // FIXME: Can't this be simpler? This might even be worse than the
1099 // corresponding gcc code.
1100 llvm::Value *cmd =
1101 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
1102 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1103 llvm::Value *ivarOffset =
1104 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1105
1106 CallArgList args;
1107 args.add(RValue::get(self), getContext().getObjCIdType());
1108 args.add(RValue::get(cmd), getContext().getObjCSelType());
1109 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1110 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1111 getContext().BoolTy);
1112
1113 // FIXME: We shouldn't need to get the function info here, the
1114 // runtime already should have computed it to build the function.
1115 llvm::CallBase *CallInstruction;
1116 RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(
1117 getContext().getObjCIdType(), args),
1118 callee, ReturnValueSlot(), args, &CallInstruction);
1119 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1120 call->setTailCall();
1121
1122 // We need to fix the type here. Ivars with copy & retain are
1123 // always objects so we don't need to worry about complex or
1124 // aggregates.
1125 RV = RValue::get(Builder.CreateBitCast(
1126 RV.getScalarVal(),
1127 getTypes().ConvertType(getterMethod->getReturnType())));
1128
1129 EmitReturnOfRValue(RV, propType);
1130
1131 // objc_getProperty does an autorelease, so we should suppress ours.
1132 AutoreleaseResult = false;
1133
1134 return;
1135 }
1136
1137 case PropertyImplStrategy::CopyStruct:
1138 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1139 strategy.hasStrongMember());
1140 return;
1141
1142 case PropertyImplStrategy::Expression:
1143 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1144 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1145
1146 QualType ivarType = ivar->getType();
1147 switch (getEvaluationKind(ivarType)) {
1148 case TEK_Complex: {
1149 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
1150 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
1151 /*init*/ true);
1152 return;
1153 }
1154 case TEK_Aggregate: {
1155 // The return value slot is guaranteed to not be aliased, but
1156 // that's not necessarily the same as "on the stack", so
1157 // we still potentially need objc_memmove_collectable.
1158 EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
1159 /* Src= */ LV, ivarType, getOverlapForReturnValue());
1160 return;
1161 }
1162 case TEK_Scalar: {
1163 llvm::Value *value;
1164 if (propType->isReferenceType()) {
1165 value = LV.getAddress().getPointer();
1166 } else {
1167 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1168 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1169 if (getLangOpts().ObjCAutoRefCount) {
1170 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1171 } else {
1172 value = EmitARCLoadWeak(LV.getAddress());
1173 }
1174
1175 // Otherwise we want to do a simple load, suppressing the
1176 // final autorelease.
1177 } else {
1178 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
1179 AutoreleaseResult = false;
1180 }
1181
1182 value = Builder.CreateBitCast(
1183 value, ConvertType(GetterMethodDecl->getReturnType()));
1184 }
1185
1186 EmitReturnOfRValue(RValue::get(value), propType);
1187 return;
1188 }
1189 }
1190 llvm_unreachable("bad evaluation kind")::llvm::llvm_unreachable_internal("bad evaluation kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 1190)
;
1191 }
1192
1193 }
1194 llvm_unreachable("bad @property implementation strategy!")::llvm::llvm_unreachable_internal("bad @property implementation strategy!"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 1194)
;
1195}
1196
1197/// emitStructSetterCall - Call the runtime function to store the value
1198/// from the first formal parameter into the given ivar.
1199static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1200 ObjCIvarDecl *ivar) {
1201 // objc_copyStruct (&structIvar, &Arg,
1202 // sizeof (struct something), true, false);
1203 CallArgList args;
1204
1205 // The first argument is the address of the ivar.
1206 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1207 CGF.LoadObjCSelf(), ivar, 0)
1208 .getPointer();
1209 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1210 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1211
1212 // The second argument is the address of the parameter variable.
1213 ParmVarDecl *argVar = *OMD->param_begin();
1214 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1215 argVar->getType().getNonReferenceType(), VK_LValue,
1216 SourceLocation());
1217 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
1218 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1219 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1220
1221 // The third argument is the sizeof the type.
1222 llvm::Value *size =
1223 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1224 args.add(RValue::get(size), CGF.getContext().getSizeType());
1225
1226 // The fourth argument is the 'isAtomic' flag.
1227 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
1228
1229 // The fifth argument is the 'hasStrong' flag.
1230 // FIXME: should this really always be false?
1231 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1232
1233 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1234 CGCallee callee = CGCallee::forDirect(fn);
1235 CGF.EmitCall(
1236 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1237 callee, ReturnValueSlot(), args);
1238}
1239
1240/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1241/// the value from the first formal parameter into the given ivar, using
1242/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1243static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1244 ObjCMethodDecl *OMD,
1245 ObjCIvarDecl *ivar,
1246 llvm::Constant *AtomicHelperFn) {
1247 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1248 // AtomicHelperFn);
1249 CallArgList args;
1250
1251 // The first argument is the address of the ivar.
1252 llvm::Value *ivarAddr =
1253 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1254 CGF.LoadObjCSelf(), ivar, 0).getPointer();
1255 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1256 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1257
1258 // The second argument is the address of the parameter variable.
1259 ParmVarDecl *argVar = *OMD->param_begin();
1260 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1261 argVar->getType().getNonReferenceType(), VK_LValue,
1262 SourceLocation());
1263 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
1264 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1265 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1266
1267 // Third argument is the helper function.
1268 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1269
1270 llvm::FunctionCallee fn =
1271 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
1272 CGCallee callee = CGCallee::forDirect(fn);
1273 CGF.EmitCall(
1274 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1275 callee, ReturnValueSlot(), args);
1276}
1277
1278
1279static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1280 Expr *setter = PID->getSetterCXXAssignment();
1281 if (!setter) return true;
1282
1283 // Sema only makes only of these when the ivar has a C++ class type,
1284 // so the form is pretty constrained.
1285
1286 // An operator call is trivial if the function it calls is trivial.
1287 // This also implies that there's nothing non-trivial going on with
1288 // the arguments, because operator= can only be trivial if it's a
1289 // synthesized assignment operator and therefore both parameters are
1290 // references.
1291 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
1292 if (const FunctionDecl *callee
1293 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1294 if (callee->isTrivial())
1295 return true;
1296 return false;
1297 }
1298
1299 assert(isa<ExprWithCleanups>(setter))((isa<ExprWithCleanups>(setter)) ? static_cast<void>
(0) : __assert_fail ("isa<ExprWithCleanups>(setter)", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 1299, __PRETTY_FUNCTION__))
;
1300 return false;
1301}
1302
1303static bool UseOptimizedSetter(CodeGenModule &CGM) {
1304 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
1305 return false;
1306 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
1307}
1308
1309void
1310CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1311 const ObjCPropertyImplDecl *propImpl,
1312 llvm::Constant *AtomicHelperFn) {
1313 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1314 ObjCMethodDecl *setterMethod = propImpl->getSetterMethodDecl();
1315
1316 // Just use the setter expression if Sema gave us one and it's
1317 // non-trivial.
1318 if (!hasTrivialSetExpr(propImpl)) {
1319 if (!AtomicHelperFn)
1320 // If non-atomic, assignment is called directly.
1321 EmitStmt(propImpl->getSetterCXXAssignment());
1322 else
1323 // If atomic, assignment is called via a locking api.
1324 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1325 AtomicHelperFn);
1326 return;
1327 }
1328
1329 PropertyImplStrategy strategy(CGM, propImpl);
1330 switch (strategy.getKind()) {
1331 case PropertyImplStrategy::Native: {
1332 // We don't need to do anything for a zero-size struct.
1333 if (strategy.getIvarSize().isZero())
1334 return;
1335
1336 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1337
1338 LValue ivarLValue =
1339 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1340 Address ivarAddr = ivarLValue.getAddress();
1341
1342 // Currently, all atomic accesses have to be through integer
1343 // types, so there's no point in trying to pick a prettier type.
1344 llvm::Type *bitcastType =
1345 llvm::Type::getIntNTy(getLLVMContext(),
1346 getContext().toBits(strategy.getIvarSize()));
1347
1348 // Cast both arguments to the chosen operation type.
1349 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1350 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
1351
1352 // This bitcast load is likely to cause some nasty IR.
1353 llvm::Value *load = Builder.CreateLoad(argAddr);
1354
1355 // Perform an atomic store. There are no memory ordering requirements.
1356 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1357 store->setAtomic(llvm::AtomicOrdering::Unordered);
1358 return;
1359 }
1360
1361 case PropertyImplStrategy::GetSetProperty:
1362 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1363
1364 llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
1365 llvm::FunctionCallee setPropertyFn = nullptr;
1366 if (UseOptimizedSetter(CGM)) {
1367 // 10.8 and iOS 6.0 code and GC is off
1368 setOptimizedPropertyFn =
1369 CGM.getObjCRuntime().GetOptimizedPropertySetFunction(
1370 strategy.isAtomic(), strategy.isCopy());
1371 if (!setOptimizedPropertyFn) {
1372 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1373 return;
1374 }
1375 }
1376 else {
1377 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1378 if (!setPropertyFn) {
1379 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1380 return;
1381 }
1382 }
1383
1384 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1385 // <is-atomic>, <is-copy>).
1386 llvm::Value *cmd =
1387 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
1388 llvm::Value *self =
1389 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1390 llvm::Value *ivarOffset =
1391 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1392 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1393 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1394 arg = Builder.CreateBitCast(arg, VoidPtrTy);
1395
1396 CallArgList args;
1397 args.add(RValue::get(self), getContext().getObjCIdType());
1398 args.add(RValue::get(cmd), getContext().getObjCSelType());
1399 if (setOptimizedPropertyFn) {
1400 args.add(RValue::get(arg), getContext().getObjCIdType());
1401 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1402 CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
1403 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1404 callee, ReturnValueSlot(), args);
1405 } else {
1406 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1407 args.add(RValue::get(arg), getContext().getObjCIdType());
1408 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1409 getContext().BoolTy);
1410 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1411 getContext().BoolTy);
1412 // FIXME: We shouldn't need to get the function info here, the runtime
1413 // already should have computed it to build the function.
1414 CGCallee callee = CGCallee::forDirect(setPropertyFn);
1415 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1416 callee, ReturnValueSlot(), args);
1417 }
1418
1419 return;
1420 }
1421
1422 case PropertyImplStrategy::CopyStruct:
1423 emitStructSetterCall(*this, setterMethod, ivar);
1424 return;
1425
1426 case PropertyImplStrategy::Expression:
1427 break;
1428 }
1429
1430 // Otherwise, fake up some ASTs and emit a normal assignment.
1431 ValueDecl *selfDecl = setterMethod->getSelfDecl();
1432 DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
1433 VK_LValue, SourceLocation());
1434 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1435 selfDecl->getType(), CK_LValueToRValue, &self,
1436 VK_RValue);
1437 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1438 SourceLocation(), SourceLocation(),
1439 &selfLoad, true, true);
1440
1441 ParmVarDecl *argDecl = *setterMethod->param_begin();
1442 QualType argType = argDecl->getType().getNonReferenceType();
1443 DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1444 SourceLocation());
1445 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1446 argType.getUnqualifiedType(), CK_LValueToRValue,
1447 &arg, VK_RValue);
1448
1449 // The property type can differ from the ivar type in some situations with
1450 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1451 // The following absurdity is just to ensure well-formed IR.
1452 CastKind argCK = CK_NoOp;
1453 if (ivarRef.getType()->isObjCObjectPointerType()) {
1454 if (argLoad.getType()->isObjCObjectPointerType())
1455 argCK = CK_BitCast;
1456 else if (argLoad.getType()->isBlockPointerType())
1457 argCK = CK_BlockPointerToObjCPointerCast;
1458 else
1459 argCK = CK_CPointerToObjCPointerCast;
1460 } else if (ivarRef.getType()->isBlockPointerType()) {
1461 if (argLoad.getType()->isBlockPointerType())
1462 argCK = CK_BitCast;
1463 else
1464 argCK = CK_AnyPointerToBlockPointerCast;
1465 } else if (ivarRef.getType()->isPointerType()) {
1466 argCK = CK_BitCast;
1467 }
1468 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1469 ivarRef.getType(), argCK, &argLoad,
1470 VK_RValue);
1471 Expr *finalArg = &argLoad;
1472 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1473 argLoad.getType()))
1474 finalArg = &argCast;
1475
1476
1477 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1478 ivarRef.getType(), VK_RValue, OK_Ordinary,
1479 SourceLocation(), FPOptions());
1480 EmitStmt(&assign);
1481}
1482
1483/// Generate an Objective-C property setter function.
1484///
1485/// The given Decl must be an ObjCImplementationDecl. \@synthesize
1486/// is illegal within a category.
1487void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1488 const ObjCPropertyImplDecl *PID) {
1489 llvm::Constant *AtomicHelperFn =
1490 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
1491 ObjCMethodDecl *OMD = PID->getSetterMethodDecl();
1492 assert(OMD && "Invalid call to generate setter (empty method)")((OMD && "Invalid call to generate setter (empty method)"
) ? static_cast<void> (0) : __assert_fail ("OMD && \"Invalid call to generate setter (empty method)\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 1492, __PRETTY_FUNCTION__))
;
1493 StartObjCMethod(OMD, IMP->getClassInterface());
1494
1495 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
1496
1497 FinishFunction();
1498}
1499
1500namespace {
1501 struct DestroyIvar final : EHScopeStack::Cleanup {
1502 private:
1503 llvm::Value *addr;
1504 const ObjCIvarDecl *ivar;
1505 CodeGenFunction::Destroyer *destroyer;
1506 bool useEHCleanupForArray;
1507 public:
1508 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1509 CodeGenFunction::Destroyer *destroyer,
1510 bool useEHCleanupForArray)
1511 : addr(addr), ivar(ivar), destroyer(destroyer),
1512 useEHCleanupForArray(useEHCleanupForArray) {}
1513
1514 void Emit(CodeGenFunction &CGF, Flags flags) override {
1515 LValue lvalue
1516 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1517 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
1518 flags.isForNormalCleanup() && useEHCleanupForArray);
1519 }
1520 };
1521}
1522
1523/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1524static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1525 Address addr,
1526 QualType type) {
1527 llvm::Value *null = getNullForVariable(addr);
1528 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1529}
1530
1531static void emitCXXDestructMethod(CodeGenFunction &CGF,
1532 ObjCImplementationDecl *impl) {
1533 CodeGenFunction::RunCleanupsScope scope(CGF);
1534
1535 llvm::Value *self = CGF.LoadObjCSelf();
1536
1537 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1538 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1539 ivar; ivar = ivar->getNextIvar()) {
1540 QualType type = ivar->getType();
1541
1542 // Check whether the ivar is a destructible type.
1543 QualType::DestructionKind dtorKind = type.isDestructedType();
1544 if (!dtorKind) continue;
1545
1546 CodeGenFunction::Destroyer *destroyer = nullptr;
1547
1548 // Use a call to objc_storeStrong to destroy strong ivars, for the
1549 // general benefit of the tools.
1550 if (dtorKind == QualType::DK_objc_strong_lifetime) {
1551 destroyer = destroyARCStrongWithStore;
1552
1553 // Otherwise use the default for the destruction kind.
1554 } else {
1555 destroyer = CGF.getDestroyer(dtorKind);
1556 }
1557
1558 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1559
1560 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1561 cleanupKind & EHCleanup);
1562 }
1563
1564 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?")((scope.requiresCleanups() && "nothing to do in .cxx_destruct?"
) ? static_cast<void> (0) : __assert_fail ("scope.requiresCleanups() && \"nothing to do in .cxx_destruct?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 1564, __PRETTY_FUNCTION__))
;
1565}
1566
1567void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1568 ObjCMethodDecl *MD,
1569 bool ctor) {
1570 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
1571 StartObjCMethod(MD, IMP->getClassInterface());
1572
1573 // Emit .cxx_construct.
1574 if (ctor) {
1575 // Suppress the final autorelease in ARC.
1576 AutoreleaseResult = false;
1577
1578 for (const auto *IvarInit : IMP->inits()) {
1579 FieldDecl *Field = IvarInit->getAnyMember();
1580 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
1581 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1582 LoadObjCSelf(), Ivar, 0);
1583 EmitAggExpr(IvarInit->getInit(),
1584 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
1585 AggValueSlot::DoesNotNeedGCBarriers,
1586 AggValueSlot::IsNotAliased,
1587 AggValueSlot::DoesNotOverlap));
1588 }
1589 // constructor returns 'self'.
1590 CodeGenTypes &Types = CGM.getTypes();
1591 QualType IdTy(CGM.getContext().getObjCIdType());
1592 llvm::Value *SelfAsId =
1593 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1594 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
1595
1596 // Emit .cxx_destruct.
1597 } else {
1598 emitCXXDestructMethod(*this, IMP);
1599 }
1600 FinishFunction();
1601}
1602
1603llvm::Value *CodeGenFunction::LoadObjCSelf() {
1604 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1605 DeclRefExpr DRE(getContext(), Self,
1606 /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1607 Self->getType(), VK_LValue, SourceLocation());
1608 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
1609}
1610
1611QualType CodeGenFunction::TypeOfSelfObject() {
1612 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1613 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
1614 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1615 getContext().getCanonicalType(selfDecl->getType()));
1616 return PTy->getPointeeType();
1617}
1618
1619void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
1620 llvm::FunctionCallee EnumerationMutationFnPtr =
1621 CGM.getObjCRuntime().EnumerationMutationFunction();
1622 if (!EnumerationMutationFnPtr) {
1623 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1624 return;
1625 }
1626 CGCallee EnumerationMutationFn =
1627 CGCallee::forDirect(EnumerationMutationFnPtr);
1628
1629 CGDebugInfo *DI = getDebugInfo();
1630 if (DI)
1631 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
1632
1633 RunCleanupsScope ForScope(*this);
1634
1635 // The local variable comes into scope immediately.
1636 AutoVarEmission variable = AutoVarEmission::invalid();
1637 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1638 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1639
1640 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
1641
1642 // Fast enumeration state.
1643 QualType StateTy = CGM.getObjCFastEnumerationStateType();
1644 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
1645 EmitNullInitialization(StatePtr, StateTy);
1646
1647 // Number of elements in the items array.
1648 static const unsigned NumItems = 16;
1649
1650 // Fetch the countByEnumeratingWithState:objects:count: selector.
1651 IdentifierInfo *II[] = {
1652 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1653 &CGM.getContext().Idents.get("objects"),
1654 &CGM.getContext().Idents.get("count")
1655 };
1656 Selector FastEnumSel =
1657 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
1658
1659 QualType ItemsTy =
1660 getContext().getConstantArrayType(getContext().getObjCIdType(),
1661 llvm::APInt(32, NumItems), nullptr,
1662 ArrayType::Normal, 0);
1663 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
1664
1665 // Emit the collection pointer. In ARC, we do a retain.
1666 llvm::Value *Collection;
1667 if (getLangOpts().ObjCAutoRefCount) {
1668 Collection = EmitARCRetainScalarExpr(S.getCollection());
1669
1670 // Enter a cleanup to do the release.
1671 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1672 } else {
1673 Collection = EmitScalarExpr(S.getCollection());
1674 }
1675
1676 // The 'continue' label needs to appear within the cleanup for the
1677 // collection object.
1678 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1679
1680 // Send it our message:
1681 CallArgList Args;
1682
1683 // The first argument is a temporary of the enumeration-state type.
1684 Args.add(RValue::get(StatePtr.getPointer()),
1685 getContext().getPointerType(StateTy));
1686
1687 // The second argument is a temporary array with space for NumItems
1688 // pointers. We'll actually be loading elements from the array
1689 // pointer written into the control state; this buffer is so that
1690 // collections that *aren't* backed by arrays can still queue up
1691 // batches of elements.
1692 Args.add(RValue::get(ItemsPtr.getPointer()),
1693 getContext().getPointerType(ItemsTy));
1694
1695 // The third argument is the capacity of that temporary array.
1696 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1697 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1698 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
1699
1700 // Start the enumeration.
1701 RValue CountRV =
1702 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1703 getContext().getNSUIntegerType(),
1704 FastEnumSel, Collection, Args);
1705
1706 // The initial number of objects that were returned in the buffer.
1707 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
1708
1709 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1710 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
1711
1712 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
1713
1714 // If the limit pointer was zero to begin with, the collection is
1715 // empty; skip all this. Set the branch weight assuming this has the same
1716 // probability of exiting the loop as any other loop exit.
1717 uint64_t EntryCount = getCurrentProfileCount();
1718 Builder.CreateCondBr(
1719 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1720 LoopInitBB,
1721 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
1722
1723 // Otherwise, initialize the loop.
1724 EmitBlock(LoopInitBB);
1725
1726 // Save the initial mutations value. This is the value at an
1727 // address that was written into the state object by
1728 // countByEnumeratingWithState:objects:count:.
1729 Address StateMutationsPtrPtr =
1730 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
1731 llvm::Value *StateMutationsPtr
1732 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1733
1734 llvm::Value *initialMutations =
1735 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1736 "forcoll.initial-mutations");
1737
1738 // Start looping. This is the point we return to whenever we have a
1739 // fresh, non-empty batch of objects.
1740 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1741 EmitBlock(LoopBodyBB);
1742
1743 // The current index into the buffer.
1744 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
1745 index->addIncoming(zero, LoopInitBB);
1746
1747 // The current buffer size.
1748 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
1749 count->addIncoming(initialBufferLimit, LoopInitBB);
1750
1751 incrementProfileCounter(&S);
1752
1753 // Check whether the mutations value has changed from where it was
1754 // at start. StateMutationsPtr should actually be invariant between
1755 // refreshes.
1756 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1757 llvm::Value *currentMutations
1758 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1759 "statemutations");
1760
1761 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
1762 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
1763
1764 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1765 WasNotMutatedBB, WasMutatedBB);
1766
1767 // If so, call the enumeration-mutation function.
1768 EmitBlock(WasMutatedBB);
1769 llvm::Value *V =
1770 Builder.CreateBitCast(Collection,
1771 ConvertType(getContext().getObjCIdType()));
1772 CallArgList Args2;
1773 Args2.add(RValue::get(V), getContext().getObjCIdType());
1774 // FIXME: We shouldn't need to get the function info here, the runtime already
1775 // should have computed it to build the function.
1776 EmitCall(
1777 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
1778 EnumerationMutationFn, ReturnValueSlot(), Args2);
1779
1780 // Otherwise, or if the mutation function returns, just continue.
1781 EmitBlock(WasNotMutatedBB);
1782
1783 // Initialize the element variable.
1784 RunCleanupsScope elementVariableScope(*this);
1785 bool elementIsVariable;
1786 LValue elementLValue;
1787 QualType elementType;
1788 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
1789 // Initialize the variable, in case it's a __block variable or something.
1790 EmitAutoVarInit(variable);
1791
1792 const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1793 DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1794 D->getType(), VK_LValue, SourceLocation());
1795 elementLValue = EmitLValue(&tempDRE);
1796 elementType = D->getType();
1797 elementIsVariable = true;
1798
1799 if (D->isARCPseudoStrong())
1800 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
1801 } else {
1802 elementLValue = LValue(); // suppress warning
1803 elementType = cast<Expr>(S.getElement())->getType();
1804 elementIsVariable = false;
1805 }
1806 llvm::Type *convertedElementType = ConvertType(elementType);
1807
1808 // Fetch the buffer out of the enumeration state.
1809 // TODO: this pointer should actually be invariant between
1810 // refreshes, which would help us do certain loop optimizations.
1811 Address StateItemsPtr =
1812 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
1813 llvm::Value *EnumStateItems =
1814 Builder.CreateLoad(StateItemsPtr, "stateitems");
1815
1816 // Fetch the value at the current index from the buffer.
1817 llvm::Value *CurrentItemPtr =
1818 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1819 llvm::Value *CurrentItem =
1820 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
1821
1822 // Cast that value to the right type.
1823 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1824 "currentitem");
1825
1826 // Make sure we have an l-value. Yes, this gets evaluated every
1827 // time through the loop.
1828 if (!elementIsVariable) {
1829 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1830 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
1831 } else {
1832 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1833 /*isInit*/ true);
1834 }
1835
1836 // If we do have an element variable, this assignment is the end of
1837 // its initialization.
1838 if (elementIsVariable)
1839 EmitAutoVarCleanups(variable);
1840
1841 // Perform the loop body, setting up break and continue labels.
1842 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
1843 {
1844 RunCleanupsScope Scope(*this);
1845 EmitStmt(S.getBody());
1846 }
1847 BreakContinueStack.pop_back();
1848
1849 // Destroy the element variable now.
1850 elementVariableScope.ForceCleanup();
1851
1852 // Check whether there are more elements.
1853 EmitBlock(AfterBody.getBlock());
1854
1855 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
1856
1857 // First we check in the local buffer.
1858 llvm::Value *indexPlusOne =
1859 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
1860
1861 // If we haven't overrun the buffer yet, we can continue.
1862 // Set the branch weights based on the simplifying assumption that this is
1863 // like a while-loop, i.e., ignoring that the false branch fetches more
1864 // elements and then returns to the loop.
1865 Builder.CreateCondBr(
1866 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
1867 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
1868
1869 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1870 count->addIncoming(count, AfterBody.getBlock());
1871
1872 // Otherwise, we have to fetch more elements.
1873 EmitBlock(FetchMoreBB);
1874
1875 CountRV =
1876 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1877 getContext().getNSUIntegerType(),
1878 FastEnumSel, Collection, Args);
1879
1880 // If we got a zero count, we're done.
1881 llvm::Value *refetchCount = CountRV.getScalarVal();
1882
1883 // (note that the message send might split FetchMoreBB)
1884 index->addIncoming(zero, Builder.GetInsertBlock());
1885 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1886
1887 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1888 EmptyBB, LoopBodyBB);
1889
1890 // No more elements.
1891 EmitBlock(EmptyBB);
1892
1893 if (!elementIsVariable) {
1894 // If the element was not a declaration, set it to be null.
1895
1896 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1897 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1898 EmitStoreThroughLValue(RValue::get(null), elementLValue);
1899 }
1900
1901 if (DI)
1902 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
1903
1904 ForScope.ForceCleanup();
1905 EmitBlock(LoopEnd.getBlock());
1906}
1907
1908void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
1909 CGM.getObjCRuntime().EmitTryStmt(*this, S);
1910}
1911
1912void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
1913 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1914}
1915
1916void CodeGenFunction::EmitObjCAtSynchronizedStmt(
1917 const ObjCAtSynchronizedStmt &S) {
1918 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
1919}
1920
1921namespace {
1922 struct CallObjCRelease final : EHScopeStack::Cleanup {
1923 CallObjCRelease(llvm::Value *object) : object(object) {}
1924 llvm::Value *object;
1925
1926 void Emit(CodeGenFunction &CGF, Flags flags) override {
1927 // Releases at the end of the full-expression are imprecise.
1928 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
1929 }
1930 };
1931}
1932
1933/// Produce the code for a CK_ARCConsumeObject. Does a primitive
1934/// release at the end of the full-expression.
1935llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1936 llvm::Value *object) {
1937 // If we're in a conditional branch, we need to make the cleanup
1938 // conditional.
1939 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
1940 return object;
1941}
1942
1943llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1944 llvm::Value *value) {
1945 return EmitARCRetainAutorelease(type, value);
1946}
1947
1948/// Given a number of pointers, inform the optimizer that they're
1949/// being intrinsically used up until this point in the program.
1950void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
1951 llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
1952 if (!fn)
1953 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
1954
1955 // This isn't really a "runtime" function, but as an intrinsic it
1956 // doesn't really matter as long as we align things up.
1957 EmitNounwindRuntimeCall(fn, values);
1958}
1959
1960static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {
1961 if (auto *F = dyn_cast<llvm::Function>(RTF)) {
1962 // If the target runtime doesn't naturally support ARC, emit weak
1963 // references to the runtime support library. We don't really
1964 // permit this to fail, but we need a particular relocation style.
1965 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1966 !CGM.getTriple().isOSBinFormatCOFF()) {
1967 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1968 }
1969 }
1970}
1971
1972static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
1973 llvm::FunctionCallee RTF) {
1974 setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());
1975}
1976
1977/// Perform an operation having the signature
1978/// i8* (i8*)
1979/// where a null input causes a no-op and returns null.
1980static llvm::Value *emitARCValueOperation(
1981 CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType,
1982 llvm::Function *&fn, llvm::Intrinsic::ID IntID,
1983 llvm::CallInst::TailCallKind tailKind = llvm::CallInst::TCK_None) {
1984 if (isa<llvm::ConstantPointerNull>(value))
1985 return value;
1986
1987 if (!fn) {
1988 fn = CGF.CGM.getIntrinsic(IntID);
1989 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
1990 }
1991
1992 // Cast the argument to 'id'.
1993 llvm::Type *origType = returnType ? returnType : value->getType();
1994 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1995
1996 // Call the function.
1997 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
1998 call->setTailCallKind(tailKind);
1999
2000 // Cast the result back to the original type.
2001 return CGF.Builder.CreateBitCast(call, origType);
2002}
2003
2004/// Perform an operation having the following signature:
2005/// i8* (i8**)
2006static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,
2007 llvm::Function *&fn,
2008 llvm::Intrinsic::ID IntID) {
2009 if (!fn) {
2010 fn = CGF.CGM.getIntrinsic(IntID);
2011 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
2012 }
2013
2014 // Cast the argument to 'id*'.
2015 llvm::Type *origType = addr.getElementType();
2016 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
2017
2018 // Call the function.
2019 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
2020
2021 // Cast the result back to a dereference of the original type.
2022 if (origType != CGF.Int8PtrTy)
2023 result = CGF.Builder.CreateBitCast(result, origType);
2024
2025 return result;
2026}
2027
2028/// Perform an operation having the following signature:
2029/// i8* (i8**, i8*)
2030static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,
2031 llvm::Value *value,
2032 llvm::Function *&fn,
2033 llvm::Intrinsic::ID IntID,
2034 bool ignored) {
2035 assert(addr.getElementType() == value->getType())((addr.getElementType() == value->getType()) ? static_cast
<void> (0) : __assert_fail ("addr.getElementType() == value->getType()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 2035, __PRETTY_FUNCTION__))
;
2036
2037 if (!fn) {
2038 fn = CGF.CGM.getIntrinsic(IntID);
2039 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
2040 }
2041
2042 llvm::Type *origType = value->getType();
2043
2044 llvm::Value *args[] = {
2045 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
2046 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
2047 };
2048 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
2049
2050 if (ignored) return nullptr;
2051
2052 return CGF.Builder.CreateBitCast(result, origType);
2053}
2054
2055/// Perform an operation having the following signature:
2056/// void (i8**, i8**)
2057static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src,
2058 llvm::Function *&fn,
2059 llvm::Intrinsic::ID IntID) {
2060 assert(dst.getType() == src.getType())((dst.getType() == src.getType()) ? static_cast<void> (
0) : __assert_fail ("dst.getType() == src.getType()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 2060, __PRETTY_FUNCTION__))
;
2061
2062 if (!fn) {
2063 fn = CGF.CGM.getIntrinsic(IntID);
2064 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
2065 }
2066
2067 llvm::Value *args[] = {
2068 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2069 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
2070 };
2071 CGF.EmitNounwindRuntimeCall(fn, args);
2072}
2073
2074/// Perform an operation having the signature
2075/// i8* (i8*)
2076/// where a null input causes a no-op and returns null.
2077static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2078 llvm::Value *value,
2079 llvm::Type *returnType,
2080 llvm::FunctionCallee &fn,
2081 StringRef fnName) {
2082 if (isa<llvm::ConstantPointerNull>(value))
2083 return value;
2084
2085 if (!fn) {
2086 llvm::FunctionType *fnType =
2087 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2088 fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
2089
2090 // We have Native ARC, so set nonlazybind attribute for performance
2091 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2092 if (fnName == "objc_retain")
2093 f->addFnAttr(llvm::Attribute::NonLazyBind);
2094 }
2095
2096 // Cast the argument to 'id'.
2097 llvm::Type *origType = returnType ? returnType : value->getType();
2098 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2099
2100 // Call the function.
2101 llvm::CallBase *Inst = CGF.EmitCallOrInvoke(fn, value);
2102
2103 // Cast the result back to the original type.
2104 return CGF.Builder.CreateBitCast(Inst, origType);
2105}
2106
2107/// Produce the code to do a retain. Based on the type, calls one of:
2108/// call i8* \@objc_retain(i8* %value)
2109/// call i8* \@objc_retainBlock(i8* %value)
2110llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2111 if (type->isBlockPointerType())
2112 return EmitARCRetainBlock(value, /*mandatory*/ false);
2113 else
2114 return EmitARCRetainNonBlock(value);
2115}
2116
2117/// Retain the given object, with normal retain semantics.
2118/// call i8* \@objc_retain(i8* %value)
2119llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
2120 return emitARCValueOperation(*this, value, nullptr,
2121 CGM.getObjCEntrypoints().objc_retain,
2122 llvm::Intrinsic::objc_retain);
2123}
2124
2125/// Retain the given block, with _Block_copy semantics.
2126/// call i8* \@objc_retainBlock(i8* %value)
2127///
2128/// \param mandatory - If false, emit the call with metadata
2129/// indicating that it's okay for the optimizer to eliminate this call
2130/// if it can prove that the block never escapes except down the stack.
2131llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2132 bool mandatory) {
2133 llvm::Value *result
2134 = emitARCValueOperation(*this, value, nullptr,
2135 CGM.getObjCEntrypoints().objc_retainBlock,
2136 llvm::Intrinsic::objc_retainBlock);
2137
2138 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2139 // tell the optimizer that it doesn't need to do this copy if the
2140 // block doesn't escape, where being passed as an argument doesn't
2141 // count as escaping.
2142 if (!mandatory && isa<llvm::Instruction>(result)) {
2143 llvm::CallInst *call
2144 = cast<llvm::CallInst>(result->stripPointerCasts());
2145 assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock)((call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock
) ? static_cast<void> (0) : __assert_fail ("call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 2145, __PRETTY_FUNCTION__))
;
2146
2147 call->setMetadata("clang.arc.copy_on_escape",
2148 llvm::MDNode::get(Builder.getContext(), None));
2149 }
2150
2151 return result;
2152}
2153
2154static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
2155 // Fetch the void(void) inline asm which marks that we're going to
2156 // do something with the autoreleased return value.
2157 llvm::InlineAsm *&marker
2158 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
2159 if (!marker) {
2160 StringRef assembly
2161 = CGF.CGM.getTargetCodeGenInfo()
2162 .getARCRetainAutoreleasedReturnValueMarker();
2163
2164 // If we have an empty assembly string, there's nothing to do.
2165 if (assembly.empty()) {
2166
2167 // Otherwise, at -O0, build an inline asm that we're going to call
2168 // in a moment.
2169 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
2170 llvm::FunctionType *type =
2171 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
2172
2173 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2174
2175 // If we're at -O1 and above, we don't want to litter the code
2176 // with this marker yet, so leave a breadcrumb for the ARC
2177 // optimizer to pick up.
2178 } else {
2179 const char *markerKey = "clang.arc.retainAutoreleasedReturnValueMarker";
2180 if (!CGF.CGM.getModule().getModuleFlag(markerKey)) {
2181 auto *str = llvm::MDString::get(CGF.getLLVMContext(), assembly);
2182 CGF.CGM.getModule().addModuleFlag(llvm::Module::Error, markerKey, str);
2183 }
2184 }
2185 }
2186
2187 // Call the marker asm if we made one, which we do only at -O0.
2188 if (marker)
2189 CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
2190}
2191
2192/// Retain the given object which is the result of a function call.
2193/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2194///
2195/// Yes, this function name is one character away from a different
2196/// call with completely different semantics.
2197llvm::Value *
2198CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2199 emitAutoreleasedReturnValueMarker(*this);
2200 llvm::CallInst::TailCallKind tailKind =
2201 CGM.getTargetCodeGenInfo()
2202 .shouldSuppressTailCallsOfRetainAutoreleasedReturnValue()
2203 ? llvm::CallInst::TCK_NoTail
2204 : llvm::CallInst::TCK_None;
2205 return emitARCValueOperation(
2206 *this, value, nullptr,
2207 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
2208 llvm::Intrinsic::objc_retainAutoreleasedReturnValue, tailKind);
2209}
2210
2211/// Claim a possibly-autoreleased return value at +0. This is only
2212/// valid to do in contexts which do not rely on the retain to keep
2213/// the object valid for all of its uses; for example, when
2214/// the value is ignored, or when it is being assigned to an
2215/// __unsafe_unretained variable.
2216///
2217/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2218llvm::Value *
2219CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2220 emitAutoreleasedReturnValueMarker(*this);
2221 return emitARCValueOperation(*this, value, nullptr,
2222 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
2223 llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue);
2224}
2225
2226/// Release the given object.
2227/// call void \@objc_release(i8* %value)
2228void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2229 ARCPreciseLifetime_t precise) {
2230 if (isa<llvm::ConstantPointerNull>(value)) return;
2231
2232 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
2233 if (!fn) {
2234 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_release);
2235 setARCRuntimeFunctionLinkage(CGM, fn);
2236 }
2237
2238 // Cast the argument to 'id'.
2239 value = Builder.CreateBitCast(value, Int8PtrTy);
2240
2241 // Call objc_release.
2242 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
2243
2244 if (precise == ARCImpreciseLifetime) {
2245 call->setMetadata("clang.imprecise_release",
2246 llvm::MDNode::get(Builder.getContext(), None));
2247 }
2248}
2249
2250/// Destroy a __strong variable.
2251///
2252/// At -O0, emit a call to store 'null' into the address;
2253/// instrumenting tools prefer this because the address is exposed,
2254/// but it's relatively cumbersome to optimize.
2255///
2256/// At -O1 and above, just load and call objc_release.
2257///
2258/// call void \@objc_storeStrong(i8** %addr, i8* null)
2259void CodeGenFunction::EmitARCDestroyStrong(Address addr,
2260 ARCPreciseLifetime_t precise) {
2261 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2262 llvm::Value *null = getNullForVariable(addr);
2263 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2264 return;
2265 }
2266
2267 llvm::Value *value = Builder.CreateLoad(addr);
2268 EmitARCRelease(value, precise);
2269}
2270
2271/// Store into a strong object. Always calls this:
2272/// call void \@objc_storeStrong(i8** %addr, i8* %value)
2273llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
2274 llvm::Value *value,
2275 bool ignored) {
2276 assert(addr.getElementType() == value->getType())((addr.getElementType() == value->getType()) ? static_cast
<void> (0) : __assert_fail ("addr.getElementType() == value->getType()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 2276, __PRETTY_FUNCTION__))
;
2277
2278 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
2279 if (!fn) {
2280 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_storeStrong);
2281 setARCRuntimeFunctionLinkage(CGM, fn);
2282 }
2283
2284 llvm::Value *args[] = {
2285 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
2286 Builder.CreateBitCast(value, Int8PtrTy)
2287 };
2288 EmitNounwindRuntimeCall(fn, args);
2289
2290 if (ignored) return nullptr;
2291 return value;
2292}
2293
2294/// Store into a strong object. Sometimes calls this:
2295/// call void \@objc_storeStrong(i8** %addr, i8* %value)
2296/// Other times, breaks it down into components.
2297llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
2298 llvm::Value *newValue,
2299 bool ignored) {
2300 QualType type = dst.getType();
2301 bool isBlock = type->isBlockPointerType();
2302
2303 // Use a store barrier at -O0 unless this is a block type or the
2304 // lvalue is inadequately aligned.
2305 if (shouldUseFusedARCCalls() &&
2306 !isBlock &&
2307 (dst.getAlignment().isZero() ||
2308 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
2309 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2310 }
2311
2312 // Otherwise, split it out.
2313
2314 // Retain the new value.
2315 newValue = EmitARCRetain(type, newValue);
2316
2317 // Read the old value.
2318 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
2319
2320 // Store. We do this before the release so that any deallocs won't
2321 // see the old value.
2322 EmitStoreOfScalar(newValue, dst);
2323
2324 // Finally, release the old value.
2325 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
2326
2327 return newValue;
2328}
2329
2330/// Autorelease the given object.
2331/// call i8* \@objc_autorelease(i8* %value)
2332llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2333 return emitARCValueOperation(*this, value, nullptr,
2334 CGM.getObjCEntrypoints().objc_autorelease,
2335 llvm::Intrinsic::objc_autorelease);
2336}
2337
2338/// Autorelease the given object.
2339/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
2340llvm::Value *
2341CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2342 return emitARCValueOperation(*this, value, nullptr,
2343 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
2344 llvm::Intrinsic::objc_autoreleaseReturnValue,
2345 llvm::CallInst::TCK_Tail);
2346}
2347
2348/// Do a fused retain/autorelease of the given object.
2349/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
2350llvm::Value *
2351CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2352 return emitARCValueOperation(*this, value, nullptr,
2353 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
2354 llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
2355 llvm::CallInst::TCK_Tail);
2356}
2357
2358/// Do a fused retain/autorelease of the given object.
2359/// call i8* \@objc_retainAutorelease(i8* %value)
2360/// or
2361/// %retain = call i8* \@objc_retainBlock(i8* %value)
2362/// call i8* \@objc_autorelease(i8* %retain)
2363llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2364 llvm::Value *value) {
2365 if (!type->isBlockPointerType())
2366 return EmitARCRetainAutoreleaseNonBlock(value);
2367
2368 if (isa<llvm::ConstantPointerNull>(value)) return value;
2369
2370 llvm::Type *origType = value->getType();
2371 value = Builder.CreateBitCast(value, Int8PtrTy);
2372 value = EmitARCRetainBlock(value, /*mandatory*/ true);
2373 value = EmitARCAutorelease(value);
2374 return Builder.CreateBitCast(value, origType);
2375}
2376
2377/// Do a fused retain/autorelease of the given object.
2378/// call i8* \@objc_retainAutorelease(i8* %value)
2379llvm::Value *
2380CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2381 return emitARCValueOperation(*this, value, nullptr,
2382 CGM.getObjCEntrypoints().objc_retainAutorelease,
2383 llvm::Intrinsic::objc_retainAutorelease);
2384}
2385
2386/// i8* \@objc_loadWeak(i8** %addr)
2387/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2388llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2389 return emitARCLoadOperation(*this, addr,
2390 CGM.getObjCEntrypoints().objc_loadWeak,
2391 llvm::Intrinsic::objc_loadWeak);
2392}
2393
2394/// i8* \@objc_loadWeakRetained(i8** %addr)
2395llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
2396 return emitARCLoadOperation(*this, addr,
2397 CGM.getObjCEntrypoints().objc_loadWeakRetained,
2398 llvm::Intrinsic::objc_loadWeakRetained);
2399}
2400
2401/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
2402/// Returns %value.
2403llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
2404 llvm::Value *value,
2405 bool ignored) {
2406 return emitARCStoreOperation(*this, addr, value,
2407 CGM.getObjCEntrypoints().objc_storeWeak,
2408 llvm::Intrinsic::objc_storeWeak, ignored);
2409}
2410
2411/// i8* \@objc_initWeak(i8** %addr, i8* %value)
2412/// Returns %value. %addr is known to not have a current weak entry.
2413/// Essentially equivalent to:
2414/// *addr = nil; objc_storeWeak(addr, value);
2415void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
2416 // If we're initializing to null, just write null to memory; no need
2417 // to get the runtime involved. But don't do this if optimization
2418 // is enabled, because accounting for this would make the optimizer
2419 // much more complicated.
2420 if (isa<llvm::ConstantPointerNull>(value) &&
2421 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2422 Builder.CreateStore(value, addr);
2423 return;
2424 }
2425
2426 emitARCStoreOperation(*this, addr, value,
2427 CGM.getObjCEntrypoints().objc_initWeak,
2428 llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
2429}
2430
2431/// void \@objc_destroyWeak(i8** %addr)
2432/// Essentially objc_storeWeak(addr, nil).
2433void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
2434 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
2435 if (!fn) {
2436 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_destroyWeak);
2437 setARCRuntimeFunctionLinkage(CGM, fn);
2438 }
2439
2440 // Cast the argument to 'id*'.
2441 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2442
2443 EmitNounwindRuntimeCall(fn, addr.getPointer());
2444}
2445
2446/// void \@objc_moveWeak(i8** %dest, i8** %src)
2447/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2448/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2449void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
2450 emitARCCopyOperation(*this, dst, src,
2451 CGM.getObjCEntrypoints().objc_moveWeak,
2452 llvm::Intrinsic::objc_moveWeak);
2453}
2454
2455/// void \@objc_copyWeak(i8** %dest, i8** %src)
2456/// Disregards the current value in %dest. Essentially
2457/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2458void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
2459 emitARCCopyOperation(*this, dst, src,
2460 CGM.getObjCEntrypoints().objc_copyWeak,
2461 llvm::Intrinsic::objc_copyWeak);
2462}
2463
2464void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2465 Address SrcAddr) {
2466 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2467 Object = EmitObjCConsumeObject(Ty, Object);
2468 EmitARCStoreWeak(DstAddr, Object, false);
2469}
2470
2471void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2472 Address SrcAddr) {
2473 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2474 Object = EmitObjCConsumeObject(Ty, Object);
2475 EmitARCStoreWeak(DstAddr, Object, false);
2476 EmitARCDestroyWeak(SrcAddr);
2477}
2478
2479/// Produce the code to do a objc_autoreleasepool_push.
2480/// call i8* \@objc_autoreleasePoolPush(void)
2481llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2482 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
2483 if (!fn) {
2484 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush);
2485 setARCRuntimeFunctionLinkage(CGM, fn);
2486 }
2487
2488 return EmitNounwindRuntimeCall(fn);
2489}
2490
2491/// Produce the code to do a primitive release.
2492/// call void \@objc_autoreleasePoolPop(i8* %ptr)
2493void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2494 assert(value->getType() == Int8PtrTy)((value->getType() == Int8PtrTy) ? static_cast<void>
(0) : __assert_fail ("value->getType() == Int8PtrTy", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 2494, __PRETTY_FUNCTION__))
;
2495
2496 if (getInvokeDest()) {
2497 // Call the runtime method not the intrinsic if we are handling exceptions
2498 llvm::FunctionCallee &fn =
2499 CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
2500 if (!fn) {
2501 llvm::FunctionType *fnType =
2502 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2503 fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2504 setARCRuntimeFunctionLinkage(CGM, fn);
2505 }
2506
2507 // objc_autoreleasePoolPop can throw.
2508 EmitRuntimeCallOrInvoke(fn, value);
2509 } else {
2510 llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
2511 if (!fn) {
2512 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop);
2513 setARCRuntimeFunctionLinkage(CGM, fn);
2514 }
2515
2516 EmitRuntimeCall(fn, value);
2517 }
2518}
2519
2520/// Produce the code to do an MRR version objc_autoreleasepool_push.
2521/// Which is: [[NSAutoreleasePool alloc] init];
2522/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2523/// init is declared as: - (id) init; in its NSObject super class.
2524///
2525llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2526 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2527 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
2528 // [NSAutoreleasePool alloc]
2529 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2530 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2531 CallArgList Args;
2532 RValue AllocRV =
2533 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2534 getContext().getObjCIdType(),
2535 AllocSel, Receiver, Args);
2536
2537 // [Receiver init]
2538 Receiver = AllocRV.getScalarVal();
2539 II = &CGM.getContext().Idents.get("init");
2540 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2541 RValue InitRV =
2542 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2543 getContext().getObjCIdType(),
2544 InitSel, Receiver, Args);
2545 return InitRV.getScalarVal();
2546}
2547
2548/// Allocate the given objc object.
2549/// call i8* \@objc_alloc(i8* %value)
2550llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2551 llvm::Type *resultType) {
2552 return emitObjCValueOperation(*this, value, resultType,
2553 CGM.getObjCEntrypoints().objc_alloc,
2554 "objc_alloc");
2555}
2556
2557/// Allocate the given objc object.
2558/// call i8* \@objc_allocWithZone(i8* %value)
2559llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2560 llvm::Type *resultType) {
2561 return emitObjCValueOperation(*this, value, resultType,
2562 CGM.getObjCEntrypoints().objc_allocWithZone,
2563 "objc_allocWithZone");
2564}
2565
2566llvm::Value *CodeGenFunction::EmitObjCAllocInit(llvm::Value *value,
2567 llvm::Type *resultType) {
2568 return emitObjCValueOperation(*this, value, resultType,
2569 CGM.getObjCEntrypoints().objc_alloc_init,
2570 "objc_alloc_init");
2571}
2572
2573/// Produce the code to do a primitive release.
2574/// [tmp drain];
2575void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2576 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2577 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2578 CallArgList Args;
2579 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2580 getContext().VoidTy, DrainSel, Arg, Args);
2581}
2582
2583void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2584 Address addr,
2585 QualType type) {
2586 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
2587}
2588
2589void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2590 Address addr,
2591 QualType type) {
2592 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
2593}
2594
2595void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2596 Address addr,
2597 QualType type) {
2598 CGF.EmitARCDestroyWeak(addr);
2599}
2600
2601void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2602 QualType type) {
2603 llvm::Value *value = CGF.Builder.CreateLoad(addr);
2604 CGF.EmitARCIntrinsicUse(value);
2605}
2606
2607/// Autorelease the given object.
2608/// call i8* \@objc_autorelease(i8* %value)
2609llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2610 llvm::Type *returnType) {
2611 return emitObjCValueOperation(
2612 *this, value, returnType,
2613 CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
2614 "objc_autorelease");
2615}
2616
2617/// Retain the given object, with normal retain semantics.
2618/// call i8* \@objc_retain(i8* %value)
2619llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2620 llvm::Type *returnType) {
2621 return emitObjCValueOperation(
2622 *this, value, returnType,
2623 CGM.getObjCEntrypoints().objc_retainRuntimeFunction, "objc_retain");
2624}
2625
2626/// Release the given object.
2627/// call void \@objc_release(i8* %value)
2628void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2629 ARCPreciseLifetime_t precise) {
2630 if (isa<llvm::ConstantPointerNull>(value)) return;
2631
2632 llvm::FunctionCallee &fn =
2633 CGM.getObjCEntrypoints().objc_releaseRuntimeFunction;
2634 if (!fn) {
2635 llvm::FunctionType *fnType =
2636 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2637 fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2638 setARCRuntimeFunctionLinkage(CGM, fn);
2639 // We have Native ARC, so set nonlazybind attribute for performance
2640 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2641 f->addFnAttr(llvm::Attribute::NonLazyBind);
2642 }
2643
2644 // Cast the argument to 'id'.
2645 value = Builder.CreateBitCast(value, Int8PtrTy);
2646
2647 // Call objc_release.
2648 llvm::CallBase *call = EmitCallOrInvoke(fn, value);
2649
2650 if (precise == ARCImpreciseLifetime) {
2651 call->setMetadata("clang.imprecise_release",
2652 llvm::MDNode::get(Builder.getContext(), None));
2653 }
2654}
2655
2656namespace {
2657 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
2658 llvm::Value *Token;
2659
2660 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2661
2662 void Emit(CodeGenFunction &CGF, Flags flags) override {
2663 CGF.EmitObjCAutoreleasePoolPop(Token);
2664 }
2665 };
2666 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
2667 llvm::Value *Token;
2668
2669 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2670
2671 void Emit(CodeGenFunction &CGF, Flags flags) override {
2672 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2673 }
2674 };
2675}
2676
2677void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2678 if (CGM.getLangOpts().ObjCAutoRefCount)
2679 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2680 else
2681 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2682}
2683
2684static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2685 switch (lifetime) {
2686 case Qualifiers::OCL_None:
2687 case Qualifiers::OCL_ExplicitNone:
2688 case Qualifiers::OCL_Strong:
2689 case Qualifiers::OCL_Autoreleasing:
2690 return true;
2691
2692 case Qualifiers::OCL_Weak:
2693 return false;
2694 }
2695
2696 llvm_unreachable("impossible lifetime!")::llvm::llvm_unreachable_internal("impossible lifetime!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 2696)
;
2697}
2698
2699static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2700 LValue lvalue,
2701 QualType type) {
2702 llvm::Value *result;
2703 bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2704 if (shouldRetain) {
2705 result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2706 } else {
2707 assert(type.getObjCLifetime() == Qualifiers::OCL_Weak)((type.getObjCLifetime() == Qualifiers::OCL_Weak) ? static_cast
<void> (0) : __assert_fail ("type.getObjCLifetime() == Qualifiers::OCL_Weak"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 2707, __PRETTY_FUNCTION__))
;
2708 result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress());
2709 }
2710 return TryEmitResult(result, !shouldRetain);
2711}
2712
2713static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2714 const Expr *e) {
2715 e = e->IgnoreParens();
2716 QualType type = e->getType();
2717
2718 // If we're loading retained from a __strong xvalue, we can avoid
2719 // an extra retain/release pair by zeroing out the source of this
2720 // "move" operation.
2721 if (e->isXValue() &&
2722 !type.isConstQualified() &&
2723 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2724 // Emit the lvalue.
2725 LValue lv = CGF.EmitLValue(e);
2726
2727 // Load the object pointer.
2728 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2729 SourceLocation()).getScalarVal();
2730
2731 // Set the source pointer to NULL.
2732 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2733
2734 return TryEmitResult(result, true);
2735 }
2736
2737 // As a very special optimization, in ARC++, if the l-value is the
2738 // result of a non-volatile assignment, do a simple retain of the
2739 // result of the call to objc_storeWeak instead of reloading.
2740 if (CGF.getLangOpts().CPlusPlus &&
2741 !type.isVolatileQualified() &&
2742 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2743 isa<BinaryOperator>(e) &&
2744 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2745 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2746
2747 // Try to emit code for scalar constant instead of emitting LValue and
2748 // loading it because we are not guaranteed to have an l-value. One of such
2749 // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2750 if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2751 auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2752 if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2753 return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2754 !shouldRetainObjCLifetime(type.getObjCLifetime()));
2755 }
2756
2757 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2758}
2759
2760typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2761 llvm::Value *value)>
2762 ValueTransform;
2763
2764/// Insert code immediately after a call.
2765static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2766 llvm::Value *value,
2767 ValueTransform doAfterCall,
2768 ValueTransform doFallback) {
2769 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2770 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2771
2772 // Place the retain immediately following the call.
2773 CGF.Builder.SetInsertPoint(call->getParent(),
2774 ++llvm::BasicBlock::iterator(call));
2775 value = doAfterCall(CGF, value);
2776
2777 CGF.Builder.restoreIP(ip);
2778 return value;
2779 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2780 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2781
2782 // Place the retain at the beginning of the normal destination block.
2783 llvm::BasicBlock *BB = invoke->getNormalDest();
2784 CGF.Builder.SetInsertPoint(BB, BB->begin());
2785 value = doAfterCall(CGF, value);
2786
2787 CGF.Builder.restoreIP(ip);
2788 return value;
2789
2790 // Bitcasts can arise because of related-result returns. Rewrite
2791 // the operand.
2792 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2793 llvm::Value *operand = bitcast->getOperand(0);
2794 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
2795 bitcast->setOperand(0, operand);
2796 return bitcast;
2797
2798 // Generic fall-back case.
2799 } else {
2800 // Retain using the non-block variant: we never need to do a copy
2801 // of a block that's been returned to us.
2802 return doFallback(CGF, value);
2803 }
2804}
2805
2806/// Given that the given expression is some sort of call (which does
2807/// not return retained), emit a retain following it.
2808static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2809 const Expr *e) {
2810 llvm::Value *value = CGF.EmitScalarExpr(e);
2811 return emitARCOperationAfterCall(CGF, value,
2812 [](CodeGenFunction &CGF, llvm::Value *value) {
2813 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2814 },
2815 [](CodeGenFunction &CGF, llvm::Value *value) {
2816 return CGF.EmitARCRetainNonBlock(value);
2817 });
2818}
2819
2820/// Given that the given expression is some sort of call (which does
2821/// not return retained), perform an unsafeClaim following it.
2822static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2823 const Expr *e) {
2824 llvm::Value *value = CGF.EmitScalarExpr(e);
2825 return emitARCOperationAfterCall(CGF, value,
2826 [](CodeGenFunction &CGF, llvm::Value *value) {
2827 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2828 },
2829 [](CodeGenFunction &CGF, llvm::Value *value) {
2830 return value;
2831 });
2832}
2833
2834llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2835 bool allowUnsafeClaim) {
2836 if (allowUnsafeClaim &&
2837 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2838 return emitARCUnsafeClaimCallResult(*this, E);
2839 } else {
2840 llvm::Value *value = emitARCRetainCallResult(*this, E);
2841 return EmitObjCConsumeObject(E->getType(), value);
2842 }
2843}
2844
2845/// Determine whether it might be important to emit a separate
2846/// objc_retain_block on the result of the given expression, or
2847/// whether it's okay to just emit it in a +1 context.
2848static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2849 assert(e->getType()->isBlockPointerType())((e->getType()->isBlockPointerType()) ? static_cast<
void> (0) : __assert_fail ("e->getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 2849, __PRETTY_FUNCTION__))
;
2850 e = e->IgnoreParens();
2851
2852 // For future goodness, emit block expressions directly in +1
2853 // contexts if we can.
2854 if (isa<BlockExpr>(e))
2855 return false;
2856
2857 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2858 switch (cast->getCastKind()) {
2859 // Emitting these operations in +1 contexts is goodness.
2860 case CK_LValueToRValue:
2861 case CK_ARCReclaimReturnedObject:
2862 case CK_ARCConsumeObject:
2863 case CK_ARCProduceObject:
2864 return false;
2865
2866 // These operations preserve a block type.
2867 case CK_NoOp:
2868 case CK_BitCast:
2869 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2870
2871 // These operations are known to be bad (or haven't been considered).
2872 case CK_AnyPointerToBlockPointerCast:
2873 default:
2874 return true;
2875 }
2876 }
2877
2878 return true;
2879}
2880
2881namespace {
2882/// A CRTP base class for emitting expressions of retainable object
2883/// pointer type in ARC.
2884template <typename Impl, typename Result> class ARCExprEmitter {
2885protected:
2886 CodeGenFunction &CGF;
2887 Impl &asImpl() { return *static_cast<Impl*>(this); }
2888
2889 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2890
2891public:
2892 Result visit(const Expr *e);
2893 Result visitCastExpr(const CastExpr *e);
2894 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
2895 Result visitBlockExpr(const BlockExpr *e);
2896 Result visitBinaryOperator(const BinaryOperator *e);
2897 Result visitBinAssign(const BinaryOperator *e);
2898 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2899 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2900 Result visitBinAssignWeak(const BinaryOperator *e);
2901 Result visitBinAssignStrong(const BinaryOperator *e);
2902
2903 // Minimal implementation:
2904 // Result visitLValueToRValue(const Expr *e)
2905 // Result visitConsumeObject(const Expr *e)
2906 // Result visitExtendBlockObject(const Expr *e)
2907 // Result visitReclaimReturnedObject(const Expr *e)
2908 // Result visitCall(const Expr *e)
2909 // Result visitExpr(const Expr *e)
2910 //
2911 // Result emitBitCast(Result result, llvm::Type *resultType)
2912 // llvm::Value *getValueOfResult(Result result)
2913};
2914}
2915
2916/// Try to emit a PseudoObjectExpr under special ARC rules.
2917///
2918/// This massively duplicates emitPseudoObjectRValue.
2919template <typename Impl, typename Result>
2920Result
2921ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
2922 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2923
2924 // Find the result expression.
2925 const Expr *resultExpr = E->getResultExpr();
2926 assert(resultExpr)((resultExpr) ? static_cast<void> (0) : __assert_fail (
"resultExpr", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 2926, __PRETTY_FUNCTION__))
;
2927 Result result;
2928
2929 for (PseudoObjectExpr::const_semantics_iterator
2930 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2931 const Expr *semantic = *i;
2932
2933 // If this semantic expression is an opaque value, bind it
2934 // to the result of its source expression.
2935 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2936 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2937 OVMA opaqueData;
2938
2939 // If this semantic is the result of the pseudo-object
2940 // expression, try to evaluate the source as +1.
2941 if (ov == resultExpr) {
2942 assert(!OVMA::shouldBindAsLValue(ov))((!OVMA::shouldBindAsLValue(ov)) ? static_cast<void> (0
) : __assert_fail ("!OVMA::shouldBindAsLValue(ov)", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 2942, __PRETTY_FUNCTION__))
;
2943 result = asImpl().visit(ov->getSourceExpr());
2944 opaqueData = OVMA::bind(CGF, ov,
2945 RValue::get(asImpl().getValueOfResult(result)));
2946
2947 // Otherwise, just bind it.
2948 } else {
2949 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2950 }
2951 opaques.push_back(opaqueData);
2952
2953 // Otherwise, if the expression is the result, evaluate it
2954 // and remember the result.
2955 } else if (semantic == resultExpr) {
2956 result = asImpl().visit(semantic);
2957
2958 // Otherwise, evaluate the expression in an ignored context.
2959 } else {
2960 CGF.EmitIgnoredExpr(semantic);
2961 }
2962 }
2963
2964 // Unbind all the opaques now.
2965 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2966 opaques[i].unbind(CGF);
2967
2968 return result;
2969}
2970
2971template <typename Impl, typename Result>
2972Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {
2973 // The default implementation just forwards the expression to visitExpr.
2974 return asImpl().visitExpr(e);
2975}
2976
2977template <typename Impl, typename Result>
2978Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2979 switch (e->getCastKind()) {
2980
2981 // No-op casts don't change the type, so we just ignore them.
2982 case CK_NoOp:
2983 return asImpl().visit(e->getSubExpr());
2984
2985 // These casts can change the type.
2986 case CK_CPointerToObjCPointerCast:
2987 case CK_BlockPointerToObjCPointerCast:
2988 case CK_AnyPointerToBlockPointerCast:
2989 case CK_BitCast: {
2990 llvm::Type *resultType = CGF.ConvertType(e->getType());
2991 assert(e->getSubExpr()->getType()->hasPointerRepresentation())((e->getSubExpr()->getType()->hasPointerRepresentation
()) ? static_cast<void> (0) : __assert_fail ("e->getSubExpr()->getType()->hasPointerRepresentation()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 2991, __PRETTY_FUNCTION__))
;
2992 Result result = asImpl().visit(e->getSubExpr());
2993 return asImpl().emitBitCast(result, resultType);
2994 }
2995
2996 // Handle some casts specially.
2997 case CK_LValueToRValue:
2998 return asImpl().visitLValueToRValue(e->getSubExpr());
2999 case CK_ARCConsumeObject:
3000 return asImpl().visitConsumeObject(e->getSubExpr());
3001 case CK_ARCExtendBlockObject:
3002 return asImpl().visitExtendBlockObject(e->getSubExpr());
3003 case CK_ARCReclaimReturnedObject:
3004 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
3005
3006 // Otherwise, use the default logic.
3007 default:
3008 return asImpl().visitExpr(e);
3009 }
3010}
3011
3012template <typename Impl, typename Result>
3013Result
3014ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
3015 switch (e->getOpcode()) {
3016 case BO_Comma:
3017 CGF.EmitIgnoredExpr(e->getLHS());
3018 CGF.EnsureInsertPoint();
3019 return asImpl().visit(e->getRHS());
3020
3021 case BO_Assign:
3022 return asImpl().visitBinAssign(e);
3023
3024 default:
3025 return asImpl().visitExpr(e);
3026 }
3027}
3028
3029template <typename Impl, typename Result>
3030Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3031 switch (e->getLHS()->getType().getObjCLifetime()) {
3032 case Qualifiers::OCL_ExplicitNone:
3033 return asImpl().visitBinAssignUnsafeUnretained(e);
3034
3035 case Qualifiers::OCL_Weak:
3036 return asImpl().visitBinAssignWeak(e);
3037
3038 case Qualifiers::OCL_Autoreleasing:
3039 return asImpl().visitBinAssignAutoreleasing(e);
3040
3041 case Qualifiers::OCL_Strong:
3042 return asImpl().visitBinAssignStrong(e);
3043
3044 case Qualifiers::OCL_None:
3045 return asImpl().visitExpr(e);
3046 }
3047 llvm_unreachable("bad ObjC ownership qualifier")::llvm::llvm_unreachable_internal("bad ObjC ownership qualifier"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 3047)
;
3048}
3049
3050/// The default rule for __unsafe_unretained emits the RHS recursively,
3051/// stores into the unsafe variable, and propagates the result outward.
3052template <typename Impl, typename Result>
3053Result ARCExprEmitter<Impl,Result>::
3054 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3055 // Recursively emit the RHS.
3056 // For __block safety, do this before emitting the LHS.
3057 Result result = asImpl().visit(e->getRHS());
3058
3059 // Perform the store.
3060 LValue lvalue =
3061 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
3062 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
3063 lvalue);
3064
3065 return result;
3066}
3067
3068template <typename Impl, typename Result>
3069Result
3070ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3071 return asImpl().visitExpr(e);
3072}
3073
3074template <typename Impl, typename Result>
3075Result
3076ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3077 return asImpl().visitExpr(e);
3078}
3079
3080template <typename Impl, typename Result>
3081Result
3082ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3083 return asImpl().visitExpr(e);
3084}
3085
3086/// The general expression-emission logic.
3087template <typename Impl, typename Result>
3088Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3089 // We should *never* see a nested full-expression here, because if
3090 // we fail to emit at +1, our caller must not retain after we close
3091 // out the full-expression. This isn't as important in the unsafe
3092 // emitter.
3093 assert(!isa<ExprWithCleanups>(e))((!isa<ExprWithCleanups>(e)) ? static_cast<void> (
0) : __assert_fail ("!isa<ExprWithCleanups>(e)", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 3093, __PRETTY_FUNCTION__))
;
3094
3095 // Look through parens, __extension__, generic selection, etc.
3096 e = e->IgnoreParens();
3097
3098 // Handle certain kinds of casts.
3099 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3100 return asImpl().visitCastExpr(ce);
3101
3102 // Handle the comma operator.
3103 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3104 return asImpl().visitBinaryOperator(op);
3105
3106 // TODO: handle conditional operators here
3107
3108 // For calls and message sends, use the retained-call logic.
3109 // Delegate inits are a special case in that they're the only
3110 // returns-retained expression that *isn't* surrounded by
3111 // a consume.
3112 } else if (isa<CallExpr>(e) ||
3113 (isa<ObjCMessageExpr>(e) &&
3114 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3115 return asImpl().visitCall(e);
3116
3117 // Look through pseudo-object expressions.
3118 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3119 return asImpl().visitPseudoObjectExpr(pseudo);
3120 } else if (auto *be = dyn_cast<BlockExpr>(e))
3121 return asImpl().visitBlockExpr(be);
3122
3123 return asImpl().visitExpr(e);
3124}
3125
3126namespace {
3127
3128/// An emitter for +1 results.
3129struct ARCRetainExprEmitter :
3130 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3131
3132 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3133
3134 llvm::Value *getValueOfResult(TryEmitResult result) {
3135 return result.getPointer();
3136 }
3137
3138 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3139 llvm::Value *value = result.getPointer();
3140 value = CGF.Builder.CreateBitCast(value, resultType);
3141 result.setPointer(value);
3142 return result;
3143 }
3144
3145 TryEmitResult visitLValueToRValue(const Expr *e) {
3146 return tryEmitARCRetainLoadOfScalar(CGF, e);
3147 }
3148
3149 /// For consumptions, just emit the subexpression and thus elide
3150 /// the retain/release pair.
3151 TryEmitResult visitConsumeObject(const Expr *e) {
3152 llvm::Value *result = CGF.EmitScalarExpr(e);
3153 return TryEmitResult(result, true);
3154 }
3155
3156 TryEmitResult visitBlockExpr(const BlockExpr *e) {
3157 TryEmitResult result = visitExpr(e);
3158 // Avoid the block-retain if this is a block literal that doesn't need to be
3159 // copied to the heap.
3160 if (e->getBlockDecl()->canAvoidCopyToHeap())
3161 result.setInt(true);
3162 return result;
3163 }
3164
3165 /// Block extends are net +0. Naively, we could just recurse on
3166 /// the subexpression, but actually we need to ensure that the
3167 /// value is copied as a block, so there's a little filter here.
3168 TryEmitResult visitExtendBlockObject(const Expr *e) {
3169 llvm::Value *result; // will be a +0 value
3170
3171 // If we can't safely assume the sub-expression will produce a
3172 // block-copied value, emit the sub-expression at +0.
3173 if (shouldEmitSeparateBlockRetain(e)) {
3174 result = CGF.EmitScalarExpr(e);
3175
3176 // Otherwise, try to emit the sub-expression at +1 recursively.
3177 } else {
3178 TryEmitResult subresult = asImpl().visit(e);
3179
3180 // If that produced a retained value, just use that.
3181 if (subresult.getInt()) {
3182 return subresult;
3183 }
3184
3185 // Otherwise it's +0.
3186 result = subresult.getPointer();
3187 }
3188
3189 // Retain the object as a block.
3190 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3191 return TryEmitResult(result, true);
3192 }
3193
3194 /// For reclaims, emit the subexpression as a retained call and
3195 /// skip the consumption.
3196 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3197 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3198 return TryEmitResult(result, true);
3199 }
3200
3201 /// When we have an undecorated call, retroactively do a claim.
3202 TryEmitResult visitCall(const Expr *e) {
3203 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3204 return TryEmitResult(result, true);
3205 }
3206
3207 // TODO: maybe special-case visitBinAssignWeak?
3208
3209 TryEmitResult visitExpr(const Expr *e) {
3210 // We didn't find an obvious production, so emit what we've got and
3211 // tell the caller that we didn't manage to retain.
3212 llvm::Value *result = CGF.EmitScalarExpr(e);
3213 return TryEmitResult(result, false);
3214 }
3215};
3216}
3217
3218static TryEmitResult
3219tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3220 return ARCRetainExprEmitter(CGF).visit(e);
3221}
3222
3223static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3224 LValue lvalue,
3225 QualType type) {
3226 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3227 llvm::Value *value = result.getPointer();
3228 if (!result.getInt())
3229 value = CGF.EmitARCRetain(type, value);
3230 return value;
3231}
3232
3233/// EmitARCRetainScalarExpr - Semantically equivalent to
3234/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3235/// best-effort attempt to peephole expressions that naturally produce
3236/// retained objects.
3237llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
3238 // The retain needs to happen within the full-expression.
3239 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3240 enterFullExpression(cleanups);
3241 RunCleanupsScope scope(*this);
3242 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3243 }
3244
3245 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3246 llvm::Value *value = result.getPointer();
3247 if (!result.getInt())
3248 value = EmitARCRetain(e->getType(), value);
3249 return value;
3250}
3251
3252llvm::Value *
3253CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
3254 // The retain needs to happen within the full-expression.
3255 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3256 enterFullExpression(cleanups);
3257 RunCleanupsScope scope(*this);
3258 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3259 }
3260
3261 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3262 llvm::Value *value = result.getPointer();
3263 if (result.getInt())
3264 value = EmitARCAutorelease(value);
3265 else
3266 value = EmitARCRetainAutorelease(e->getType(), value);
3267 return value;
3268}
3269
3270llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3271 llvm::Value *result;
3272 bool doRetain;
3273
3274 if (shouldEmitSeparateBlockRetain(e)) {
3275 result = EmitScalarExpr(e);
3276 doRetain = true;
3277 } else {
3278 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3279 result = subresult.getPointer();
3280 doRetain = !subresult.getInt();
3281 }
3282
3283 if (doRetain)
3284 result = EmitARCRetainBlock(result, /*mandatory*/ true);
3285 return EmitObjCConsumeObject(e->getType(), result);
3286}
3287
3288llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3289 // In ARC, retain and autorelease the expression.
3290 if (getLangOpts().ObjCAutoRefCount) {
3291 // Do so before running any cleanups for the full-expression.
3292 // EmitARCRetainAutoreleaseScalarExpr does this for us.
3293 return EmitARCRetainAutoreleaseScalarExpr(expr);
3294 }
3295
3296 // Otherwise, use the normal scalar-expression emission. The
3297 // exception machinery doesn't do anything special with the
3298 // exception like retaining it, so there's no safety associated with
3299 // only running cleanups after the throw has started, and when it
3300 // matters it tends to be substantially inferior code.
3301 return EmitScalarExpr(expr);
3302}
3303
3304namespace {
3305
3306/// An emitter for assigning into an __unsafe_unretained context.
3307struct ARCUnsafeUnretainedExprEmitter :
3308 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3309
3310 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3311
3312 llvm::Value *getValueOfResult(llvm::Value *value) {
3313 return value;
3314 }
3315
3316 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3317 return CGF.Builder.CreateBitCast(value, resultType);
3318 }
3319
3320 llvm::Value *visitLValueToRValue(const Expr *e) {
3321 return CGF.EmitScalarExpr(e);
3322 }
3323
3324 /// For consumptions, just emit the subexpression and perform the
3325 /// consumption like normal.
3326 llvm::Value *visitConsumeObject(const Expr *e) {
3327 llvm::Value *value = CGF.EmitScalarExpr(e);
3328 return CGF.EmitObjCConsumeObject(e->getType(), value);
3329 }
3330
3331 /// No special logic for block extensions. (This probably can't
3332 /// actually happen in this emitter, though.)
3333 llvm::Value *visitExtendBlockObject(const Expr *e) {
3334 return CGF.EmitARCExtendBlockObject(e);
3335 }
3336
3337 /// For reclaims, perform an unsafeClaim if that's enabled.
3338 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3339 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3340 }
3341
3342 /// When we have an undecorated call, just emit it without adding
3343 /// the unsafeClaim.
3344 llvm::Value *visitCall(const Expr *e) {
3345 return CGF.EmitScalarExpr(e);
3346 }
3347
3348 /// Just do normal scalar emission in the default case.
3349 llvm::Value *visitExpr(const Expr *e) {
3350 return CGF.EmitScalarExpr(e);
3351 }
3352};
3353}
3354
3355static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3356 const Expr *e) {
3357 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3358}
3359
3360/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3361/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3362/// avoiding any spurious retains, including by performing reclaims
3363/// with objc_unsafeClaimAutoreleasedReturnValue.
3364llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3365 // Look through full-expressions.
3366 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3367 enterFullExpression(cleanups);
3368 RunCleanupsScope scope(*this);
3369 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3370 }
3371
3372 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3373}
3374
3375std::pair<LValue,llvm::Value*>
3376CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3377 bool ignored) {
3378 // Evaluate the RHS first. If we're ignoring the result, assume
3379 // that we can emit at an unsafe +0.
3380 llvm::Value *value;
3381 if (ignored) {
3382 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3383 } else {
3384 value = EmitScalarExpr(e->getRHS());
3385 }
3386
3387 // Emit the LHS and perform the store.
3388 LValue lvalue = EmitLValue(e->getLHS());
3389 EmitStoreOfScalar(value, lvalue);
3390
3391 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3392}
3393
3394std::pair<LValue,llvm::Value*>
3395CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3396 bool ignored) {
3397 // Evaluate the RHS first.
3398 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3399 llvm::Value *value = result.getPointer();
3400
3401 bool hasImmediateRetain = result.getInt();
3402
3403 // If we didn't emit a retained object, and the l-value is of block
3404 // type, then we need to emit the block-retain immediately in case
3405 // it invalidates the l-value.
3406 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
3407 value = EmitARCRetainBlock(value, /*mandatory*/ false);
3408 hasImmediateRetain = true;
3409 }
3410
3411 LValue lvalue = EmitLValue(e->getLHS());
3412
3413 // If the RHS was emitted retained, expand this.
3414 if (hasImmediateRetain) {
3415 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
3416 EmitStoreOfScalar(value, lvalue);
3417 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
3418 } else {
3419 value = EmitARCStoreStrong(lvalue, value, ignored);
3420 }
3421
3422 return std::pair<LValue,llvm::Value*>(lvalue, value);
3423}
3424
3425std::pair<LValue,llvm::Value*>
3426CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3427 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3428 LValue lvalue = EmitLValue(e->getLHS());
3429
3430 EmitStoreOfScalar(value, lvalue);
3431
3432 return std::pair<LValue,llvm::Value*>(lvalue, value);
3433}
3434
3435void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
3436 const ObjCAutoreleasePoolStmt &ARPS) {
3437 const Stmt *subStmt = ARPS.getSubStmt();
3438 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3439
3440 CGDebugInfo *DI = getDebugInfo();
3441 if (DI)
3442 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
3443
3444 // Keep track of the current cleanup stack depth.
3445 RunCleanupsScope Scope(*this);
3446 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
3447 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3448 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3449 } else {
3450 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3451 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3452 }
3453
3454 for (const auto *I : S.body())
3455 EmitStmt(I);
3456
3457 if (DI)
3458 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
3459}
3460
3461/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3462/// make sure it survives garbage collection until this point.
3463void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3464 // We just use an inline assembly.
3465 llvm::FunctionType *extenderType
3466 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
3467 llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,
3468 /* assembly */ "",
3469 /* constraints */ "r",
3470 /* side effects */ true);
3471
3472 object = Builder.CreateBitCast(object, VoidPtrTy);
3473 EmitNounwindRuntimeCall(extender, object);
3474}
3475
3476/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
3477/// non-trivial copy assignment function, produce following helper function.
3478/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3479///
3480llvm::Constant *
3481CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3482 const ObjCPropertyImplDecl *PID) {
3483 if (!getLangOpts().CPlusPlus ||
3484 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
3485 return nullptr;
3486 QualType Ty = PID->getPropertyIvarDecl()->getType();
3487 if (!Ty->isRecordType())
3488 return nullptr;
3489 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3490 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
3491 return nullptr;
3492 llvm::Constant *HelperFn = nullptr;
3493 if (hasTrivialSetExpr(PID))
3494 return nullptr;
3495 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null")((PID->getSetterCXXAssignment() && "SetterCXXAssignment - null"
) ? static_cast<void> (0) : __assert_fail ("PID->getSetterCXXAssignment() && \"SetterCXXAssignment - null\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 3495, __PRETTY_FUNCTION__))
;
3496 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3497 return HelperFn;
3498
3499 ASTContext &C = getContext();
3500 IdentifierInfo *II
3501 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
3502
3503 QualType ReturnTy = C.VoidTy;
3504 QualType DestTy = C.getPointerType(Ty);
3505 QualType SrcTy = Ty;
3506 SrcTy.addConst();
3507 SrcTy = C.getPointerType(SrcTy);
3508
3509 SmallVector<QualType, 2> ArgTys;
3510 ArgTys.push_back(DestTy);
3511 ArgTys.push_back(SrcTy);
3512 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3513
3514 FunctionDecl *FD = FunctionDecl::Create(
3515 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3516 FunctionTy, nullptr, SC_Static, false, false);
3517
3518 FunctionArgList args;
3519 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3520 ImplicitParamDecl::Other);
3521 args.push_back(&DstDecl);
3522 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3523 ImplicitParamDecl::Other);
3524 args.push_back(&SrcDecl);
3525
3526 const CGFunctionInfo &FI =
3527 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
3528
3529 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3530
3531 llvm::Function *Fn =
3532 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
3533 "__assign_helper_atomic_property_",
3534 &CGM.getModule());
3535
3536 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
3537
3538 StartFunction(FD, ReturnTy, Fn, FI, args);
3539
3540 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3541 SourceLocation());
3542 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
3543 VK_LValue, OK_Ordinary, SourceLocation(), false);
3544
3545 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3546 SourceLocation());
3547 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3548 VK_LValue, OK_Ordinary, SourceLocation(), false);
3549
3550 Expr *Args[2] = { &DST, &SRC };
3551 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
3552 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3553 C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3554 VK_LValue, SourceLocation(), FPOptions());
3555
3556 EmitStmt(TheCall);
3557
3558 FinishFunction();
3559 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3560 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
3561 return HelperFn;
3562}
3563
3564llvm::Constant *
3565CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3566 const ObjCPropertyImplDecl *PID) {
3567 if (!getLangOpts().CPlusPlus ||
3568 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
3569 return nullptr;
3570 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3571 QualType Ty = PD->getType();
3572 if (!Ty->isRecordType())
3573 return nullptr;
3574 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
3575 return nullptr;
3576 llvm::Constant *HelperFn = nullptr;
3577 if (hasTrivialGetExpr(PID))
3578 return nullptr;
3579 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null")((PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null"
) ? static_cast<void> (0) : __assert_fail ("PID->getGetterCXXConstructor() && \"getGetterCXXConstructor - null\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 3579, __PRETTY_FUNCTION__))
;
3580 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3581 return HelperFn;
3582
3583 ASTContext &C = getContext();
3584 IdentifierInfo *II =
3585 &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
3586
3587 QualType ReturnTy = C.VoidTy;
3588 QualType DestTy = C.getPointerType(Ty);
3589 QualType SrcTy = Ty;
3590 SrcTy.addConst();
3591 SrcTy = C.getPointerType(SrcTy);
3592
3593 SmallVector<QualType, 2> ArgTys;
3594 ArgTys.push_back(DestTy);
3595 ArgTys.push_back(SrcTy);
3596 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3597
3598 FunctionDecl *FD = FunctionDecl::Create(
3599 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3600 FunctionTy, nullptr, SC_Static, false, false);
3601
3602 FunctionArgList args;
3603 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3604 ImplicitParamDecl::Other);
3605 args.push_back(&DstDecl);
3606 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3607 ImplicitParamDecl::Other);
3608 args.push_back(&SrcDecl);
3609
3610 const CGFunctionInfo &FI =
3611 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
3612
3613 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3614
3615 llvm::Function *Fn = llvm::Function::Create(
3616 LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3617 &CGM.getModule());
3618
3619 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
3620
3621 StartFunction(FD, ReturnTy, Fn, FI, args);
3622
3623 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3624 SourceLocation());
3625
3626 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3627 VK_LValue, OK_Ordinary, SourceLocation(), false);
3628
3629 CXXConstructExpr *CXXConstExpr =
3630 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3631
3632 SmallVector<Expr*, 4> ConstructorArgs;
3633 ConstructorArgs.push_back(&SRC);
3634 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3635 CXXConstExpr->arg_end());
3636
3637 CXXConstructExpr *TheCXXConstructExpr =
3638 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3639 CXXConstExpr->getConstructor(),
3640 CXXConstExpr->isElidable(),
3641 ConstructorArgs,
3642 CXXConstExpr->hadMultipleCandidates(),
3643 CXXConstExpr->isListInitialization(),
3644 CXXConstExpr->isStdInitListInitialization(),
3645 CXXConstExpr->requiresZeroInitialization(),
3646 CXXConstExpr->getConstructionKind(),
3647 SourceRange());
3648
3649 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3650 SourceLocation());
3651
3652 RValue DV = EmitAnyExpr(&DstExpr);
3653 CharUnits Alignment
3654 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
3655 EmitAggExpr(TheCXXConstructExpr,
3656 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3657 Qualifiers(),
3658 AggValueSlot::IsDestructed,
3659 AggValueSlot::DoesNotNeedGCBarriers,
3660 AggValueSlot::IsNotAliased,
3661 AggValueSlot::DoesNotOverlap));
3662
3663 FinishFunction();
3664 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3665 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3666 return HelperFn;
3667}
3668
3669llvm::Value *
3670CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3671 // Get selectors for retain/autorelease.
3672 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3673 Selector CopySelector =
3674 getContext().Selectors.getNullarySelector(CopyID);
3675 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3676 Selector AutoreleaseSelector =
3677 getContext().Selectors.getNullarySelector(AutoreleaseID);
3678
3679 // Emit calls to retain/autorelease.
3680 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3681 llvm::Value *Val = Block;
3682 RValue Result;
3683 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3684 Ty, CopySelector,
3685 Val, CallArgList(), nullptr, nullptr);
3686 Val = Result.getScalarVal();
3687 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3688 Ty, AutoreleaseSelector,
3689 Val, CallArgList(), nullptr, nullptr);
3690 Val = Result.getScalarVal();
3691 return Val;
3692}
3693
3694llvm::Value *
3695CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3696 assert(Args.size() == 3 && "Expected 3 argument here!")((Args.size() == 3 && "Expected 3 argument here!") ? static_cast
<void> (0) : __assert_fail ("Args.size() == 3 && \"Expected 3 argument here!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjC.cpp"
, 3696, __PRETTY_FUNCTION__))
;
3697
3698 if (!CGM.IsOSVersionAtLeastFn) {
3699 llvm::FunctionType *FTy =
3700 llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3701 CGM.IsOSVersionAtLeastFn =
3702 CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3703 }
3704
3705 llvm::Value *CallRes =
3706 EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3707
3708 return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3709}
3710
3711void CodeGenModule::emitAtAvailableLinkGuard() {
3712 if (!IsOSVersionAtLeastFn)
3713 return;
3714 // @available requires CoreFoundation only on Darwin.
3715 if (!Target.getTriple().isOSDarwin())
3716 return;
3717 // Add -framework CoreFoundation to the linker commands. We still want to
3718 // emit the core foundation reference down below because otherwise if
3719 // CoreFoundation is not used in the code, the linker won't link the
3720 // framework.
3721 auto &Context = getLLVMContext();
3722 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3723 llvm::MDString::get(Context, "CoreFoundation")};
3724 LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3725 // Emit a reference to a symbol from CoreFoundation to ensure that
3726 // CoreFoundation is linked into the final binary.
3727 llvm::FunctionType *FTy =
3728 llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
3729 llvm::FunctionCallee CFFunc =
3730 CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3731
3732 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
3733 llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
3734 CheckFTy, "__clang_at_available_requires_core_foundation_framework",
3735 llvm::AttributeList(), /*Local=*/true);
3736 llvm::Function *CFLinkCheckFunc =
3737 cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
3738 if (CFLinkCheckFunc->empty()) {
3739 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3740 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3741 CodeGenFunction CGF(*this);
3742 CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3743 CGF.EmitNounwindRuntimeCall(CFFunc,
3744 llvm::Constant::getNullValue(VoidPtrTy));
3745 CGF.Builder.CreateUnreachable();
3746 addCompilerUsedGlobal(CFLinkCheckFunc);
3747 }
3748}
3749
3750CGObjCRuntime::~CGObjCRuntime() {}

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Basic/ObjCRuntime.h

1//===- ObjCRuntime.h - Objective-C Runtime Configuration --------*- 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/// \file
10/// Defines types useful for describing an Objective-C runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_BASIC_OBJCRUNTIME_H
15#define LLVM_CLANG_BASIC_OBJCRUNTIME_H
16
17#include "clang/Basic/LLVM.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/Triple.h"
20#include "llvm/Support/ErrorHandling.h"
21#include "llvm/Support/VersionTuple.h"
22#include <string>
23
24namespace clang {
25
26/// The basic abstraction for the target Objective-C runtime.
27class ObjCRuntime {
28public:
29 /// The basic Objective-C runtimes that we know about.
30 enum Kind {
31 /// 'macosx' is the Apple-provided NeXT-derived runtime on Mac OS
32 /// X platforms that use the non-fragile ABI; the version is a
33 /// release of that OS.
34 MacOSX,
35
36 /// 'macosx-fragile' is the Apple-provided NeXT-derived runtime on
37 /// Mac OS X platforms that use the fragile ABI; the version is a
38 /// release of that OS.
39 FragileMacOSX,
40
41 /// 'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS
42 /// simulator; it is always non-fragile. The version is a release
43 /// version of iOS.
44 iOS,
45
46 /// 'watchos' is a variant of iOS for Apple's watchOS. The version
47 /// is a release version of watchOS.
48 WatchOS,
49
50 /// 'gcc' is the Objective-C runtime shipped with GCC, implementing a
51 /// fragile Objective-C ABI
52 GCC,
53
54 /// 'gnustep' is the modern non-fragile GNUstep runtime.
55 GNUstep,
56
57 /// 'objfw' is the Objective-C runtime included in ObjFW
58 ObjFW
59 };
60
61private:
62 Kind TheKind = MacOSX;
63 VersionTuple Version;
64
65public:
66 /// A bogus initialization of the runtime.
67 ObjCRuntime() = default;
68 ObjCRuntime(Kind kind, const VersionTuple &version)
69 : TheKind(kind), Version(version) {}
70
71 void set(Kind kind, VersionTuple version) {
72 TheKind = kind;
73 Version = version;
74 }
75
76 Kind getKind() const { return TheKind; }
77 const VersionTuple &getVersion() const { return Version; }
78
79 /// Does this runtime follow the set of implied behaviors for a
80 /// "non-fragile" ABI?
81 bool isNonFragile() const {
82 switch (getKind()) {
83 case FragileMacOSX: return false;
84 case GCC: return false;
85 case MacOSX: return true;
86 case GNUstep: return true;
87 case ObjFW: return true;
88 case iOS: return true;
89 case WatchOS: return true;
90 }
91 llvm_unreachable("bad kind")::llvm::llvm_unreachable_internal("bad kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Basic/ObjCRuntime.h"
, 91)
;
92 }
93
94 /// The inverse of isNonFragile(): does this runtime follow the set of
95 /// implied behaviors for a "fragile" ABI?
96 bool isFragile() const { return !isNonFragile(); }
97
98 /// The default dispatch mechanism to use for the specified architecture
99 bool isLegacyDispatchDefaultForArch(llvm::Triple::ArchType Arch) {
100 // The GNUstep runtime uses a newer dispatch method by default from
101 // version 1.6 onwards
102 if (getKind() == GNUstep && getVersion() >= VersionTuple(1, 6)) {
103 if (Arch == llvm::Triple::arm ||
104 Arch == llvm::Triple::x86 ||
105 Arch == llvm::Triple::x86_64)
106 return false;
107 }
108 else if ((getKind() == MacOSX) && isNonFragile() &&
109 (getVersion() >= VersionTuple(10, 0)) &&
110 (getVersion() < VersionTuple(10, 6)))
111 return Arch != llvm::Triple::x86_64;
112 // Except for deployment target of 10.5 or less,
113 // Mac runtimes use legacy dispatch everywhere now.
114 return true;
115 }
116
117 /// Is this runtime basically of the GNU family of runtimes?
118 bool isGNUFamily() const {
119 switch (getKind()) {
120 case FragileMacOSX:
121 case MacOSX:
122 case iOS:
123 case WatchOS:
124 return false;
125 case GCC:
126 case GNUstep:
127 case ObjFW:
128 return true;
129 }
130 llvm_unreachable("bad kind")::llvm::llvm_unreachable_internal("bad kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Basic/ObjCRuntime.h"
, 130)
;
131 }
132
133 /// Is this runtime basically of the NeXT family of runtimes?
134 bool isNeXTFamily() const {
135 // For now, this is just the inverse of isGNUFamily(), but that's
136 // not inherently true.
137 return !isGNUFamily();
138 }
139
140 /// Does this runtime allow ARC at all?
141 bool allowsARC() const {
142 switch (getKind()) {
143 case FragileMacOSX:
144 // No stub library for the fragile runtime.
145 return getVersion() >= VersionTuple(10, 7);
146 case MacOSX: return true;
147 case iOS: return true;
148 case WatchOS: return true;
149 case GCC: return false;
150 case GNUstep: return true;
151 case ObjFW: return true;
152 }
153 llvm_unreachable("bad kind")::llvm::llvm_unreachable_internal("bad kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Basic/ObjCRuntime.h"
, 153)
;
154 }
155
156 /// Does this runtime natively provide the ARC entrypoints?
157 ///
158 /// ARC cannot be directly supported on a platform that does not provide
159 /// these entrypoints, although it may be supportable via a stub
160 /// library.
161 bool hasNativeARC() const {
162 switch (getKind()) {
163 case FragileMacOSX: return getVersion() >= VersionTuple(10, 7);
164 case MacOSX: return getVersion() >= VersionTuple(10, 7);
165 case iOS: return getVersion() >= VersionTuple(5);
166 case WatchOS: return true;
167
168 case GCC: return false;
169 case GNUstep: return getVersion() >= VersionTuple(1, 6);
170 case ObjFW: return true;
171 }
172 llvm_unreachable("bad kind")::llvm::llvm_unreachable_internal("bad kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Basic/ObjCRuntime.h"
, 172)
;
173 }
174
175 /// Does this runtime provide ARC entrypoints that are likely to be faster
176 /// than an ordinary message send of the appropriate selector?
177 ///
178 /// The ARC entrypoints are guaranteed to be equivalent to just sending the
179 /// corresponding message. If the entrypoint is implemented naively as just a
180 /// message send, using it is a trade-off: it sacrifices a few cycles of
181 /// overhead to save a small amount of code. However, it's possible for
182 /// runtimes to detect and special-case classes that use "standard"
183 /// retain/release behavior; if that's dynamically a large proportion of all
184 /// retained objects, using the entrypoint will also be faster than using a
185 /// message send.
186 ///
187 /// When this method returns true, Clang will turn non-super message sends of
188 /// certain selectors into calls to the correspond entrypoint:
189 /// retain => objc_retain
190 /// release => objc_release
191 /// autorelease => objc_autorelease
192 bool shouldUseARCFunctionsForRetainRelease() const {
193 switch (getKind()) {
194 case FragileMacOSX:
195 return false;
196 case MacOSX:
197 return getVersion() >= VersionTuple(10, 10);
198 case iOS:
199 return getVersion() >= VersionTuple(8);
200 case WatchOS:
201 return true;
202 case GCC:
203 return false;
204 case GNUstep:
205 return false;
206 case ObjFW:
207 return false;
208 }
209 llvm_unreachable("bad kind")::llvm::llvm_unreachable_internal("bad kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Basic/ObjCRuntime.h"
, 209)
;
210 }
211
212 /// Does this runtime provide entrypoints that are likely to be faster
213 /// than an ordinary message send of the "alloc" selector?
214 ///
215 /// The "alloc" entrypoint is guaranteed to be equivalent to just sending the
216 /// corresponding message. If the entrypoint is implemented naively as just a
217 /// message send, using it is a trade-off: it sacrifices a few cycles of
218 /// overhead to save a small amount of code. However, it's possible for
219 /// runtimes to detect and special-case classes that use "standard"
220 /// alloc behavior; if that's dynamically a large proportion of all
221 /// objects, using the entrypoint will also be faster than using a message
222 /// send.
223 ///
224 /// When this method returns true, Clang will turn non-super message sends of
225 /// certain selectors into calls to the corresponding entrypoint:
226 /// alloc => objc_alloc
227 /// allocWithZone:nil => objc_allocWithZone
228 bool shouldUseRuntimeFunctionsForAlloc() const {
229 switch (getKind()) {
230 case FragileMacOSX:
231 return false;
232 case MacOSX:
233 return getVersion() >= VersionTuple(10, 10);
234 case iOS:
235 return getVersion() >= VersionTuple(8);
236 case WatchOS:
237 return true;
238
239 case GCC:
240 return false;
241 case GNUstep:
242 return false;
243 case ObjFW:
244 return false;
245 }
246 llvm_unreachable("bad kind")::llvm::llvm_unreachable_internal("bad kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Basic/ObjCRuntime.h"
, 246)
;
247 }
248
249 /// Does this runtime provide the objc_alloc_init entrypoint? This can apply
250 /// the same optimization as objc_alloc, but also sends an -init message,
251 /// reducing code size on the caller.
252 bool shouldUseRuntimeFunctionForCombinedAllocInit() const {
253 switch (getKind()) {
3
Control jumps to 'case WatchOS:' at line 258
254 case MacOSX:
255 return getVersion() >= VersionTuple(10, 14, 4);
256 case iOS:
257 return getVersion() >= VersionTuple(12, 2);
258 case WatchOS:
259 return getVersion() >= VersionTuple(5, 2);
4
Calling 'operator>='
18
Returning from 'operator>='
19
Returning the value 1, which participates in a condition later
260 default:
261 return false;
262 }
263 }
264
265 /// Does this runtime supports optimized setter entrypoints?
266 bool hasOptimizedSetter() const {
267 switch (getKind()) {
268 case MacOSX:
269 return getVersion() >= VersionTuple(10, 8);
270 case iOS:
271 return (getVersion() >= VersionTuple(6));
272 case WatchOS:
273 return true;
274 case GNUstep:
275 return getVersion() >= VersionTuple(1, 7);
276 default:
277 return false;
278 }
279 }
280
281 /// Does this runtime allow the use of __weak?
282 bool allowsWeak() const {
283 return hasNativeWeak();
284 }
285
286 /// Does this runtime natively provide ARC-compliant 'weak'
287 /// entrypoints?
288 bool hasNativeWeak() const {
289 // Right now, this is always equivalent to whether the runtime
290 // natively supports ARC decision.
291 return hasNativeARC();
292 }
293
294 /// Does this runtime directly support the subscripting methods?
295 ///
296 /// This is really a property of the library, not the runtime.
297 bool hasSubscripting() const {
298 switch (getKind()) {
299 case FragileMacOSX: return false;
300 case MacOSX: return getVersion() >= VersionTuple(10, 11);
301 case iOS: return getVersion() >= VersionTuple(9);
302 case WatchOS: return true;
303
304 // This is really a lie, because some implementations and versions
305 // of the runtime do not support ARC. Probably -fgnu-runtime
306 // should imply a "maximal" runtime or something?
307 case GCC: return true;
308 case GNUstep: return true;
309 case ObjFW: return true;
310 }
311 llvm_unreachable("bad kind")::llvm::llvm_unreachable_internal("bad kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Basic/ObjCRuntime.h"
, 311)
;
312 }
313
314 /// Does this runtime allow sizeof or alignof on object types?
315 bool allowsSizeofAlignof() const {
316 return isFragile();
317 }
318
319 /// Does this runtime allow pointer arithmetic on objects?
320 ///
321 /// This covers +, -, ++, --, and (if isSubscriptPointerArithmetic()
322 /// yields true) [].
323 bool allowsPointerArithmetic() const {
324 switch (getKind()) {
325 case FragileMacOSX:
326 case GCC:
327 return true;
328 case MacOSX:
329 case iOS:
330 case WatchOS:
331 case GNUstep:
332 case ObjFW:
333 return false;
334 }
335 llvm_unreachable("bad kind")::llvm::llvm_unreachable_internal("bad kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Basic/ObjCRuntime.h"
, 335)
;
336 }
337
338 /// Is subscripting pointer arithmetic?
339 bool isSubscriptPointerArithmetic() const {
340 return allowsPointerArithmetic();
341 }
342
343 /// Does this runtime provide an objc_terminate function?
344 ///
345 /// This is used in handlers for exceptions during the unwind process;
346 /// without it, abort() must be used in pure ObjC files.
347 bool hasTerminate() const {
348 switch (getKind()) {
349 case FragileMacOSX: return getVersion() >= VersionTuple(10, 8);
350 case MacOSX: return getVersion() >= VersionTuple(10, 8);
351 case iOS: return getVersion() >= VersionTuple(5);
352 case WatchOS: return true;
353 case GCC: return false;
354 case GNUstep: return false;
355 case ObjFW: return false;
356 }
357 llvm_unreachable("bad kind")::llvm::llvm_unreachable_internal("bad kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Basic/ObjCRuntime.h"
, 357)
;
358 }
359
360 /// Does this runtime support weakly importing classes?
361 bool hasWeakClassImport() const {
362 switch (getKind()) {
363 case MacOSX: return true;
364 case iOS: return true;
365 case WatchOS: return true;
366 case FragileMacOSX: return false;
367 case GCC: return true;
368 case GNUstep: return true;
369 case ObjFW: return true;
370 }
371 llvm_unreachable("bad kind")::llvm::llvm_unreachable_internal("bad kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Basic/ObjCRuntime.h"
, 371)
;
372 }
373
374 /// Does this runtime use zero-cost exceptions?
375 bool hasUnwindExceptions() const {
376 switch (getKind()) {
377 case MacOSX: return true;
378 case iOS: return true;
379 case WatchOS: return true;
380 case FragileMacOSX: return false;
381 case GCC: return true;
382 case GNUstep: return true;
383 case ObjFW: return true;
384 }
385 llvm_unreachable("bad kind")::llvm::llvm_unreachable_internal("bad kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Basic/ObjCRuntime.h"
, 385)
;
386 }
387
388 bool hasAtomicCopyHelper() const {
389 switch (getKind()) {
390 case FragileMacOSX:
391 case MacOSX:
392 case iOS:
393 case WatchOS:
394 return true;
395 case GNUstep:
396 return getVersion() >= VersionTuple(1, 7);
397 default: return false;
398 }
399 }
400
401 /// Is objc_unsafeClaimAutoreleasedReturnValue available?
402 bool hasARCUnsafeClaimAutoreleasedReturnValue() const {
403 switch (getKind()) {
404 case MacOSX:
405 case FragileMacOSX:
406 return getVersion() >= VersionTuple(10, 11);
407 case iOS:
408 return getVersion() >= VersionTuple(9);
409 case WatchOS:
410 return getVersion() >= VersionTuple(2);
411 case GNUstep:
412 return false;
413 default:
414 return false;
415 }
416 }
417
418 /// Are the empty collection symbols available?
419 bool hasEmptyCollections() const {
420 switch (getKind()) {
421 default:
422 return false;
423 case MacOSX:
424 return getVersion() >= VersionTuple(10, 11);
425 case iOS:
426 return getVersion() >= VersionTuple(9);
427 case WatchOS:
428 return getVersion() >= VersionTuple(2);
429 }
430 }
431
432 /// Returns true if this Objective-C runtime supports Objective-C class
433 /// stubs.
434 bool allowsClassStubs() const {
435 switch (getKind()) {
436 case FragileMacOSX:
437 case GCC:
438 case GNUstep:
439 case ObjFW:
440 return false;
441 case MacOSX:
442 case iOS:
443 case WatchOS:
444 return true;
445 }
446 llvm_unreachable("bad kind")::llvm::llvm_unreachable_internal("bad kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Basic/ObjCRuntime.h"
, 446)
;
447 }
448
449 /// Try to parse an Objective-C runtime specification from the given
450 /// string.
451 ///
452 /// \return true on error.
453 bool tryParse(StringRef input);
454
455 std::string getAsString() const;
456
457 friend bool operator==(const ObjCRuntime &left, const ObjCRuntime &right) {
458 return left.getKind() == right.getKind() &&
459 left.getVersion() == right.getVersion();
460 }
461
462 friend bool operator!=(const ObjCRuntime &left, const ObjCRuntime &right) {
463 return !(left == right);
464 }
465};
466
467raw_ostream &operator<<(raw_ostream &out, const ObjCRuntime &value);
468
469} // namespace clang
470
471#endif // LLVM_CLANG_BASIC_OBJCRUNTIME_H

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Support/VersionTuple.h

1//===- VersionTuple.h - Version Number Handling -----------------*- 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/// \file
10/// Defines the llvm::VersionTuple class, which represents a version in
11/// the form major[.minor[.subminor]].
12///
13//===----------------------------------------------------------------------===//
14#ifndef LLVM_SUPPORT_VERSIONTUPLE_H
15#define LLVM_SUPPORT_VERSIONTUPLE_H
16
17#include "llvm/ADT/Optional.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/Support/raw_ostream.h"
20#include <string>
21#include <tuple>
22
23namespace llvm {
24
25/// Represents a version number in the form major[.minor[.subminor[.build]]].
26class VersionTuple {
27 unsigned Major : 32;
28
29 unsigned Minor : 31;
30 unsigned HasMinor : 1;
31
32 unsigned Subminor : 31;
33 unsigned HasSubminor : 1;
34
35 unsigned Build : 31;
36 unsigned HasBuild : 1;
37
38public:
39 VersionTuple()
40 : Major(0), Minor(0), HasMinor(false), Subminor(0), HasSubminor(false),
41 Build(0), HasBuild(false) {}
42
43 explicit VersionTuple(unsigned Major)
44 : Major(Major), Minor(0), HasMinor(false), Subminor(0),
45 HasSubminor(false), Build(0), HasBuild(false) {}
46
47 explicit VersionTuple(unsigned Major, unsigned Minor)
48 : Major(Major), Minor(Minor), HasMinor(true), Subminor(0),
49 HasSubminor(false), Build(0), HasBuild(false) {}
50
51 explicit VersionTuple(unsigned Major, unsigned Minor, unsigned Subminor)
52 : Major(Major), Minor(Minor), HasMinor(true), Subminor(Subminor),
53 HasSubminor(true), Build(0), HasBuild(false) {}
54
55 explicit VersionTuple(unsigned Major, unsigned Minor, unsigned Subminor,
56 unsigned Build)
57 : Major(Major), Minor(Minor), HasMinor(true), Subminor(Subminor),
58 HasSubminor(true), Build(Build), HasBuild(true) {}
59
60 /// Determine whether this version information is empty
61 /// (e.g., all version components are zero).
62 bool empty() const {
63 return Major == 0 && Minor == 0 && Subminor == 0 && Build == 0;
64 }
65
66 /// Retrieve the major version number.
67 unsigned getMajor() const { return Major; }
68
69 /// Retrieve the minor version number, if provided.
70 Optional<unsigned> getMinor() const {
71 if (!HasMinor)
72 return None;
73 return Minor;
74 }
75
76 /// Retrieve the subminor version number, if provided.
77 Optional<unsigned> getSubminor() const {
78 if (!HasSubminor)
79 return None;
80 return Subminor;
81 }
82
83 /// Retrieve the build version number, if provided.
84 Optional<unsigned> getBuild() const {
85 if (!HasBuild)
86 return None;
87 return Build;
88 }
89
90 /// Determine if two version numbers are equivalent. If not
91 /// provided, minor and subminor version numbers are considered to be zero.
92 friend bool operator==(const VersionTuple &X, const VersionTuple &Y) {
93 return X.Major == Y.Major && X.Minor == Y.Minor &&
94 X.Subminor == Y.Subminor && X.Build == Y.Build;
95 }
96
97 /// Determine if two version numbers are not equivalent.
98 ///
99 /// If not provided, minor and subminor version numbers are considered to be
100 /// zero.
101 friend bool operator!=(const VersionTuple &X, const VersionTuple &Y) {
102 return !(X == Y);
103 }
104
105 /// Determine whether one version number precedes another.
106 ///
107 /// If not provided, minor and subminor version numbers are considered to be
108 /// zero.
109 friend bool operator<(const VersionTuple &X, const VersionTuple &Y) {
110 return std::tie(X.Major, X.Minor, X.Subminor, X.Build) <
6
Calling 'operator<<const unsigned int &, const unsigned int &, const unsigned int &, const unsigned int &, const unsigned int &, const unsigned int &, const unsigned int &, const unsigned int &>'
13
Returning from 'operator<<const unsigned int &, const unsigned int &, const unsigned int &, const unsigned int &, const unsigned int &, const unsigned int &, const unsigned int &, const unsigned int &>'
14
Returning value, which participates in a condition later
111 std::tie(Y.Major, Y.Minor, Y.Subminor, Y.Build);
112 }
113
114 /// Determine whether one version number follows another.
115 ///
116 /// If not provided, minor and subminor version numbers are considered to be
117 /// zero.
118 friend bool operator>(const VersionTuple &X, const VersionTuple &Y) {
119 return Y < X;
120 }
121
122 /// Determine whether one version number precedes or is
123 /// equivalent to another.
124 ///
125 /// If not provided, minor and subminor version numbers are considered to be
126 /// zero.
127 friend bool operator<=(const VersionTuple &X, const VersionTuple &Y) {
128 return !(Y < X);
129 }
130
131 /// Determine whether one version number follows or is
132 /// equivalent to another.
133 ///
134 /// If not provided, minor and subminor version numbers are considered to be
135 /// zero.
136 friend bool operator>=(const VersionTuple &X, const VersionTuple &Y) {
137 return !(X < Y);
5
Calling 'operator<'
15
Returning from 'operator<'
16
Assuming the condition is true
17
Returning the value 1, which participates in a condition later
138 }
139
140 /// Retrieve a string representation of the version number.
141 std::string getAsString() const;
142
143 /// Try to parse the given string as a version number.
144 /// \returns \c true if the string does not match the regular expression
145 /// [0-9]+(\.[0-9]+){0,3}
146 bool tryParse(StringRef string);
147};
148
149/// Print a version number.
150raw_ostream &operator<<(raw_ostream &Out, const VersionTuple &V);
151
152} // end namespace llvm
153#endif // LLVM_SUPPORT_VERSIONTUPLE_H

/usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/tuple

1// <tuple> -*- C++ -*-
2
3// Copyright (C) 2007-2016 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 include/tuple
26 * This is a Standard C++ Library header.
27 */
28
29#ifndef _GLIBCXX_TUPLE1
30#define _GLIBCXX_TUPLE1 1
31
32#pragma GCC system_header
33
34#if __cplusplus201402L < 201103L
35# include <bits/c++0x_warning.h>
36#else
37
38#include <utility>
39#include <array>
40#include <bits/uses_allocator.h>
41
42namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
43{
44_GLIBCXX_BEGIN_NAMESPACE_VERSION
45
46 /**
47 * @addtogroup utilities
48 * @{
49 */
50
51 template<std::size_t _Idx, typename _Head, bool _IsEmptyNotFinal>
52 struct _Head_base;
53
54 template<std::size_t _Idx, typename _Head>
55 struct _Head_base<_Idx, _Head, true>
56 : public _Head
57 {
58 constexpr _Head_base()
59 : _Head() { }
60
61 constexpr _Head_base(const _Head& __h)
62 : _Head(__h) { }
63
64 constexpr _Head_base(const _Head_base&) = default;
65 constexpr _Head_base(_Head_base&&) = default;
66
67 template<typename _UHead>
68 constexpr _Head_base(_UHead&& __h)
69 : _Head(std::forward<_UHead>(__h)) { }
70
71 _Head_base(allocator_arg_t, __uses_alloc0)
72 : _Head() { }
73
74 template<typename _Alloc>
75 _Head_base(allocator_arg_t, __uses_alloc1<_Alloc> __a)
76 : _Head(allocator_arg, *__a._M_a) { }
77
78 template<typename _Alloc>
79 _Head_base(allocator_arg_t, __uses_alloc2<_Alloc> __a)
80 : _Head(*__a._M_a) { }
81
82 template<typename _UHead>
83 _Head_base(__uses_alloc0, _UHead&& __uhead)
84 : _Head(std::forward<_UHead>(__uhead)) { }
85
86 template<typename _Alloc, typename _UHead>
87 _Head_base(__uses_alloc1<_Alloc> __a, _UHead&& __uhead)
88 : _Head(allocator_arg, *__a._M_a, std::forward<_UHead>(__uhead)) { }
89
90 template<typename _Alloc, typename _UHead>
91 _Head_base(__uses_alloc2<_Alloc> __a, _UHead&& __uhead)
92 : _Head(std::forward<_UHead>(__uhead), *__a._M_a) { }
93
94 static constexpr _Head&
95 _M_head(_Head_base& __b) noexcept { return __b; }
96
97 static constexpr const _Head&
98 _M_head(const _Head_base& __b) noexcept { return __b; }
99 };
100
101 template<std::size_t _Idx, typename _Head>
102 struct _Head_base<_Idx, _Head, false>
103 {
104 constexpr _Head_base()
105 : _M_head_impl() { }
106
107 constexpr _Head_base(const _Head& __h)
108 : _M_head_impl(__h) { }
109
110 constexpr _Head_base(const _Head_base&) = default;
111 constexpr _Head_base(_Head_base&&) = default;
112
113 template<typename _UHead>
114 constexpr _Head_base(_UHead&& __h)
115 : _M_head_impl(std::forward<_UHead>(__h)) { }
116
117 _Head_base(allocator_arg_t, __uses_alloc0)
118 : _M_head_impl() { }
119
120 template<typename _Alloc>
121 _Head_base(allocator_arg_t, __uses_alloc1<_Alloc> __a)
122 : _M_head_impl(allocator_arg, *__a._M_a) { }
123
124 template<typename _Alloc>
125 _Head_base(allocator_arg_t, __uses_alloc2<_Alloc> __a)
126 : _M_head_impl(*__a._M_a) { }
127
128 template<typename _UHead>
129 _Head_base(__uses_alloc0, _UHead&& __uhead)
130 : _M_head_impl(std::forward<_UHead>(__uhead)) { }
131
132 template<typename _Alloc, typename _UHead>
133 _Head_base(__uses_alloc1<_Alloc> __a, _UHead&& __uhead)
134 : _M_head_impl(allocator_arg, *__a._M_a, std::forward<_UHead>(__uhead))
135 { }
136
137 template<typename _Alloc, typename _UHead>
138 _Head_base(__uses_alloc2<_Alloc> __a, _UHead&& __uhead)
139 : _M_head_impl(std::forward<_UHead>(__uhead), *__a._M_a) { }
140
141 static constexpr _Head&
142 _M_head(_Head_base& __b) noexcept { return __b._M_head_impl; }
143
144 static constexpr const _Head&
145 _M_head(const _Head_base& __b) noexcept { return __b._M_head_impl; }
146
147 _Head _M_head_impl;
148 };
149
150 /**
151 * Contains the actual implementation of the @c tuple template, stored
152 * as a recursive inheritance hierarchy from the first element (most
153 * derived class) to the last (least derived class). The @c Idx
154 * parameter gives the 0-based index of the element stored at this
155 * point in the hierarchy; we use it to implement a constant-time
156 * get() operation.
157 */
158 template<std::size_t _Idx, typename... _Elements>
159 struct _Tuple_impl;
160
161 template<typename _Tp>
162 struct __is_empty_non_tuple : is_empty<_Tp> { };
163
164 // Using EBO for elements that are tuples causes ambiguous base errors.
165 template<typename _El0, typename... _El>
166 struct __is_empty_non_tuple<tuple<_El0, _El...>> : false_type { };
167
168 // Use the Empty Base-class Optimization for empty, non-final types.
169 template<typename _Tp>
170 using __empty_not_final
171 = typename conditional<__is_final(_Tp), false_type,
172 __is_empty_non_tuple<_Tp>>::type;
173
174 /**
175 * Recursive tuple implementation. Here we store the @c Head element
176 * and derive from a @c Tuple_impl containing the remaining elements
177 * (which contains the @c Tail).
178 */
179 template<std::size_t _Idx, typename _Head, typename... _Tail>
180 struct _Tuple_impl<_Idx, _Head, _Tail...>
181 : public _Tuple_impl<_Idx + 1, _Tail...>,
182 private _Head_base<_Idx, _Head, __empty_not_final<_Head>::value>
183 {
184 template<std::size_t, typename...> friend class _Tuple_impl;
185
186 typedef _Tuple_impl<_Idx + 1, _Tail...> _Inherited;
187 typedef _Head_base<_Idx, _Head, __empty_not_final<_Head>::value> _Base;
188
189 static constexpr _Head&
190 _M_head(_Tuple_impl& __t) noexcept { return _Base::_M_head(__t); }
191
192 static constexpr const _Head&
193 _M_head(const _Tuple_impl& __t) noexcept { return _Base::_M_head(__t); }
194
195 static constexpr _Inherited&
196 _M_tail(_Tuple_impl& __t) noexcept { return __t; }
197
198 static constexpr const _Inherited&
199 _M_tail(const _Tuple_impl& __t) noexcept { return __t; }
200
201 constexpr _Tuple_impl()
202 : _Inherited(), _Base() { }
203
204 explicit
205 constexpr _Tuple_impl(const _Head& __head, const _Tail&... __tail)
206 : _Inherited(__tail...), _Base(__head) { }
207
208 template<typename _UHead, typename... _UTail, typename = typename
209 enable_if<sizeof...(_Tail) == sizeof...(_UTail)>::type>
210 explicit
211 constexpr _Tuple_impl(_UHead&& __head, _UTail&&... __tail)
212 : _Inherited(std::forward<_UTail>(__tail)...),
213 _Base(std::forward<_UHead>(__head)) { }
214
215 constexpr _Tuple_impl(const _Tuple_impl&) = default;
216
217 constexpr
218 _Tuple_impl(_Tuple_impl&& __in)
219 noexcept(__and_<is_nothrow_move_constructible<_Head>,
220 is_nothrow_move_constructible<_Inherited>>::value)
221 : _Inherited(std::move(_M_tail(__in))),
222 _Base(std::forward<_Head>(_M_head(__in))) { }
223
224 template<typename... _UElements>
225 constexpr _Tuple_impl(const _Tuple_impl<_Idx, _UElements...>& __in)
226 : _Inherited(_Tuple_impl<_Idx, _UElements...>::_M_tail(__in)),
227 _Base(_Tuple_impl<_Idx, _UElements...>::_M_head(__in)) { }
228
229 template<typename _UHead, typename... _UTails>
230 constexpr _Tuple_impl(_Tuple_impl<_Idx, _UHead, _UTails...>&& __in)
231 : _Inherited(std::move
232 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_tail(__in))),
233 _Base(std::forward<_UHead>
234 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_head(__in))) { }
235
236 template<typename _Alloc>
237 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a)
238 : _Inherited(__tag, __a),
239 _Base(__tag, __use_alloc<_Head>(__a)) { }
240
241 template<typename _Alloc>
242 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
243 const _Head& __head, const _Tail&... __tail)
244 : _Inherited(__tag, __a, __tail...),
245 _Base(__use_alloc<_Head, _Alloc, _Head>(__a), __head) { }
246
247 template<typename _Alloc, typename _UHead, typename... _UTail,
248 typename = typename enable_if<sizeof...(_Tail)
249 == sizeof...(_UTail)>::type>
250 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
251 _UHead&& __head, _UTail&&... __tail)
252 : _Inherited(__tag, __a, std::forward<_UTail>(__tail)...),
253 _Base(__use_alloc<_Head, _Alloc, _UHead>(__a),
254 std::forward<_UHead>(__head)) { }
255
256 template<typename _Alloc>
257 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
258 const _Tuple_impl& __in)
259 : _Inherited(__tag, __a, _M_tail(__in)),
260 _Base(__use_alloc<_Head, _Alloc, _Head>(__a), _M_head(__in)) { }
261
262 template<typename _Alloc>
263 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
264 _Tuple_impl&& __in)
265 : _Inherited(__tag, __a, std::move(_M_tail(__in))),
266 _Base(__use_alloc<_Head, _Alloc, _Head>(__a),
267 std::forward<_Head>(_M_head(__in))) { }
268
269 template<typename _Alloc, typename... _UElements>
270 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
271 const _Tuple_impl<_Idx, _UElements...>& __in)
272 : _Inherited(__tag, __a,
273 _Tuple_impl<_Idx, _UElements...>::_M_tail(__in)),
274 _Base(__use_alloc<_Head, _Alloc, _Head>(__a),
275 _Tuple_impl<_Idx, _UElements...>::_M_head(__in)) { }
276
277 template<typename _Alloc, typename _UHead, typename... _UTails>
278 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
279 _Tuple_impl<_Idx, _UHead, _UTails...>&& __in)
280 : _Inherited(__tag, __a, std::move
281 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_tail(__in))),
282 _Base(__use_alloc<_Head, _Alloc, _UHead>(__a),
283 std::forward<_UHead>
284 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_head(__in))) { }
285
286 _Tuple_impl&
287 operator=(const _Tuple_impl& __in)
288 {
289 _M_head(*this) = _M_head(__in);
290 _M_tail(*this) = _M_tail(__in);
291 return *this;
292 }
293
294 _Tuple_impl&
295 operator=(_Tuple_impl&& __in)
296 noexcept(__and_<is_nothrow_move_assignable<_Head>,
297 is_nothrow_move_assignable<_Inherited>>::value)
298 {
299 _M_head(*this) = std::forward<_Head>(_M_head(__in));
300 _M_tail(*this) = std::move(_M_tail(__in));
301 return *this;
302 }
303
304 template<typename... _UElements>
305 _Tuple_impl&
306 operator=(const _Tuple_impl<_Idx, _UElements...>& __in)
307 {
308 _M_head(*this) = _Tuple_impl<_Idx, _UElements...>::_M_head(__in);
309 _M_tail(*this) = _Tuple_impl<_Idx, _UElements...>::_M_tail(__in);
310 return *this;
311 }
312
313 template<typename _UHead, typename... _UTails>
314 _Tuple_impl&
315 operator=(_Tuple_impl<_Idx, _UHead, _UTails...>&& __in)
316 {
317 _M_head(*this) = std::forward<_UHead>
318 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_head(__in));
319 _M_tail(*this) = std::move
320 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_tail(__in));
321 return *this;
322 }
323
324 protected:
325 void
326 _M_swap(_Tuple_impl& __in)
327 noexcept(__is_nothrow_swappable<_Head>::value
328 && noexcept(_M_tail(__in)._M_swap(_M_tail(__in))))
329 {
330 using std::swap;
331 swap(_M_head(*this), _M_head(__in));
332 _Inherited::_M_swap(_M_tail(__in));
333 }
334 };
335
336 // Basis case of inheritance recursion.
337 template<std::size_t _Idx, typename _Head>
338 struct _Tuple_impl<_Idx, _Head>
339 : private _Head_base<_Idx, _Head, __empty_not_final<_Head>::value>
340 {
341 template<std::size_t, typename...> friend class _Tuple_impl;
342
343 typedef _Head_base<_Idx, _Head, __empty_not_final<_Head>::value> _Base;
344
345 static constexpr _Head&
346 _M_head(_Tuple_impl& __t) noexcept { return _Base::_M_head(__t); }
347
348 static constexpr const _Head&
349 _M_head(const _Tuple_impl& __t) noexcept { return _Base::_M_head(__t); }
350
351 constexpr _Tuple_impl()
352 : _Base() { }
353
354 explicit
355 constexpr _Tuple_impl(const _Head& __head)
356 : _Base(__head) { }
357
358 template<typename _UHead>
359 explicit
360 constexpr _Tuple_impl(_UHead&& __head)
361 : _Base(std::forward<_UHead>(__head)) { }
362
363 constexpr _Tuple_impl(const _Tuple_impl&) = default;
364
365 constexpr
366 _Tuple_impl(_Tuple_impl&& __in)
367 noexcept(is_nothrow_move_constructible<_Head>::value)
368 : _Base(std::forward<_Head>(_M_head(__in))) { }
369
370 template<typename _UHead>
371 constexpr _Tuple_impl(const _Tuple_impl<_Idx, _UHead>& __in)
372 : _Base(_Tuple_impl<_Idx, _UHead>::_M_head(__in)) { }
373
374 template<typename _UHead>
375 constexpr _Tuple_impl(_Tuple_impl<_Idx, _UHead>&& __in)
376 : _Base(std::forward<_UHead>(_Tuple_impl<_Idx, _UHead>::_M_head(__in)))
377 { }
378
379 template<typename _Alloc>
380 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a)
381 : _Base(__tag, __use_alloc<_Head>(__a)) { }
382
383 template<typename _Alloc>
384 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
385 const _Head& __head)
386 : _Base(__use_alloc<_Head, _Alloc, _Head>(__a), __head) { }
387
388 template<typename _Alloc, typename _UHead>
389 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
390 _UHead&& __head)
391 : _Base(__use_alloc<_Head, _Alloc, _UHead>(__a),
392 std::forward<_UHead>(__head)) { }
393
394 template<typename _Alloc>
395 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
396 const _Tuple_impl& __in)
397 : _Base(__use_alloc<_Head, _Alloc, _Head>(__a), _M_head(__in)) { }
398
399 template<typename _Alloc>
400 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
401 _Tuple_impl&& __in)
402 : _Base(__use_alloc<_Head, _Alloc, _Head>(__a),
403 std::forward<_Head>(_M_head(__in))) { }
404
405 template<typename _Alloc, typename _UHead>
406 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
407 const _Tuple_impl<_Idx, _UHead>& __in)
408 : _Base(__use_alloc<_Head, _Alloc, _Head>(__a),
409 _Tuple_impl<_Idx, _UHead>::_M_head(__in)) { }
410
411 template<typename _Alloc, typename _UHead>
412 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
413 _Tuple_impl<_Idx, _UHead>&& __in)
414 : _Base(__use_alloc<_Head, _Alloc, _UHead>(__a),
415 std::forward<_UHead>(_Tuple_impl<_Idx, _UHead>::_M_head(__in)))
416 { }
417
418 _Tuple_impl&
419 operator=(const _Tuple_impl& __in)
420 {
421 _M_head(*this) = _M_head(__in);
422 return *this;
423 }
424
425 _Tuple_impl&
426 operator=(_Tuple_impl&& __in)
427 noexcept(is_nothrow_move_assignable<_Head>::value)
428 {
429 _M_head(*this) = std::forward<_Head>(_M_head(__in));
430 return *this;
431 }
432
433 template<typename _UHead>
434 _Tuple_impl&
435 operator=(const _Tuple_impl<_Idx, _UHead>& __in)
436 {
437 _M_head(*this) = _Tuple_impl<_Idx, _UHead>::_M_head(__in);
438 return *this;
439 }
440
441 template<typename _UHead>
442 _Tuple_impl&
443 operator=(_Tuple_impl<_Idx, _UHead>&& __in)
444 {
445 _M_head(*this)
446 = std::forward<_UHead>(_Tuple_impl<_Idx, _UHead>::_M_head(__in));
447 return *this;
448 }
449
450 protected:
451 void
452 _M_swap(_Tuple_impl& __in)
453 noexcept(__is_nothrow_swappable<_Head>::value)
454 {
455 using std::swap;
456 swap(_M_head(*this), _M_head(__in));
457 }
458 };
459
460 template<typename... _Elements>
461 class tuple;
462
463 // Concept utility functions, reused in conditionally-explicit
464 // constructors.
465 template<bool, typename... _Elements>
466 struct _TC
467 {
468 template<typename... _UElements>
469 static constexpr bool _ConstructibleTuple()
470 {
471 return __and_<is_constructible<_Elements, const _UElements&>...>::value;
472 }
473
474 template<typename... _UElements>
475 static constexpr bool _ImplicitlyConvertibleTuple()
476 {
477 return __and_<is_convertible<const _UElements&, _Elements>...>::value;
478 }
479
480 template<typename... _UElements>
481 static constexpr bool _MoveConstructibleTuple()
482 {
483 return __and_<is_constructible<_Elements, _UElements&&>...>::value;
484 }
485
486 template<typename... _UElements>
487 static constexpr bool _ImplicitlyMoveConvertibleTuple()
488 {
489 return __and_<is_convertible<_UElements&&, _Elements>...>::value;
490 }
491
492 template<typename _SrcTuple>
493 static constexpr bool _NonNestedTuple()
494 {
495 return __and_<__not_<is_same<tuple<_Elements...>,
496 typename remove_cv<
497 typename remove_reference<_SrcTuple>::type
498 >::type>>,
499 __not_<is_convertible<_SrcTuple, _Elements...>>,
500 __not_<is_constructible<_Elements..., _SrcTuple>>
501 >::value;
502 }
503 template<typename... _UElements>
504 static constexpr bool _NotSameTuple()
505 {
506 return __not_<is_same<tuple<_Elements...>,
507 typename remove_const<
508 typename remove_reference<_UElements...>::type
509 >::type>>::value;
510 }
511 };
512
513 template<typename... _Elements>
514 struct _TC<false, _Elements...>
515 {
516 template<typename... _UElements>
517 static constexpr bool _ConstructibleTuple()
518 {
519 return false;
520 }
521
522 template<typename... _UElements>
523 static constexpr bool _ImplicitlyConvertibleTuple()
524 {
525 return false;
526 }
527
528 template<typename... _UElements>
529 static constexpr bool _MoveConstructibleTuple()
530 {
531 return false;
532 }
533
534 template<typename... _UElements>
535 static constexpr bool _ImplicitlyMoveConvertibleTuple()
536 {
537 return false;
538 }
539
540 template<typename... _UElements>
541 static constexpr bool _NonNestedTuple()
542 {
543 return true;
544 }
545 template<typename... _UElements>
546 static constexpr bool _NotSameTuple()
547 {
548 return true;
549 }
550 };
551
552 /// Primary class template, tuple
553 template<typename... _Elements>
554 class tuple : public _Tuple_impl<0, _Elements...>
555 {
556 typedef _Tuple_impl<0, _Elements...> _Inherited;
557
558 // Used for constraining the default constructor so
559 // that it becomes dependent on the constraints.
560 template<typename _Dummy>
561 struct _TC2
562 {
563 static constexpr bool _DefaultConstructibleTuple()
564 {
565 return __and_<is_default_constructible<_Elements>...>::value;
566 }
567 static constexpr bool _ImplicitlyDefaultConstructibleTuple()
568 {
569 return __and_<__is_implicitly_default_constructible<_Elements>...>
570 ::value;
571 }
572 };
573
574 public:
575 template<typename _Dummy = void,
576 typename enable_if<_TC2<_Dummy>::
577 _ImplicitlyDefaultConstructibleTuple(),
578 bool>::type = true>
579 constexpr tuple()
580 : _Inherited() { }
581
582 template<typename _Dummy = void,
583 typename enable_if<_TC2<_Dummy>::
584 _DefaultConstructibleTuple()
585 &&
586 !_TC2<_Dummy>::
587 _ImplicitlyDefaultConstructibleTuple(),
588 bool>::type = false>
589 explicit constexpr tuple()
590 : _Inherited() { }
591
592 // Shortcut for the cases where constructors taking _Elements...
593 // need to be constrained.
594 template<typename _Dummy> using _TCC =
595 _TC<is_same<_Dummy, void>::value,
596 _Elements...>;
597
598 template<typename _Dummy = void,
599 typename enable_if<
600 _TCC<_Dummy>::template
601 _ConstructibleTuple<_Elements...>()
602 && _TCC<_Dummy>::template
603 _ImplicitlyConvertibleTuple<_Elements...>()
604 && (sizeof...(_Elements) >= 1),
605 bool>::type=true>
606 constexpr tuple(const _Elements&... __elements)
607 : _Inherited(__elements...) { }
608
609 template<typename _Dummy = void,
610 typename enable_if<
611 _TCC<_Dummy>::template
612 _ConstructibleTuple<_Elements...>()
613 && !_TCC<_Dummy>::template
614 _ImplicitlyConvertibleTuple<_Elements...>()
615 && (sizeof...(_Elements) >= 1),
616 bool>::type=false>
617 explicit constexpr tuple(const _Elements&... __elements)
618 : _Inherited(__elements...) { }
619
620 // Shortcut for the cases where constructors taking _UElements...
621 // need to be constrained.
622 template<typename... _UElements> using _TMC =
623 _TC<(sizeof...(_Elements) == sizeof...(_UElements)),
624 _Elements...>;
625
626 template<typename... _UElements, typename
627 enable_if<
628 _TC<sizeof...(_UElements) == 1, _Elements...>::template
629 _NotSameTuple<_UElements...>()
630 && _TMC<_UElements...>::template
631 _MoveConstructibleTuple<_UElements...>()
632 && _TMC<_UElements...>::template
633 _ImplicitlyMoveConvertibleTuple<_UElements...>()
634 && (sizeof...(_Elements) >= 1),
635 bool>::type=true>
636 constexpr tuple(_UElements&&... __elements)
637 : _Inherited(std::forward<_UElements>(__elements)...) { }
638
639 template<typename... _UElements, typename
640 enable_if<
641 _TC<sizeof...(_UElements) == 1, _Elements...>::template
642 _NotSameTuple<_UElements...>()
643 && _TMC<_UElements...>::template
644 _MoveConstructibleTuple<_UElements...>()
645 && !_TMC<_UElements...>::template
646 _ImplicitlyMoveConvertibleTuple<_UElements...>()
647 && (sizeof...(_Elements) >= 1),
648 bool>::type=false>
649 explicit constexpr tuple(_UElements&&... __elements)
650 : _Inherited(std::forward<_UElements>(__elements)...) { }
651
652 constexpr tuple(const tuple&) = default;
653
654 constexpr tuple(tuple&&) = default;
655
656 // Shortcut for the cases where constructors taking tuples
657 // must avoid creating temporaries.
658 template<typename _Dummy> using _TNTC =
659 _TC<is_same<_Dummy, void>::value && sizeof...(_Elements) == 1,
660 _Elements...>;
661
662 template<typename... _UElements, typename _Dummy = void, typename
663 enable_if<_TMC<_UElements...>::template
664 _ConstructibleTuple<_UElements...>()
665 && _TMC<_UElements...>::template
666 _ImplicitlyConvertibleTuple<_UElements...>()
667 && _TNTC<_Dummy>::template
668 _NonNestedTuple<const tuple<_UElements...>&>(),
669 bool>::type=true>
670 constexpr tuple(const tuple<_UElements...>& __in)
671 : _Inherited(static_cast<const _Tuple_impl<0, _UElements...>&>(__in))
672 { }
673
674 template<typename... _UElements, typename _Dummy = void, typename
675 enable_if<_TMC<_UElements...>::template
676 _ConstructibleTuple<_UElements...>()
677 && !_TMC<_UElements...>::template
678 _ImplicitlyConvertibleTuple<_UElements...>()
679 && _TNTC<_Dummy>::template
680 _NonNestedTuple<const tuple<_UElements...>&>(),
681 bool>::type=false>
682 explicit constexpr tuple(const tuple<_UElements...>& __in)
683 : _Inherited(static_cast<const _Tuple_impl<0, _UElements...>&>(__in))
684 { }
685
686 template<typename... _UElements, typename _Dummy = void, typename
687 enable_if<_TMC<_UElements...>::template
688 _MoveConstructibleTuple<_UElements...>()
689 && _TMC<_UElements...>::template
690 _ImplicitlyMoveConvertibleTuple<_UElements...>()
691 && _TNTC<_Dummy>::template
692 _NonNestedTuple<tuple<_UElements...>&&>(),
693 bool>::type=true>
694 constexpr tuple(tuple<_UElements...>&& __in)
695 : _Inherited(static_cast<_Tuple_impl<0, _UElements...>&&>(__in)) { }
696
697 template<typename... _UElements, typename _Dummy = void, typename
698 enable_if<_TMC<_UElements...>::template
699 _MoveConstructibleTuple<_UElements...>()
700 && !_TMC<_UElements...>::template
701 _ImplicitlyMoveConvertibleTuple<_UElements...>()
702 && _TNTC<_Dummy>::template
703 _NonNestedTuple<tuple<_UElements...>&&>(),
704 bool>::type=false>
705 explicit constexpr tuple(tuple<_UElements...>&& __in)
706 : _Inherited(static_cast<_Tuple_impl<0, _UElements...>&&>(__in)) { }
707
708 // Allocator-extended constructors.
709
710 template<typename _Alloc>
711 tuple(allocator_arg_t __tag, const _Alloc& __a)
712 : _Inherited(__tag, __a) { }
713
714 template<typename _Alloc, typename _Dummy = void,
715 typename enable_if<
716 _TCC<_Dummy>::template
717 _ConstructibleTuple<_Elements...>()
718 && _TCC<_Dummy>::template
719 _ImplicitlyConvertibleTuple<_Elements...>(),
720 bool>::type=true>
721 tuple(allocator_arg_t __tag, const _Alloc& __a,
722 const _Elements&... __elements)
723 : _Inherited(__tag, __a, __elements...) { }
724
725 template<typename _Alloc, typename _Dummy = void,
726 typename enable_if<
727 _TCC<_Dummy>::template
728 _ConstructibleTuple<_Elements...>()
729 && !_TCC<_Dummy>::template
730 _ImplicitlyConvertibleTuple<_Elements...>(),
731 bool>::type=false>
732 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
733 const _Elements&... __elements)
734 : _Inherited(__tag, __a, __elements...) { }
735
736 template<typename _Alloc, typename... _UElements, typename
737 enable_if<_TMC<_UElements...>::template
738 _MoveConstructibleTuple<_UElements...>()
739 && _TMC<_UElements...>::template
740 _ImplicitlyMoveConvertibleTuple<_UElements...>(),
741 bool>::type=true>
742 tuple(allocator_arg_t __tag, const _Alloc& __a,
743 _UElements&&... __elements)
744 : _Inherited(__tag, __a, std::forward<_UElements>(__elements)...)
745 { }
746
747 template<typename _Alloc, typename... _UElements, typename
748 enable_if<_TMC<_UElements...>::template
749 _MoveConstructibleTuple<_UElements...>()
750 && !_TMC<_UElements...>::template
751 _ImplicitlyMoveConvertibleTuple<_UElements...>(),
752 bool>::type=false>
753 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
754 _UElements&&... __elements)
755 : _Inherited(__tag, __a, std::forward<_UElements>(__elements)...)
756 { }
757
758 template<typename _Alloc>
759 tuple(allocator_arg_t __tag, const _Alloc& __a, const tuple& __in)
760 : _Inherited(__tag, __a, static_cast<const _Inherited&>(__in)) { }
761
762 template<typename _Alloc>
763 tuple(allocator_arg_t __tag, const _Alloc& __a, tuple&& __in)
764 : _Inherited(__tag, __a, static_cast<_Inherited&&>(__in)) { }
765
766 template<typename _Alloc, typename... _UElements, typename
767 enable_if<_TMC<_UElements...>::template
768 _ConstructibleTuple<_UElements...>()
769 && _TMC<_UElements...>::template
770 _ImplicitlyConvertibleTuple<_UElements...>(),
771 bool>::type=true>
772 tuple(allocator_arg_t __tag, const _Alloc& __a,
773 const tuple<_UElements...>& __in)
774 : _Inherited(__tag, __a,
775 static_cast<const _Tuple_impl<0, _UElements...>&>(__in))
776 { }
777
778 template<typename _Alloc, typename... _UElements, typename
779 enable_if<_TMC<_UElements...>::template
780 _ConstructibleTuple<_UElements...>()
781 && !_TMC<_UElements...>::template
782 _ImplicitlyConvertibleTuple<_UElements...>(),
783 bool>::type=false>
784 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
785 const tuple<_UElements...>& __in)
786 : _Inherited(__tag, __a,
787 static_cast<const _Tuple_impl<0, _UElements...>&>(__in))
788 { }
789
790 template<typename _Alloc, typename... _UElements, typename
791 enable_if<_TMC<_UElements...>::template
792 _MoveConstructibleTuple<_UElements...>()
793 && _TMC<_UElements...>::template
794 _ImplicitlyMoveConvertibleTuple<_UElements...>(),
795 bool>::type=true>
796 tuple(allocator_arg_t __tag, const _Alloc& __a,
797 tuple<_UElements...>&& __in)
798 : _Inherited(__tag, __a,
799 static_cast<_Tuple_impl<0, _UElements...>&&>(__in))
800 { }
801
802 template<typename _Alloc, typename... _UElements, typename
803 enable_if<_TMC<_UElements...>::template
804 _MoveConstructibleTuple<_UElements...>()
805 && !_TMC<_UElements...>::template
806 _ImplicitlyMoveConvertibleTuple<_UElements...>(),
807 bool>::type=false>
808 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
809 tuple<_UElements...>&& __in)
810 : _Inherited(__tag, __a,
811 static_cast<_Tuple_impl<0, _UElements...>&&>(__in))
812 { }
813
814 tuple&
815 operator=(const tuple& __in)
816 {
817 static_cast<_Inherited&>(*this) = __in;
818 return *this;
819 }
820
821 tuple&
822 operator=(tuple&& __in)
823 noexcept(is_nothrow_move_assignable<_Inherited>::value)
824 {
825 static_cast<_Inherited&>(*this) = std::move(__in);
826 return *this;
827 }
828
829 template<typename... _UElements, typename = typename
830 enable_if<sizeof...(_UElements)
831 == sizeof...(_Elements)>::type>
832 tuple&
833 operator=(const tuple<_UElements...>& __in)
834 {
835 static_cast<_Inherited&>(*this) = __in;
836 return *this;
837 }
838
839 template<typename... _UElements, typename = typename
840 enable_if<sizeof...(_UElements)
841 == sizeof...(_Elements)>::type>
842 tuple&
843 operator=(tuple<_UElements...>&& __in)
844 {
845 static_cast<_Inherited&>(*this) = std::move(__in);
846 return *this;
847 }
848
849 void
850 swap(tuple& __in)
851 noexcept(noexcept(__in._M_swap(__in)))
852 { _Inherited::_M_swap(__in); }
853 };
854
855 // Explicit specialization, zero-element tuple.
856 template<>
857 class tuple<>
858 {
859 public:
860 void swap(tuple&) noexcept { /* no-op */ }
861 };
862
863 /// Partial specialization, 2-element tuple.
864 /// Includes construction and assignment from a pair.
865 template<typename _T1, typename _T2>
866 class tuple<_T1, _T2> : public _Tuple_impl<0, _T1, _T2>
867 {
868 typedef _Tuple_impl<0, _T1, _T2> _Inherited;
869
870 public:
871 template <typename _U1 = _T1,
872 typename _U2 = _T2,
873 typename enable_if<__and_<
874 __is_implicitly_default_constructible<_U1>,
875 __is_implicitly_default_constructible<_U2>>
876 ::value, bool>::type = true>
877
878 constexpr tuple()
879 : _Inherited() { }
880
881 template <typename _U1 = _T1,
882 typename _U2 = _T2,
883 typename enable_if<
884 __and_<
885 is_default_constructible<_U1>,
886 is_default_constructible<_U2>,
887 __not_<
888 __and_<__is_implicitly_default_constructible<_U1>,
889 __is_implicitly_default_constructible<_U2>>>>
890 ::value, bool>::type = false>
891
892 explicit constexpr tuple()
893 : _Inherited() { }
894
895 // Shortcut for the cases where constructors taking _T1, _T2
896 // need to be constrained.
897 template<typename _Dummy> using _TCC =
898 _TC<is_same<_Dummy, void>::value, _T1, _T2>;
899
900 template<typename _Dummy = void, typename
901 enable_if<_TCC<_Dummy>::template
902 _ConstructibleTuple<_T1, _T2>()
903 && _TCC<_Dummy>::template
904 _ImplicitlyConvertibleTuple<_T1, _T2>(),
905 bool>::type = true>
906 constexpr tuple(const _T1& __a1, const _T2& __a2)
907 : _Inherited(__a1, __a2) { }
908
909 template<typename _Dummy = void, typename
910 enable_if<_TCC<_Dummy>::template
911 _ConstructibleTuple<_T1, _T2>()
912 && !_TCC<_Dummy>::template
913 _ImplicitlyConvertibleTuple<_T1, _T2>(),
914 bool>::type = false>
915 explicit constexpr tuple(const _T1& __a1, const _T2& __a2)
916 : _Inherited(__a1, __a2) { }
917
918 // Shortcut for the cases where constructors taking _U1, _U2
919 // need to be constrained.
920 using _TMC = _TC<true, _T1, _T2>;
921
922 template<typename _U1, typename _U2, typename
923 enable_if<_TMC::template
924 _MoveConstructibleTuple<_U1, _U2>()
925 && _TMC::template
926 _ImplicitlyMoveConvertibleTuple<_U1, _U2>()
927 && !is_same<typename decay<_U1>::type,
928 allocator_arg_t>::value,
929 bool>::type = true>
930 constexpr tuple(_U1&& __a1, _U2&& __a2)
931 : _Inherited(std::forward<_U1>(__a1), std::forward<_U2>(__a2)) { }
932
933 template<typename _U1, typename _U2, typename
934 enable_if<_TMC::template
935 _MoveConstructibleTuple<_U1, _U2>()
936 && !_TMC::template
937 _ImplicitlyMoveConvertibleTuple<_U1, _U2>()
938 && !is_same<typename decay<_U1>::type,
939 allocator_arg_t>::value,
940 bool>::type = false>
941 explicit constexpr tuple(_U1&& __a1, _U2&& __a2)
942 : _Inherited(std::forward<_U1>(__a1), std::forward<_U2>(__a2)) { }
943
944 constexpr tuple(const tuple&) = default;
945
946 constexpr tuple(tuple&&) = default;
947
948 template<typename _U1, typename _U2, typename
949 enable_if<_TMC::template
950 _ConstructibleTuple<_U1, _U2>()
951 && _TMC::template
952 _ImplicitlyConvertibleTuple<_U1, _U2>(),
953 bool>::type = true>
954 constexpr tuple(const tuple<_U1, _U2>& __in)
955 : _Inherited(static_cast<const _Tuple_impl<0, _U1, _U2>&>(__in)) { }
956
957 template<typename _U1, typename _U2, typename
958 enable_if<_TMC::template
959 _ConstructibleTuple<_U1, _U2>()
960 && !_TMC::template
961 _ImplicitlyConvertibleTuple<_U1, _U2>(),
962 bool>::type = false>
963 explicit constexpr tuple(const tuple<_U1, _U2>& __in)
964 : _Inherited(static_cast<const _Tuple_impl<0, _U1, _U2>&>(__in)) { }
965
966 template<typename _U1, typename _U2, typename
967 enable_if<_TMC::template
968 _MoveConstructibleTuple<_U1, _U2>()
969 && _TMC::template
970 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
971 bool>::type = true>
972 constexpr tuple(tuple<_U1, _U2>&& __in)
973 : _Inherited(static_cast<_Tuple_impl<0, _U1, _U2>&&>(__in)) { }
974
975 template<typename _U1, typename _U2, typename
976 enable_if<_TMC::template
977 _MoveConstructibleTuple<_U1, _U2>()
978 && !_TMC::template
979 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
980 bool>::type = false>
981 explicit constexpr tuple(tuple<_U1, _U2>&& __in)
982 : _Inherited(static_cast<_Tuple_impl<0, _U1, _U2>&&>(__in)) { }
983
984 template<typename _U1, typename _U2, typename
985 enable_if<_TMC::template
986 _ConstructibleTuple<_U1, _U2>()
987 && _TMC::template
988 _ImplicitlyConvertibleTuple<_U1, _U2>(),
989 bool>::type = true>
990 constexpr tuple(const pair<_U1, _U2>& __in)
991 : _Inherited(__in.first, __in.second) { }
992
993 template<typename _U1, typename _U2, typename
994 enable_if<_TMC::template
995 _ConstructibleTuple<_U1, _U2>()
996 && !_TMC::template
997 _ImplicitlyConvertibleTuple<_U1, _U2>(),
998 bool>::type = false>
999 explicit constexpr tuple(const pair<_U1, _U2>& __in)
1000 : _Inherited(__in.first, __in.second) { }
1001
1002 template<typename _U1, typename _U2, typename
1003 enable_if<_TMC::template
1004 _MoveConstructibleTuple<_U1, _U2>()
1005 && _TMC::template
1006 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
1007 bool>::type = true>
1008 constexpr tuple(pair<_U1, _U2>&& __in)
1009 : _Inherited(std::forward<_U1>(__in.first),
1010 std::forward<_U2>(__in.second)) { }
1011
1012 template<typename _U1, typename _U2, typename
1013 enable_if<_TMC::template
1014 _MoveConstructibleTuple<_U1, _U2>()
1015 && !_TMC::template
1016 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
1017 bool>::type = false>
1018 explicit constexpr tuple(pair<_U1, _U2>&& __in)
1019 : _Inherited(std::forward<_U1>(__in.first),
1020 std::forward<_U2>(__in.second)) { }
1021
1022 // Allocator-extended constructors.
1023
1024 template<typename _Alloc>
1025 tuple(allocator_arg_t __tag, const _Alloc& __a)
1026 : _Inherited(__tag, __a) { }
1027
1028 template<typename _Alloc, typename _Dummy = void,
1029 typename enable_if<
1030 _TCC<_Dummy>::template
1031 _ConstructibleTuple<_T1, _T2>()
1032 && _TCC<_Dummy>::template
1033 _ImplicitlyConvertibleTuple<_T1, _T2>(),
1034 bool>::type=true>
1035
1036 tuple(allocator_arg_t __tag, const _Alloc& __a,
1037 const _T1& __a1, const _T2& __a2)
1038 : _Inherited(__tag, __a, __a1, __a2) { }
1039
1040 template<typename _Alloc, typename _Dummy = void,
1041 typename enable_if<
1042 _TCC<_Dummy>::template
1043 _ConstructibleTuple<_T1, _T2>()
1044 && !_TCC<_Dummy>::template
1045 _ImplicitlyConvertibleTuple<_T1, _T2>(),
1046 bool>::type=false>
1047
1048 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
1049 const _T1& __a1, const _T2& __a2)
1050 : _Inherited(__tag, __a, __a1, __a2) { }
1051
1052 template<typename _Alloc, typename _U1, typename _U2, typename
1053 enable_if<_TMC::template
1054 _MoveConstructibleTuple<_U1, _U2>()
1055 && _TMC::template
1056 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
1057 bool>::type = true>
1058 tuple(allocator_arg_t __tag, const _Alloc& __a, _U1&& __a1, _U2&& __a2)
1059 : _Inherited(__tag, __a, std::forward<_U1>(__a1),
1060 std::forward<_U2>(__a2)) { }
1061
1062 template<typename _Alloc, typename _U1, typename _U2, typename
1063 enable_if<_TMC::template
1064 _MoveConstructibleTuple<_U1, _U2>()
1065 && !_TMC::template
1066 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
1067 bool>::type = false>
1068 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
1069 _U1&& __a1, _U2&& __a2)
1070 : _Inherited(__tag, __a, std::forward<_U1>(__a1),
1071 std::forward<_U2>(__a2)) { }
1072
1073 template<typename _Alloc>
1074 tuple(allocator_arg_t __tag, const _Alloc& __a, const tuple& __in)
1075 : _Inherited(__tag, __a, static_cast<const _Inherited&>(__in)) { }
1076
1077 template<typename _Alloc>
1078 tuple(allocator_arg_t __tag, const _Alloc& __a, tuple&& __in)
1079 : _Inherited(__tag, __a, static_cast<_Inherited&&>(__in)) { }
1080
1081 template<typename _Alloc, typename _U1, typename _U2, typename
1082 enable_if<_TMC::template
1083 _ConstructibleTuple<_U1, _U2>()
1084 && _TMC::template
1085 _ImplicitlyConvertibleTuple<_U1, _U2>(),
1086 bool>::type = true>
1087 tuple(allocator_arg_t __tag, const _Alloc& __a,
1088 const tuple<_U1, _U2>& __in)
1089 : _Inherited(__tag, __a,
1090 static_cast<const _Tuple_impl<0, _U1, _U2>&>(__in))
1091 { }
1092
1093 template<typename _Alloc, typename _U1, typename _U2, typename
1094 enable_if<_TMC::template
1095 _ConstructibleTuple<_U1, _U2>()
1096 && !_TMC::template
1097 _ImplicitlyConvertibleTuple<_U1, _U2>(),
1098 bool>::type = false>
1099 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
1100 const tuple<_U1, _U2>& __in)
1101 : _Inherited(__tag, __a,
1102 static_cast<const _Tuple_impl<0, _U1, _U2>&>(__in))
1103 { }
1104
1105 template<typename _Alloc, typename _U1, typename _U2, typename
1106 enable_if<_TMC::template
1107 _MoveConstructibleTuple<_U1, _U2>()
1108 && _TMC::template
1109 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
1110 bool>::type = true>
1111 tuple(allocator_arg_t __tag, const _Alloc& __a, tuple<_U1, _U2>&& __in)
1112 : _Inherited(__tag, __a, static_cast<_Tuple_impl<0, _U1, _U2>&&>(__in))
1113 { }
1114
1115 template<typename _Alloc, typename _U1, typename _U2, typename
1116 enable_if<_TMC::template
1117 _MoveConstructibleTuple<_U1, _U2>()
1118 && !_TMC::template
1119 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
1120 bool>::type = false>
1121 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
1122 tuple<_U1, _U2>&& __in)
1123 : _Inherited(__tag, __a, static_cast<_Tuple_impl<0, _U1, _U2>&&>(__in))
1124 { }
1125
1126 template<typename _Alloc, typename _U1, typename _U2, typename
1127 enable_if<_TMC::template
1128 _ConstructibleTuple<_U1, _U2>()
1129 && _TMC::template
1130 _ImplicitlyConvertibleTuple<_U1, _U2>(),
1131 bool>::type = true>
1132 tuple(allocator_arg_t __tag, const _Alloc& __a,
1133 const pair<_U1, _U2>& __in)
1134 : _Inherited(__tag, __a, __in.first, __in.second) { }
1135
1136 template<typename _Alloc, typename _U1, typename _U2, typename
1137 enable_if<_TMC::template
1138 _ConstructibleTuple<_U1, _U2>()
1139 && !_TMC::template
1140 _ImplicitlyConvertibleTuple<_U1, _U2>(),
1141 bool>::type = false>
1142 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
1143 const pair<_U1, _U2>& __in)
1144 : _Inherited(__tag, __a, __in.first, __in.second) { }
1145
1146 template<typename _Alloc, typename _U1, typename _U2, typename
1147 enable_if<_TMC::template
1148 _MoveConstructibleTuple<_U1, _U2>()
1149 && _TMC::template
1150 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
1151 bool>::type = true>
1152 tuple(allocator_arg_t __tag, const _Alloc& __a, pair<_U1, _U2>&& __in)
1153 : _Inherited(__tag, __a, std::forward<_U1>(__in.first),
1154 std::forward<_U2>(__in.second)) { }
1155
1156 template<typename _Alloc, typename _U1, typename _U2, typename
1157 enable_if<_TMC::template
1158 _MoveConstructibleTuple<_U1, _U2>()
1159 && !_TMC::template
1160 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
1161 bool>::type = false>
1162 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
1163 pair<_U1, _U2>&& __in)
1164 : _Inherited(__tag, __a, std::forward<_U1>(__in.first),
1165 std::forward<_U2>(__in.second)) { }
1166
1167 tuple&
1168 operator=(const tuple& __in)
1169 {
1170 static_cast<_Inherited&>(*this) = __in;
1171 return *this;
1172 }
1173
1174 tuple&
1175 operator=(tuple&& __in)
1176 noexcept(is_nothrow_move_assignable<_Inherited>::value)
1177 {
1178 static_cast<_Inherited&>(*this) = std::move(__in);
1179 return *this;
1180 }
1181
1182 template<typename _U1, typename _U2>
1183 tuple&
1184 operator=(const tuple<_U1, _U2>& __in)
1185 {
1186 static_cast<_Inherited&>(*this) = __in;
1187 return *this;
1188 }
1189
1190 template<typename _U1, typename _U2>
1191 tuple&
1192 operator=(tuple<_U1, _U2>&& __in)
1193 {
1194 static_cast<_Inherited&>(*this) = std::move(__in);
1195 return *this;
1196 }
1197
1198 template<typename _U1, typename _U2>
1199 tuple&
1200 operator=(const pair<_U1, _U2>& __in)
1201 {
1202 this->_M_head(*this) = __in.first;
1203 this->_M_tail(*this)._M_head(*this) = __in.second;
1204 return *this;
1205 }
1206
1207 template<typename _U1, typename _U2>
1208 tuple&
1209 operator=(pair<_U1, _U2>&& __in)
1210 {
1211 this->_M_head(*this) = std::forward<_U1>(__in.first);
1212 this->_M_tail(*this)._M_head(*this) = std::forward<_U2>(__in.second);
1213 return *this;
1214 }
1215
1216 void
1217 swap(tuple& __in)
1218 noexcept(noexcept(__in._M_swap(__in)))
1219 { _Inherited::_M_swap(__in); }
1220 };
1221
1222
1223 /**
1224 * Recursive case for tuple_element: strip off the first element in
1225 * the tuple and retrieve the (i-1)th element of the remaining tuple.
1226 */
1227 template<std::size_t __i, typename _Head, typename... _Tail>
1228 struct tuple_element<__i, tuple<_Head, _Tail...> >
1229 : tuple_element<__i - 1, tuple<_Tail...> > { };
1230
1231 /**
1232 * Basis case for tuple_element: The first element is the one we're seeking.
1233 */
1234 template<typename _Head, typename... _Tail>
1235 struct tuple_element<0, tuple<_Head, _Tail...> >
1236 {
1237 typedef _Head type;
1238 };
1239
1240 /// class tuple_size
1241 template<typename... _Elements>
1242 struct tuple_size<tuple<_Elements...>>
1243 : public integral_constant<std::size_t, sizeof...(_Elements)> { };
1244
1245 template<std::size_t __i, typename _Head, typename... _Tail>
1246 constexpr _Head&
1247 __get_helper(_Tuple_impl<__i, _Head, _Tail...>& __t) noexcept
1248 { return _Tuple_impl<__i, _Head, _Tail...>::_M_head(__t); }
1249
1250 template<std::size_t __i, typename _Head, typename... _Tail>
1251 constexpr const _Head&
1252 __get_helper(const _Tuple_impl<__i, _Head, _Tail...>& __t) noexcept
1253 { return _Tuple_impl<__i, _Head, _Tail...>::_M_head(__t); }
1254
1255 /// Return a reference to the ith element of a tuple.
1256 template<std::size_t __i, typename... _Elements>
1257 constexpr __tuple_element_t<__i, tuple<_Elements...>>&
1258 get(tuple<_Elements...>& __t) noexcept
1259 { return std::__get_helper<__i>(__t); }
1260
1261 /// Return a const reference to the ith element of a const tuple.
1262 template<std::size_t __i, typename... _Elements>
1263 constexpr const __tuple_element_t<__i, tuple<_Elements...>>&
1264 get(const tuple<_Elements...>& __t) noexcept
1265 { return std::__get_helper<__i>(__t); }
1266
1267 /// Return an rvalue reference to the ith element of a tuple rvalue.
1268 template<std::size_t __i, typename... _Elements>
1269 constexpr __tuple_element_t<__i, tuple<_Elements...>>&&
1270 get(tuple<_Elements...>&& __t) noexcept
1271 {
1272 typedef __tuple_element_t<__i, tuple<_Elements...>> __element_type;
1273 return std::forward<__element_type&&>(std::get<__i>(__t));
1274 }
1275
1276#if __cplusplus201402L > 201103L
1277
1278#define __cpp_lib_tuples_by_type201304 201304
1279
1280 template<typename _Head, size_t __i, typename... _Tail>
1281 constexpr _Head&
1282 __get_helper2(_Tuple_impl<__i, _Head, _Tail...>& __t) noexcept
1283 { return _Tuple_impl<__i, _Head, _Tail...>::_M_head(__t); }
1284
1285 template<typename _Head, size_t __i, typename... _Tail>
1286 constexpr const _Head&
1287 __get_helper2(const _Tuple_impl<__i, _Head, _Tail...>& __t) noexcept
1288 { return _Tuple_impl<__i, _Head, _Tail...>::_M_head(__t); }
1289
1290 /// Return a reference to the unique element of type _Tp of a tuple.
1291 template <typename _Tp, typename... _Types>
1292 constexpr _Tp&
1293 get(tuple<_Types...>& __t) noexcept
1294 { return std::__get_helper2<_Tp>(__t); }
1295
1296 /// Return a reference to the unique element of type _Tp of a tuple rvalue.
1297 template <typename _Tp, typename... _Types>
1298 constexpr _Tp&&
1299 get(tuple<_Types...>&& __t) noexcept
1300 { return std::forward<_Tp&&>(std::__get_helper2<_Tp>(__t)); }
1301
1302 /// Return a const reference to the unique element of type _Tp of a tuple.
1303 template <typename _Tp, typename... _Types>
1304 constexpr const _Tp&
1305 get(const tuple<_Types...>& __t) noexcept
1306 { return std::__get_helper2<_Tp>(__t); }
1307#endif
1308
1309 // This class performs the comparison operations on tuples
1310 template<typename _Tp, typename _Up, size_t __i, size_t __size>
1311 struct __tuple_compare
1312 {
1313 static constexpr bool
1314 __eq(const _Tp& __t, const _Up& __u)
1315 {
1316 return bool(std::get<__i>(__t) == std::get<__i>(__u))
1317 && __tuple_compare<_Tp, _Up, __i + 1, __size>::__eq(__t, __u);
1318 }
1319
1320 static constexpr bool
1321 __less(const _Tp& __t, const _Up& __u)
1322 {
1323 return bool(std::get<__i>(__t) < std::get<__i>(__u))
8
Assuming the condition is false
10
Returning value, which participates in a condition later
1324 || (!bool(std::get<__i>(__u) < std::get<__i>(__t))
9
Assuming the condition is false
1325 && __tuple_compare<_Tp, _Up, __i + 1, __size>::__less(__t, __u));
1326 }
1327 };
1328
1329 template<typename _Tp, typename _Up, size_t __size>
1330 struct __tuple_compare<_Tp, _Up, __size, __size>
1331 {
1332 static constexpr bool
1333 __eq(const _Tp&, const _Up&) { return true; }
1334
1335 static constexpr bool
1336 __less(const _Tp&, const _Up&) { return false; }
1337 };
1338
1339 template<typename... _TElements, typename... _UElements>
1340 constexpr bool
1341 operator==(const tuple<_TElements...>& __t,
1342 const tuple<_UElements...>& __u)
1343 {
1344 static_assert(sizeof...(_TElements) == sizeof...(_UElements),
1345 "tuple objects can only be compared if they have equal sizes.");
1346 using __compare = __tuple_compare<tuple<_TElements...>,
1347 tuple<_UElements...>,
1348 0, sizeof...(_TElements)>;
1349 return __compare::__eq(__t, __u);
1350 }
1351
1352 template<typename... _TElements, typename... _UElements>
1353 constexpr bool
1354 operator<(const tuple<_TElements...>& __t,
1355 const tuple<_UElements...>& __u)
1356 {
1357 static_assert(sizeof...(_TElements) == sizeof...(_UElements),
1358 "tuple objects can only be compared if they have equal sizes.");
1359 using __compare = __tuple_compare<tuple<_TElements...>,
1360 tuple<_UElements...>,
1361 0, sizeof...(_TElements)>;
1362 return __compare::__less(__t, __u);
7
Calling '__tuple_compare::__less'
11
Returning from '__tuple_compare::__less'
12
Returning value, which participates in a condition later
1363 }
1364
1365 template<typename... _TElements, typename... _UElements>
1366 constexpr bool
1367 operator!=(const tuple<_TElements...>& __t,
1368 const tuple<_UElements...>& __u)
1369 { return !(__t == __u); }
1370
1371 template<typename... _TElements, typename... _UElements>
1372 constexpr bool
1373 operator>(const tuple<_TElements...>& __t,
1374 const tuple<_UElements...>& __u)
1375 { return __u < __t; }
1376
1377 template<typename... _TElements, typename... _UElements>
1378 constexpr bool
1379 operator<=(const tuple<_TElements...>& __t,
1380 const tuple<_UElements...>& __u)
1381 { return !(__u < __t); }
1382
1383 template<typename... _TElements, typename... _UElements>
1384 constexpr bool
1385 operator>=(const tuple<_TElements...>& __t,
1386 const tuple<_UElements...>& __u)
1387 { return !(__t < __u); }
1388
1389 // NB: DR 705.
1390 template<typename... _Elements>
1391 constexpr tuple<typename __decay_and_strip<_Elements>::__type...>
1392 make_tuple(_Elements&&... __args)
1393 {
1394 typedef tuple<typename __decay_and_strip<_Elements>::__type...>
1395 __result_type;
1396 return __result_type(std::forward<_Elements>(__args)...);
1397 }
1398
1399 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1400 // 2275. Why is forward_as_tuple not constexpr?
1401 template<typename... _Elements>
1402 constexpr tuple<_Elements&&...>
1403 forward_as_tuple(_Elements&&... __args) noexcept
1404 { return tuple<_Elements&&...>(std::forward<_Elements>(__args)...); }
1405
1406 template<typename... _Tps>
1407 struct __is_tuple_like_impl<tuple<_Tps...>> : true_type
1408 { };
1409
1410 // Internal type trait that allows us to sfinae-protect tuple_cat.
1411 template<typename _Tp>
1412 struct __is_tuple_like
1413 : public __is_tuple_like_impl<typename std::remove_cv
1414 <typename std::remove_reference<_Tp>::type>::type>::type
1415 { };
1416
1417 template<size_t, typename, typename, size_t>
1418 struct __make_tuple_impl;
1419
1420 template<size_t _Idx, typename _Tuple, typename... _Tp, size_t _Nm>
1421 struct __make_tuple_impl<_Idx, tuple<_Tp...>, _Tuple, _Nm>
1422 : __make_tuple_impl<_Idx + 1,
1423 tuple<_Tp..., __tuple_element_t<_Idx, _Tuple>>,
1424 _Tuple, _Nm>
1425 { };
1426
1427 template<std::size_t _Nm, typename _Tuple, typename... _Tp>
1428 struct __make_tuple_impl<_Nm, tuple<_Tp...>, _Tuple, _Nm>
1429 {
1430 typedef tuple<_Tp...> __type;
1431 };
1432
1433 template<typename _Tuple>
1434 struct __do_make_tuple
1435 : __make_tuple_impl<0, tuple<>, _Tuple, std::tuple_size<_Tuple>::value>
1436 { };
1437
1438 // Returns the std::tuple equivalent of a tuple-like type.
1439 template<typename _Tuple>
1440 struct __make_tuple
1441 : public __do_make_tuple<typename std::remove_cv
1442 <typename std::remove_reference<_Tuple>::type>::type>
1443 { };
1444
1445 // Combines several std::tuple's into a single one.
1446 template<typename...>
1447 struct __combine_tuples;
1448
1449 template<>
1450 struct __combine_tuples<>
1451 {
1452 typedef tuple<> __type;
1453 };
1454
1455 template<typename... _Ts>
1456 struct __combine_tuples<tuple<_Ts...>>
1457 {
1458 typedef tuple<_Ts...> __type;
1459 };
1460
1461 template<typename... _T1s, typename... _T2s, typename... _Rem>
1462 struct __combine_tuples<tuple<_T1s...>, tuple<_T2s...>, _Rem...>
1463 {
1464 typedef typename __combine_tuples<tuple<_T1s..., _T2s...>,
1465 _Rem...>::__type __type;
1466 };
1467
1468 // Computes the result type of tuple_cat given a set of tuple-like types.
1469 template<typename... _Tpls>
1470 struct __tuple_cat_result
1471 {
1472 typedef typename __combine_tuples
1473 <typename __make_tuple<_Tpls>::__type...>::__type __type;
1474 };
1475
1476 // Helper to determine the index set for the first tuple-like
1477 // type of a given set.
1478 template<typename...>
1479 struct __make_1st_indices;
1480
1481 template<>
1482 struct __make_1st_indices<>
1483 {
1484 typedef std::_Index_tuple<> __type;
1485 };
1486
1487 template<typename _Tp, typename... _Tpls>
1488 struct __make_1st_indices<_Tp, _Tpls...>
1489 {
1490 typedef typename std::_Build_index_tuple<std::tuple_size<
1491 typename std::remove_reference<_Tp>::type>::value>::__type __type;
1492 };
1493
1494 // Performs the actual concatenation by step-wise expanding tuple-like
1495 // objects into the elements, which are finally forwarded into the
1496 // result tuple.
1497 template<typename _Ret, typename _Indices, typename... _Tpls>
1498 struct __tuple_concater;
1499
1500 template<typename _Ret, std::size_t... _Is, typename _Tp, typename... _Tpls>
1501 struct __tuple_concater<_Ret, std::_Index_tuple<_Is...>, _Tp, _Tpls...>
1502 {
1503 template<typename... _Us>
1504 static constexpr _Ret
1505 _S_do(_Tp&& __tp, _Tpls&&... __tps, _Us&&... __us)
1506 {
1507 typedef typename __make_1st_indices<_Tpls...>::__type __idx;
1508 typedef __tuple_concater<_Ret, __idx, _Tpls...> __next;
1509 return __next::_S_do(std::forward<_Tpls>(__tps)...,
1510 std::forward<_Us>(__us)...,
1511 std::get<_Is>(std::forward<_Tp>(__tp))...);
1512 }
1513 };
1514
1515 template<typename _Ret>
1516 struct __tuple_concater<_Ret, std::_Index_tuple<>>
1517 {
1518 template<typename... _Us>
1519 static constexpr _Ret
1520 _S_do(_Us&&... __us)
1521 {
1522 return _Ret(std::forward<_Us>(__us)...);
1523 }
1524 };
1525
1526 /// tuple_cat
1527 template<typename... _Tpls, typename = typename
1528 enable_if<__and_<__is_tuple_like<_Tpls>...>::value>::type>
1529 constexpr auto
1530 tuple_cat(_Tpls&&... __tpls)
1531 -> typename __tuple_cat_result<_Tpls...>::__type
1532 {
1533 typedef typename __tuple_cat_result<_Tpls...>::__type __ret;
1534 typedef typename __make_1st_indices<_Tpls...>::__type __idx;
1535 typedef __tuple_concater<__ret, __idx, _Tpls...> __concater;
1536 return __concater::_S_do(std::forward<_Tpls>(__tpls)...);
1537 }
1538
1539 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1540 // 2301. Why is tie not constexpr?
1541 /// tie
1542 template<typename... _Elements>
1543 constexpr tuple<_Elements&...>
1544 tie(_Elements&... __args) noexcept
1545 { return tuple<_Elements&...>(__args...); }
1546
1547 /// swap
1548 template<typename... _Elements>
1549 inline void
1550 swap(tuple<_Elements...>& __x, tuple<_Elements...>& __y)
1551 noexcept(noexcept(__x.swap(__y)))
1552 { __x.swap(__y); }
1553
1554 // A class (and instance) which can be used in 'tie' when an element
1555 // of a tuple is not required
1556 struct _Swallow_assign
1557 {
1558 template<class _Tp>
1559 const _Swallow_assign&
1560 operator=(const _Tp&) const
1561 { return *this; }
1562 };
1563
1564 const _Swallow_assign ignore{};
1565
1566 /// Partial specialization for tuples
1567 template<typename... _Types, typename _Alloc>
1568 struct uses_allocator<tuple<_Types...>, _Alloc> : true_type { };
1569
1570 // See stl_pair.h...
1571 template<class _T1, class _T2>
1572 template<typename... _Args1, typename... _Args2>
1573 inline
1574 pair<_T1, _T2>::
1575 pair(piecewise_construct_t,
1576 tuple<_Args1...> __first, tuple<_Args2...> __second)
1577 : pair(__first, __second,
1578 typename _Build_index_tuple<sizeof...(_Args1)>::__type(),
1579 typename _Build_index_tuple<sizeof...(_Args2)>::__type())
1580 { }
1581
1582 template<class _T1, class _T2>
1583 template<typename... _Args1, std::size_t... _Indexes1,
1584 typename... _Args2, std::size_t... _Indexes2>
1585 inline
1586 pair<_T1, _T2>::
1587 pair(tuple<_Args1...>& __tuple1, tuple<_Args2...>& __tuple2,
1588 _Index_tuple<_Indexes1...>, _Index_tuple<_Indexes2...>)
1589 : first(std::forward<_Args1>(std::get<_Indexes1>(__tuple1))...),
1590 second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
1591 { }
1592
1593 /// @}
1594
1595_GLIBCXX_END_NAMESPACE_VERSION
1596} // namespace std
1597
1598#endif // C++11
1599
1600#endif // _GLIBCXX_TUPLE