Bug Summary

File:clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
Warning:line 7509, column 45
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 RewriteModernObjC.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 -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Frontend/Rewrite -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Frontend/Rewrite -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -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-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp

1//===-- RewriteModernObjC.cpp - Playground for the code rewriter ----------===//
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// Hacks and fun related to the code rewriter.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Rewrite/Frontend/ASTConsumers.h"
14#include "clang/AST/AST.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/ParentMap.h"
18#include "clang/Basic/CharInfo.h"
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/TargetInfo.h"
23#include "clang/Config/config.h"
24#include "clang/Lex/Lexer.h"
25#include "clang/Rewrite/Core/Rewriter.h"
26#include "llvm/ADT/DenseSet.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringExtras.h"
29#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
31#include <memory>
32
33#if CLANG_ENABLE_OBJC_REWRITER1
34
35using namespace clang;
36using llvm::utostr;
37
38namespace {
39 class RewriteModernObjC : public ASTConsumer {
40 protected:
41
42 enum {
43 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
44 block, ... */
45 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
46 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
47 __block variable */
48 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
49 helpers */
50 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
51 support routines */
52 BLOCK_BYREF_CURRENT_MAX = 256
53 };
54
55 enum {
56 BLOCK_NEEDS_FREE = (1 << 24),
57 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
58 BLOCK_HAS_CXX_OBJ = (1 << 26),
59 BLOCK_IS_GC = (1 << 27),
60 BLOCK_IS_GLOBAL = (1 << 28),
61 BLOCK_HAS_DESCRIPTOR = (1 << 29)
62 };
63
64 Rewriter Rewrite;
65 DiagnosticsEngine &Diags;
66 const LangOptions &LangOpts;
67 ASTContext *Context;
68 SourceManager *SM;
69 TranslationUnitDecl *TUDecl;
70 FileID MainFileID;
71 const char *MainFileStart, *MainFileEnd;
72 Stmt *CurrentBody;
73 ParentMap *PropParentMap; // created lazily.
74 std::string InFileName;
75 std::unique_ptr<raw_ostream> OutFile;
76 std::string Preamble;
77
78 TypeDecl *ProtocolTypeDecl;
79 VarDecl *GlobalVarDecl;
80 Expr *GlobalConstructionExp;
81 unsigned RewriteFailedDiag;
82 unsigned GlobalBlockRewriteFailedDiag;
83 // ObjC string constant support.
84 unsigned NumObjCStringLiterals;
85 VarDecl *ConstantStringClassReference;
86 RecordDecl *NSStringRecord;
87
88 // ObjC foreach break/continue generation support.
89 int BcLabelCount;
90
91 unsigned TryFinallyContainsReturnDiag;
92 // Needed for super.
93 ObjCMethodDecl *CurMethodDef;
94 RecordDecl *SuperStructDecl;
95 RecordDecl *ConstantStringDecl;
96
97 FunctionDecl *MsgSendFunctionDecl;
98 FunctionDecl *MsgSendSuperFunctionDecl;
99 FunctionDecl *MsgSendStretFunctionDecl;
100 FunctionDecl *MsgSendSuperStretFunctionDecl;
101 FunctionDecl *MsgSendFpretFunctionDecl;
102 FunctionDecl *GetClassFunctionDecl;
103 FunctionDecl *GetMetaClassFunctionDecl;
104 FunctionDecl *GetSuperClassFunctionDecl;
105 FunctionDecl *SelGetUidFunctionDecl;
106 FunctionDecl *CFStringFunctionDecl;
107 FunctionDecl *SuperConstructorFunctionDecl;
108 FunctionDecl *CurFunctionDef;
109
110 /* Misc. containers needed for meta-data rewrite. */
111 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
112 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
114 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
115 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
116 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
117 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
118 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
119 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
120
121 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
122 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
123
124 SmallVector<Stmt *, 32> Stmts;
125 SmallVector<int, 8> ObjCBcLabelNo;
126 // Remember all the @protocol(<expr>) expressions.
127 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
128
129 llvm::DenseSet<uint64_t> CopyDestroyCache;
130
131 // Block expressions.
132 SmallVector<BlockExpr *, 32> Blocks;
133 SmallVector<int, 32> InnerDeclRefsCount;
134 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
135
136 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
137
138 // Block related declarations.
139 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
140 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
141 SmallVector<ValueDecl *, 8> BlockByRefDecls;
142 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
143 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
144 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
145 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
146
147 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
148 llvm::DenseMap<ObjCInterfaceDecl *,
149 llvm::SmallSetVector<ObjCIvarDecl *, 8> > ReferencedIvars;
150
151 // ivar bitfield grouping containers
152 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
153 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
154 // This container maps an <class, group number for ivar> tuple to the type
155 // of the struct where the bitfield belongs.
156 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
157 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
158
159 // This maps an original source AST to it's rewritten form. This allows
160 // us to avoid rewriting the same node twice (which is very uncommon).
161 // This is needed to support some of the exotic property rewriting.
162 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
163
164 // Needed for header files being rewritten
165 bool IsHeader;
166 bool SilenceRewriteMacroWarning;
167 bool GenerateLineInfo;
168 bool objc_impl_method;
169
170 bool DisableReplaceStmt;
171 class DisableReplaceStmtScope {
172 RewriteModernObjC &R;
173 bool SavedValue;
174
175 public:
176 DisableReplaceStmtScope(RewriteModernObjC &R)
177 : R(R), SavedValue(R.DisableReplaceStmt) {
178 R.DisableReplaceStmt = true;
179 }
180 ~DisableReplaceStmtScope() {
181 R.DisableReplaceStmt = SavedValue;
182 }
183 };
184 void InitializeCommon(ASTContext &context);
185
186 public:
187 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
188
189 // Top Level Driver code.
190 bool HandleTopLevelDecl(DeclGroupRef D) override {
191 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
192 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
193 if (!Class->isThisDeclarationADefinition()) {
194 RewriteForwardClassDecl(D);
195 break;
196 } else {
197 // Keep track of all interface declarations seen.
198 ObjCInterfacesSeen.push_back(Class);
199 break;
200 }
201 }
202
203 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
204 if (!Proto->isThisDeclarationADefinition()) {
205 RewriteForwardProtocolDecl(D);
206 break;
207 }
208 }
209
210 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
211 // Under modern abi, we cannot translate body of the function
212 // yet until all class extensions and its implementation is seen.
213 // This is because they may introduce new bitfields which must go
214 // into their grouping struct.
215 if (FDecl->isThisDeclarationADefinition() &&
216 // Not c functions defined inside an objc container.
217 !FDecl->isTopLevelDeclInObjCContainer()) {
218 FunctionDefinitionsSeen.push_back(FDecl);
219 break;
220 }
221 }
222 HandleTopLevelSingleDecl(*I);
223 }
224 return true;
225 }
226
227 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
228 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
229 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
230 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
231 RewriteBlockPointerDecl(TD);
232 else if (TD->getUnderlyingType()->isFunctionPointerType())
233 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
234 else
235 RewriteObjCQualifiedInterfaceTypes(TD);
236 }
237 }
238 }
239
240 void HandleTopLevelSingleDecl(Decl *D);
241 void HandleDeclInMainFile(Decl *D);
242 RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
243 DiagnosticsEngine &D, const LangOptions &LOpts,
244 bool silenceMacroWarn, bool LineInfo);
245
246 ~RewriteModernObjC() override {}
247
248 void HandleTranslationUnit(ASTContext &C) override;
249
250 void ReplaceStmt(Stmt *Old, Stmt *New) {
251 ReplaceStmtWithRange(Old, New, Old->getSourceRange());
252 }
253
254 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
255 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's")((Old != nullptr && New != nullptr && "Expected non-null Stmt's"
) ? static_cast<void> (0) : __assert_fail ("Old != nullptr && New != nullptr && \"Expected non-null Stmt's\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 255, __PRETTY_FUNCTION__))
;
256
257 Stmt *ReplacingStmt = ReplacedNodes[Old];
258 if (ReplacingStmt)
259 return; // We can't rewrite the same node twice.
260
261 if (DisableReplaceStmt)
262 return;
263
264 // Measure the old text.
265 int Size = Rewrite.getRangeSize(SrcRange);
266 if (Size == -1) {
267 Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
268 << Old->getSourceRange();
269 return;
270 }
271 // Get the new text.
272 std::string SStr;
273 llvm::raw_string_ostream S(SStr);
274 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
275 const std::string &Str = S.str();
276
277 // If replacement succeeded or warning disabled return with no warning.
278 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
279 ReplacedNodes[Old] = New;
280 return;
281 }
282 if (SilenceRewriteMacroWarning)
283 return;
284 Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
285 << Old->getSourceRange();
286 }
287
288 void InsertText(SourceLocation Loc, StringRef Str,
289 bool InsertAfter = true) {
290 // If insertion succeeded or warning disabled return with no warning.
291 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
292 SilenceRewriteMacroWarning)
293 return;
294
295 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
296 }
297
298 void ReplaceText(SourceLocation Start, unsigned OrigLength,
299 StringRef Str) {
300 // If removal succeeded or warning disabled return with no warning.
301 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
302 SilenceRewriteMacroWarning)
303 return;
304
305 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
306 }
307
308 // Syntactic Rewriting.
309 void RewriteRecordBody(RecordDecl *RD);
310 void RewriteInclude();
311 void RewriteLineDirective(const Decl *D);
312 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
313 std::string &LineString);
314 void RewriteForwardClassDecl(DeclGroupRef D);
315 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
316 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
317 const std::string &typedefString);
318 void RewriteImplementations();
319 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
320 ObjCImplementationDecl *IMD,
321 ObjCCategoryImplDecl *CID);
322 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
323 void RewriteImplementationDecl(Decl *Dcl);
324 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
325 ObjCMethodDecl *MDecl, std::string &ResultStr);
326 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
327 const FunctionType *&FPRetType);
328 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
329 ValueDecl *VD, bool def=false);
330 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
331 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
332 void RewriteForwardProtocolDecl(DeclGroupRef D);
333 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
334 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
335 void RewriteProperty(ObjCPropertyDecl *prop);
336 void RewriteFunctionDecl(FunctionDecl *FD);
337 void RewriteBlockPointerType(std::string& Str, QualType Type);
338 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
339 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
340 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
341 void RewriteTypeOfDecl(VarDecl *VD);
342 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
343
344 std::string getIvarAccessString(ObjCIvarDecl *D);
345
346 // Expression Rewriting.
347 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
348 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
349 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
350 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
351 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
352 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
353 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
354 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
355 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
356 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
357 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
358 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
359 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
360 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
361 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
362 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
363 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
364 SourceLocation OrigEnd);
365 Stmt *RewriteBreakStmt(BreakStmt *S);
366 Stmt *RewriteContinueStmt(ContinueStmt *S);
367 void RewriteCastExpr(CStyleCastExpr *CE);
368 void RewriteImplicitCastObjCExpr(CastExpr *IE);
369
370 // Computes ivar bitfield group no.
371 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
372 // Names field decl. for ivar bitfield group.
373 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
374 // Names struct type for ivar bitfield group.
375 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
376 // Names symbol for ivar bitfield group field offset.
377 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
378 // Given an ivar bitfield, it builds (or finds) its group record type.
379 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
380 QualType SynthesizeBitfieldGroupStructType(
381 ObjCIvarDecl *IV,
382 SmallVectorImpl<ObjCIvarDecl *> &IVars);
383
384 // Block rewriting.
385 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
386
387 // Block specific rewrite rules.
388 void RewriteBlockPointerDecl(NamedDecl *VD);
389 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
390 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
391 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
392 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
393
394 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
395 std::string &Result);
396
397 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
398 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
399 bool &IsNamedDefinition);
400 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
401 std::string &Result);
402
403 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
404
405 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
406 std::string &Result);
407
408 void Initialize(ASTContext &context) override;
409
410 // Misc. AST transformation routines. Sometimes they end up calling
411 // rewriting routines on the new ASTs.
412 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
413 ArrayRef<Expr *> Args,
414 SourceLocation StartLoc=SourceLocation(),
415 SourceLocation EndLoc=SourceLocation());
416
417 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
418 QualType returnType,
419 SmallVectorImpl<QualType> &ArgTypes,
420 SmallVectorImpl<Expr*> &MsgExprs,
421 ObjCMethodDecl *Method);
422
423 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
424 SourceLocation StartLoc=SourceLocation(),
425 SourceLocation EndLoc=SourceLocation());
426
427 void SynthCountByEnumWithState(std::string &buf);
428 void SynthMsgSendFunctionDecl();
429 void SynthMsgSendSuperFunctionDecl();
430 void SynthMsgSendStretFunctionDecl();
431 void SynthMsgSendFpretFunctionDecl();
432 void SynthMsgSendSuperStretFunctionDecl();
433 void SynthGetClassFunctionDecl();
434 void SynthGetMetaClassFunctionDecl();
435 void SynthGetSuperClassFunctionDecl();
436 void SynthSelGetUidFunctionDecl();
437 void SynthSuperConstructorFunctionDecl();
438
439 // Rewriting metadata
440 template<typename MethodIterator>
441 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
442 MethodIterator MethodEnd,
443 bool IsInstanceMethod,
444 StringRef prefix,
445 StringRef ClassName,
446 std::string &Result);
447 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
448 std::string &Result);
449 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
450 std::string &Result);
451 void RewriteClassSetupInitHook(std::string &Result);
452
453 void RewriteMetaDataIntoBuffer(std::string &Result);
454 void WriteImageInfo(std::string &Result);
455 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
456 std::string &Result);
457 void RewriteCategorySetupInitHook(std::string &Result);
458
459 // Rewriting ivar
460 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
461 std::string &Result);
462 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
463
464
465 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
466 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
467 StringRef funcName, std::string Tag);
468 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
469 StringRef funcName, std::string Tag);
470 std::string SynthesizeBlockImpl(BlockExpr *CE,
471 std::string Tag, std::string Desc);
472 std::string SynthesizeBlockDescriptor(std::string DescTag,
473 std::string ImplTag,
474 int i, StringRef funcName,
475 unsigned hasCopy);
476 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
477 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
478 StringRef FunName);
479 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
480 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
481 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
482
483 // Misc. helper routines.
484 QualType getProtocolType();
485 void WarnAboutReturnGotoStmts(Stmt *S);
486 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
487 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
488 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
489
490 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
491 void CollectBlockDeclRefInfo(BlockExpr *Exp);
492 void GetBlockDeclRefExprs(Stmt *S);
493 void GetInnerBlockDeclRefExprs(Stmt *S,
494 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
495 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
496
497 // We avoid calling Type::isBlockPointerType(), since it operates on the
498 // canonical type. We only care if the top-level type is a closure pointer.
499 bool isTopLevelBlockPointerType(QualType T) {
500 return isa<BlockPointerType>(T);
501 }
502
503 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
504 /// to a function pointer type and upon success, returns true; false
505 /// otherwise.
506 bool convertBlockPointerToFunctionPointer(QualType &T) {
507 if (isTopLevelBlockPointerType(T)) {
508 const auto *BPT = T->castAs<BlockPointerType>();
509 T = Context->getPointerType(BPT->getPointeeType());
510 return true;
511 }
512 return false;
513 }
514
515 bool convertObjCTypeToCStyleType(QualType &T);
516
517 bool needToScanForQualifiers(QualType T);
518 QualType getSuperStructType();
519 QualType getConstantStringStructType();
520 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
521
522 void convertToUnqualifiedObjCType(QualType &T) {
523 if (T->isObjCQualifiedIdType()) {
524 bool isConst = T.isConstQualified();
525 T = isConst ? Context->getObjCIdType().withConst()
526 : Context->getObjCIdType();
527 }
528 else if (T->isObjCQualifiedClassType())
529 T = Context->getObjCClassType();
530 else if (T->isObjCObjectPointerType() &&
531 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
532 if (const ObjCObjectPointerType * OBJPT =
533 T->getAsObjCInterfacePointerType()) {
534 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
535 T = QualType(IFaceT, 0);
536 T = Context->getPointerType(T);
537 }
538 }
539 }
540
541 // FIXME: This predicate seems like it would be useful to add to ASTContext.
542 bool isObjCType(QualType T) {
543 if (!LangOpts.ObjC)
544 return false;
545
546 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
547
548 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
549 OCT == Context->getCanonicalType(Context->getObjCClassType()))
550 return true;
551
552 if (const PointerType *PT = OCT->getAs<PointerType>()) {
553 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
554 PT->getPointeeType()->isObjCQualifiedIdType())
555 return true;
556 }
557 return false;
558 }
559
560 bool PointerTypeTakesAnyBlockArguments(QualType QT);
561 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
562 void GetExtentOfArgList(const char *Name, const char *&LParen,
563 const char *&RParen);
564
565 void QuoteDoublequotes(std::string &From, std::string &To) {
566 for (unsigned i = 0; i < From.length(); i++) {
567 if (From[i] == '"')
568 To += "\\\"";
569 else
570 To += From[i];
571 }
572 }
573
574 QualType getSimpleFunctionType(QualType result,
575 ArrayRef<QualType> args,
576 bool variadic = false) {
577 if (result == Context->getObjCInstanceType())
578 result = Context->getObjCIdType();
579 FunctionProtoType::ExtProtoInfo fpi;
580 fpi.Variadic = variadic;
581 return Context->getFunctionType(result, args, fpi);
582 }
583
584 // Helper function: create a CStyleCastExpr with trivial type source info.
585 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
586 CastKind Kind, Expr *E) {
587 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
588 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
589 TInfo, SourceLocation(), SourceLocation());
590 }
591
592 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
593 IdentifierInfo* II = &Context->Idents.get("load");
594 Selector LoadSel = Context->Selectors.getSelector(0, &II);
595 return OD->getClassMethod(LoadSel) != nullptr;
596 }
597
598 StringLiteral *getStringLiteral(StringRef Str) {
599 QualType StrType = Context->getConstantArrayType(
600 Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr,
601 ArrayType::Normal, 0);
602 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
603 /*Pascal=*/false, StrType, SourceLocation());
604 }
605 };
606} // end anonymous namespace
607
608void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
609 NamedDecl *D) {
610 if (const FunctionProtoType *fproto
611 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
612 for (const auto &I : fproto->param_types())
613 if (isTopLevelBlockPointerType(I)) {
614 // All the args are checked/rewritten. Don't call twice!
615 RewriteBlockPointerDecl(D);
616 break;
617 }
618 }
619}
620
621void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
622 const PointerType *PT = funcType->getAs<PointerType>();
623 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
624 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
625}
626
627static bool IsHeaderFile(const std::string &Filename) {
628 std::string::size_type DotPos = Filename.rfind('.');
629
630 if (DotPos == std::string::npos) {
631 // no file extension
632 return false;
633 }
634
635 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
636 // C header: .h
637 // C++ header: .hh or .H;
638 return Ext == "h" || Ext == "hh" || Ext == "H";
639}
640
641RewriteModernObjC::RewriteModernObjC(std::string inFile,
642 std::unique_ptr<raw_ostream> OS,
643 DiagnosticsEngine &D,
644 const LangOptions &LOpts,
645 bool silenceMacroWarn, bool LineInfo)
646 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
647 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
648 IsHeader = IsHeaderFile(inFile);
649 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
650 "rewriting sub-expression within a macro (may not be correct)");
651 // FIXME. This should be an error. But if block is not called, it is OK. And it
652 // may break including some headers.
653 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
654 "rewriting block literal declared in global scope is not implemented");
655
656 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
657 DiagnosticsEngine::Warning,
658 "rewriter doesn't support user-specified control flow semantics "
659 "for @try/@finally (code may not execute properly)");
660}
661
662std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
663 const std::string &InFile, std::unique_ptr<raw_ostream> OS,
664 DiagnosticsEngine &Diags, const LangOptions &LOpts,
665 bool SilenceRewriteMacroWarning, bool LineInfo) {
666 return std::make_unique<RewriteModernObjC>(InFile, std::move(OS), Diags,
667 LOpts, SilenceRewriteMacroWarning,
668 LineInfo);
669}
670
671void RewriteModernObjC::InitializeCommon(ASTContext &context) {
672 Context = &context;
673 SM = &Context->getSourceManager();
674 TUDecl = Context->getTranslationUnitDecl();
675 MsgSendFunctionDecl = nullptr;
676 MsgSendSuperFunctionDecl = nullptr;
677 MsgSendStretFunctionDecl = nullptr;
678 MsgSendSuperStretFunctionDecl = nullptr;
679 MsgSendFpretFunctionDecl = nullptr;
680 GetClassFunctionDecl = nullptr;
681 GetMetaClassFunctionDecl = nullptr;
682 GetSuperClassFunctionDecl = nullptr;
683 SelGetUidFunctionDecl = nullptr;
684 CFStringFunctionDecl = nullptr;
685 ConstantStringClassReference = nullptr;
686 NSStringRecord = nullptr;
687 CurMethodDef = nullptr;
688 CurFunctionDef = nullptr;
689 GlobalVarDecl = nullptr;
690 GlobalConstructionExp = nullptr;
691 SuperStructDecl = nullptr;
692 ProtocolTypeDecl = nullptr;
693 ConstantStringDecl = nullptr;
694 BcLabelCount = 0;
695 SuperConstructorFunctionDecl = nullptr;
696 NumObjCStringLiterals = 0;
697 PropParentMap = nullptr;
698 CurrentBody = nullptr;
699 DisableReplaceStmt = false;
700 objc_impl_method = false;
701
702 // Get the ID and start/end of the main file.
703 MainFileID = SM->getMainFileID();
704 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
705 MainFileStart = MainBuf->getBufferStart();
706 MainFileEnd = MainBuf->getBufferEnd();
707
708 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
709}
710
711//===----------------------------------------------------------------------===//
712// Top Level Driver Code
713//===----------------------------------------------------------------------===//
714
715void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
716 if (Diags.hasErrorOccurred())
717 return;
718
719 // Two cases: either the decl could be in the main file, or it could be in a
720 // #included file. If the former, rewrite it now. If the later, check to see
721 // if we rewrote the #include/#import.
722 SourceLocation Loc = D->getLocation();
723 Loc = SM->getExpansionLoc(Loc);
724
725 // If this is for a builtin, ignore it.
726 if (Loc.isInvalid()) return;
727
728 // Look for built-in declarations that we need to refer during the rewrite.
729 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
730 RewriteFunctionDecl(FD);
731 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
732 // declared in <Foundation/NSString.h>
733 if (FVD->getName() == "_NSConstantStringClassReference") {
734 ConstantStringClassReference = FVD;
735 return;
736 }
737 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
738 RewriteCategoryDecl(CD);
739 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
740 if (PD->isThisDeclarationADefinition())
741 RewriteProtocolDecl(PD);
742 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
743 // Recurse into linkage specifications
744 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
745 DIEnd = LSD->decls_end();
746 DI != DIEnd; ) {
747 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
748 if (!IFace->isThisDeclarationADefinition()) {
749 SmallVector<Decl *, 8> DG;
750 SourceLocation StartLoc = IFace->getBeginLoc();
751 do {
752 if (isa<ObjCInterfaceDecl>(*DI) &&
753 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
754 StartLoc == (*DI)->getBeginLoc())
755 DG.push_back(*DI);
756 else
757 break;
758
759 ++DI;
760 } while (DI != DIEnd);
761 RewriteForwardClassDecl(DG);
762 continue;
763 }
764 else {
765 // Keep track of all interface declarations seen.
766 ObjCInterfacesSeen.push_back(IFace);
767 ++DI;
768 continue;
769 }
770 }
771
772 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
773 if (!Proto->isThisDeclarationADefinition()) {
774 SmallVector<Decl *, 8> DG;
775 SourceLocation StartLoc = Proto->getBeginLoc();
776 do {
777 if (isa<ObjCProtocolDecl>(*DI) &&
778 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
779 StartLoc == (*DI)->getBeginLoc())
780 DG.push_back(*DI);
781 else
782 break;
783
784 ++DI;
785 } while (DI != DIEnd);
786 RewriteForwardProtocolDecl(DG);
787 continue;
788 }
789 }
790
791 HandleTopLevelSingleDecl(*DI);
792 ++DI;
793 }
794 }
795 // If we have a decl in the main file, see if we should rewrite it.
796 if (SM->isWrittenInMainFile(Loc))
797 return HandleDeclInMainFile(D);
798}
799
800//===----------------------------------------------------------------------===//
801// Syntactic (non-AST) Rewriting Code
802//===----------------------------------------------------------------------===//
803
804void RewriteModernObjC::RewriteInclude() {
805 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
806 StringRef MainBuf = SM->getBufferData(MainFileID);
807 const char *MainBufStart = MainBuf.begin();
808 const char *MainBufEnd = MainBuf.end();
809 size_t ImportLen = strlen("import");
810
811 // Loop over the whole file, looking for includes.
812 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
813 if (*BufPtr == '#') {
814 if (++BufPtr == MainBufEnd)
815 return;
816 while (*BufPtr == ' ' || *BufPtr == '\t')
817 if (++BufPtr == MainBufEnd)
818 return;
819 if (!strncmp(BufPtr, "import", ImportLen)) {
820 // replace import with include
821 SourceLocation ImportLoc =
822 LocStart.getLocWithOffset(BufPtr-MainBufStart);
823 ReplaceText(ImportLoc, ImportLen, "include");
824 BufPtr += ImportLen;
825 }
826 }
827 }
828}
829
830static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
831 ObjCIvarDecl *IvarDecl, std::string &Result) {
832 Result += "OBJC_IVAR_$_";
833 Result += IDecl->getName();
834 Result += "$";
835 Result += IvarDecl->getName();
836}
837
838std::string
839RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
840 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
841
842 // Build name of symbol holding ivar offset.
843 std::string IvarOffsetName;
844 if (D->isBitField())
845 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
846 else
847 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
848
849 std::string S = "(*(";
850 QualType IvarT = D->getType();
851 if (D->isBitField())
852 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
853
854 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
855 RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
856 RD = RD->getDefinition();
857 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
858 // decltype(((Foo_IMPL*)0)->bar) *
859 auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
860 // ivar in class extensions requires special treatment.
861 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
862 CDecl = CatDecl->getClassInterface();
863 std::string RecName = std::string(CDecl->getName());
864 RecName += "_IMPL";
865 RecordDecl *RD =
866 RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(),
867 SourceLocation(), &Context->Idents.get(RecName));
868 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
869 unsigned UnsignedIntSize =
870 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
871 Expr *Zero = IntegerLiteral::Create(*Context,
872 llvm::APInt(UnsignedIntSize, 0),
873 Context->UnsignedIntTy, SourceLocation());
874 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
875 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
876 Zero);
877 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
878 SourceLocation(),
879 &Context->Idents.get(D->getNameAsString()),
880 IvarT, nullptr,
881 /*BitWidth=*/nullptr, /*Mutable=*/true,
882 ICIS_NoInit);
883 MemberExpr *ME = MemberExpr::CreateImplicit(
884 *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
885 IvarT = Context->getDecltypeType(ME, ME->getType());
886 }
887 }
888 convertObjCTypeToCStyleType(IvarT);
889 QualType castT = Context->getPointerType(IvarT);
890 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
891 S += TypeString;
892 S += ")";
893
894 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
895 S += "((char *)self + ";
896 S += IvarOffsetName;
897 S += "))";
898 if (D->isBitField()) {
899 S += ".";
900 S += D->getNameAsString();
901 }
902 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
903 return S;
904}
905
906/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
907/// been found in the class implementation. In this case, it must be synthesized.
908static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
909 ObjCPropertyDecl *PD,
910 bool getter) {
911 auto *OMD = IMP->getInstanceMethod(getter ? PD->getGetterName()
912 : PD->getSetterName());
913 return !OMD || OMD->isSynthesizedAccessorStub();
914}
915
916void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
917 ObjCImplementationDecl *IMD,
918 ObjCCategoryImplDecl *CID) {
919 static bool objcGetPropertyDefined = false;
920 static bool objcSetPropertyDefined = false;
921 SourceLocation startGetterSetterLoc;
922
923 if (PID->getBeginLoc().isValid()) {
924 SourceLocation startLoc = PID->getBeginLoc();
925 InsertText(startLoc, "// ");
926 const char *startBuf = SM->getCharacterData(startLoc);
927 assert((*startBuf == '@') && "bogus @synthesize location")(((*startBuf == '@') && "bogus @synthesize location")
? static_cast<void> (0) : __assert_fail ("(*startBuf == '@') && \"bogus @synthesize location\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 927, __PRETTY_FUNCTION__))
;
928 const char *semiBuf = strchr(startBuf, ';');
929 assert((*semiBuf == ';') && "@synthesize: can't find ';'")(((*semiBuf == ';') && "@synthesize: can't find ';'")
? static_cast<void> (0) : __assert_fail ("(*semiBuf == ';') && \"@synthesize: can't find ';'\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 929, __PRETTY_FUNCTION__))
;
930 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
931 } else
932 startGetterSetterLoc = IMD ? IMD->getEndLoc() : CID->getEndLoc();
933
934 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
935 return; // FIXME: is this correct?
936
937 // Generate the 'getter' function.
938 ObjCPropertyDecl *PD = PID->getPropertyDecl();
939 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
940 assert(IMD && OID && "Synthesized ivars must be attached to @implementation")((IMD && OID && "Synthesized ivars must be attached to @implementation"
) ? static_cast<void> (0) : __assert_fail ("IMD && OID && \"Synthesized ivars must be attached to @implementation\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 940, __PRETTY_FUNCTION__))
;
941
942 unsigned Attributes = PD->getPropertyAttributes();
943 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
944 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
945 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
946 ObjCPropertyDecl::OBJC_PR_copy));
947 std::string Getr;
948 if (GenGetProperty && !objcGetPropertyDefined) {
949 objcGetPropertyDefined = true;
950 // FIXME. Is this attribute correct in all cases?
951 Getr = "\nextern \"C\" __declspec(dllimport) "
952 "id objc_getProperty(id, SEL, long, bool);\n";
953 }
954 RewriteObjCMethodDecl(OID->getContainingInterface(),
955 PID->getGetterMethodDecl(), Getr);
956 Getr += "{ ";
957 // Synthesize an explicit cast to gain access to the ivar.
958 // See objc-act.c:objc_synthesize_new_getter() for details.
959 if (GenGetProperty) {
960 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
961 Getr += "typedef ";
962 const FunctionType *FPRetType = nullptr;
963 RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr,
964 FPRetType);
965 Getr += " _TYPE";
966 if (FPRetType) {
967 Getr += ")"; // close the precedence "scope" for "*".
968
969 // Now, emit the argument types (if any).
970 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
971 Getr += "(";
972 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
973 if (i) Getr += ", ";
974 std::string ParamStr =
975 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
976 Getr += ParamStr;
977 }
978 if (FT->isVariadic()) {
979 if (FT->getNumParams())
980 Getr += ", ";
981 Getr += "...";
982 }
983 Getr += ")";
984 } else
985 Getr += "()";
986 }
987 Getr += ";\n";
988 Getr += "return (_TYPE)";
989 Getr += "objc_getProperty(self, _cmd, ";
990 RewriteIvarOffsetComputation(OID, Getr);
991 Getr += ", 1)";
992 }
993 else
994 Getr += "return " + getIvarAccessString(OID);
995 Getr += "; }";
996 InsertText(startGetterSetterLoc, Getr);
997 }
998
999 if (PD->isReadOnly() ||
1000 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
1001 return;
1002
1003 // Generate the 'setter' function.
1004 std::string Setr;
1005 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
1006 ObjCPropertyDecl::OBJC_PR_copy);
1007 if (GenSetProperty && !objcSetPropertyDefined) {
1008 objcSetPropertyDefined = true;
1009 // FIXME. Is this attribute correct in all cases?
1010 Setr = "\nextern \"C\" __declspec(dllimport) "
1011 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1012 }
1013
1014 RewriteObjCMethodDecl(OID->getContainingInterface(),
1015 PID->getSetterMethodDecl(), Setr);
1016 Setr += "{ ";
1017 // Synthesize an explicit cast to initialize the ivar.
1018 // See objc-act.c:objc_synthesize_new_setter() for details.
1019 if (GenSetProperty) {
1020 Setr += "objc_setProperty (self, _cmd, ";
1021 RewriteIvarOffsetComputation(OID, Setr);
1022 Setr += ", (id)";
1023 Setr += PD->getName();
1024 Setr += ", ";
1025 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
1026 Setr += "0, ";
1027 else
1028 Setr += "1, ";
1029 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
1030 Setr += "1)";
1031 else
1032 Setr += "0)";
1033 }
1034 else {
1035 Setr += getIvarAccessString(OID) + " = ";
1036 Setr += PD->getName();
1037 }
1038 Setr += "; }\n";
1039 InsertText(startGetterSetterLoc, Setr);
1040}
1041
1042static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1043 std::string &typedefString) {
1044 typedefString += "\n#ifndef _REWRITER_typedef_";
1045 typedefString += ForwardDecl->getNameAsString();
1046 typedefString += "\n";
1047 typedefString += "#define _REWRITER_typedef_";
1048 typedefString += ForwardDecl->getNameAsString();
1049 typedefString += "\n";
1050 typedefString += "typedef struct objc_object ";
1051 typedefString += ForwardDecl->getNameAsString();
1052 // typedef struct { } _objc_exc_Classname;
1053 typedefString += ";\ntypedef struct {} _objc_exc_";
1054 typedefString += ForwardDecl->getNameAsString();
1055 typedefString += ";\n#endif\n";
1056}
1057
1058void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1059 const std::string &typedefString) {
1060 SourceLocation startLoc = ClassDecl->getBeginLoc();
1061 const char *startBuf = SM->getCharacterData(startLoc);
1062 const char *semiPtr = strchr(startBuf, ';');
1063 // Replace the @class with typedefs corresponding to the classes.
1064 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1065}
1066
1067void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1068 std::string typedefString;
1069 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1070 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1071 if (I == D.begin()) {
1072 // Translate to typedef's that forward reference structs with the same name
1073 // as the class. As a convenience, we include the original declaration
1074 // as a comment.
1075 typedefString += "// @class ";
1076 typedefString += ForwardDecl->getNameAsString();
1077 typedefString += ";";
1078 }
1079 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1080 }
1081 else
1082 HandleTopLevelSingleDecl(*I);
1083 }
1084 DeclGroupRef::iterator I = D.begin();
1085 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1086}
1087
1088void RewriteModernObjC::RewriteForwardClassDecl(
1089 const SmallVectorImpl<Decl *> &D) {
1090 std::string typedefString;
1091 for (unsigned i = 0; i < D.size(); i++) {
1092 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1093 if (i == 0) {
1094 typedefString += "// @class ";
1095 typedefString += ForwardDecl->getNameAsString();
1096 typedefString += ";";
1097 }
1098 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1099 }
1100 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1101}
1102
1103void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1104 // When method is a synthesized one, such as a getter/setter there is
1105 // nothing to rewrite.
1106 if (Method->isImplicit())
1107 return;
1108 SourceLocation LocStart = Method->getBeginLoc();
1109 SourceLocation LocEnd = Method->getEndLoc();
1110
1111 if (SM->getExpansionLineNumber(LocEnd) >
1112 SM->getExpansionLineNumber(LocStart)) {
1113 InsertText(LocStart, "#if 0\n");
1114 ReplaceText(LocEnd, 1, ";\n#endif\n");
1115 } else {
1116 InsertText(LocStart, "// ");
1117 }
1118}
1119
1120void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1121 SourceLocation Loc = prop->getAtLoc();
1122
1123 ReplaceText(Loc, 0, "// ");
1124 // FIXME: handle properties that are declared across multiple lines.
1125}
1126
1127void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1128 SourceLocation LocStart = CatDecl->getBeginLoc();
1129
1130 // FIXME: handle category headers that are declared across multiple lines.
1131 if (CatDecl->getIvarRBraceLoc().isValid()) {
1132 ReplaceText(LocStart, 1, "/** ");
1133 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1134 }
1135 else {
1136 ReplaceText(LocStart, 0, "// ");
1137 }
1138
1139 for (auto *I : CatDecl->instance_properties())
1140 RewriteProperty(I);
1141
1142 for (auto *I : CatDecl->instance_methods())
1143 RewriteMethodDeclaration(I);
1144 for (auto *I : CatDecl->class_methods())
1145 RewriteMethodDeclaration(I);
1146
1147 // Lastly, comment out the @end.
1148 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1149 strlen("@end"), "/* @end */\n");
1150}
1151
1152void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1153 SourceLocation LocStart = PDecl->getBeginLoc();
1154 assert(PDecl->isThisDeclarationADefinition())((PDecl->isThisDeclarationADefinition()) ? static_cast<
void> (0) : __assert_fail ("PDecl->isThisDeclarationADefinition()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 1154, __PRETTY_FUNCTION__))
;
1155
1156 // FIXME: handle protocol headers that are declared across multiple lines.
1157 ReplaceText(LocStart, 0, "// ");
1158
1159 for (auto *I : PDecl->instance_methods())
1160 RewriteMethodDeclaration(I);
1161 for (auto *I : PDecl->class_methods())
1162 RewriteMethodDeclaration(I);
1163 for (auto *I : PDecl->instance_properties())
1164 RewriteProperty(I);
1165
1166 // Lastly, comment out the @end.
1167 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1168 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
1169
1170 // Must comment out @optional/@required
1171 const char *startBuf = SM->getCharacterData(LocStart);
1172 const char *endBuf = SM->getCharacterData(LocEnd);
1173 for (const char *p = startBuf; p < endBuf; p++) {
1174 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1175 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1176 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1177
1178 }
1179 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1180 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1181 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1182
1183 }
1184 }
1185}
1186
1187void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1188 SourceLocation LocStart = (*D.begin())->getBeginLoc();
1189 if (LocStart.isInvalid())
1190 llvm_unreachable("Invalid SourceLocation")::llvm::llvm_unreachable_internal("Invalid SourceLocation", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 1190)
;
1191 // FIXME: handle forward protocol that are declared across multiple lines.
1192 ReplaceText(LocStart, 0, "// ");
1193}
1194
1195void
1196RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1197 SourceLocation LocStart = DG[0]->getBeginLoc();
1198 if (LocStart.isInvalid())
1199 llvm_unreachable("Invalid SourceLocation")::llvm::llvm_unreachable_internal("Invalid SourceLocation", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 1199)
;
1200 // FIXME: handle forward protocol that are declared across multiple lines.
1201 ReplaceText(LocStart, 0, "// ");
1202}
1203
1204void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1205 const FunctionType *&FPRetType) {
1206 if (T->isObjCQualifiedIdType())
1207 ResultStr += "id";
1208 else if (T->isFunctionPointerType() ||
1209 T->isBlockPointerType()) {
1210 // needs special handling, since pointer-to-functions have special
1211 // syntax (where a decaration models use).
1212 QualType retType = T;
1213 QualType PointeeTy;
1214 if (const PointerType* PT = retType->getAs<PointerType>())
1215 PointeeTy = PT->getPointeeType();
1216 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1217 PointeeTy = BPT->getPointeeType();
1218 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1219 ResultStr +=
1220 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1221 ResultStr += "(*";
1222 }
1223 } else
1224 ResultStr += T.getAsString(Context->getPrintingPolicy());
1225}
1226
1227void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1228 ObjCMethodDecl *OMD,
1229 std::string &ResultStr) {
1230 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1231 const FunctionType *FPRetType = nullptr;
1232 ResultStr += "\nstatic ";
1233 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1234 ResultStr += " ";
1235
1236 // Unique method name
1237 std::string NameStr;
1238
1239 if (OMD->isInstanceMethod())
1240 NameStr += "_I_";
1241 else
1242 NameStr += "_C_";
1243
1244 NameStr += IDecl->getNameAsString();
1245 NameStr += "_";
1246
1247 if (ObjCCategoryImplDecl *CID =
1248 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1249 NameStr += CID->getNameAsString();
1250 NameStr += "_";
1251 }
1252 // Append selector names, replacing ':' with '_'
1253 {
1254 std::string selString = OMD->getSelector().getAsString();
1255 int len = selString.size();
1256 for (int i = 0; i < len; i++)
1257 if (selString[i] == ':')
1258 selString[i] = '_';
1259 NameStr += selString;
1260 }
1261 // Remember this name for metadata emission
1262 MethodInternalNames[OMD] = NameStr;
1263 ResultStr += NameStr;
1264
1265 // Rewrite arguments
1266 ResultStr += "(";
1267
1268 // invisible arguments
1269 if (OMD->isInstanceMethod()) {
1270 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1271 selfTy = Context->getPointerType(selfTy);
1272 if (!LangOpts.MicrosoftExt) {
1273 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1274 ResultStr += "struct ";
1275 }
1276 // When rewriting for Microsoft, explicitly omit the structure name.
1277 ResultStr += IDecl->getNameAsString();
1278 ResultStr += " *";
1279 }
1280 else
1281 ResultStr += Context->getObjCClassType().getAsString(
1282 Context->getPrintingPolicy());
1283
1284 ResultStr += " self, ";
1285 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1286 ResultStr += " _cmd";
1287
1288 // Method arguments.
1289 for (const auto *PDecl : OMD->parameters()) {
1290 ResultStr += ", ";
1291 if (PDecl->getType()->isObjCQualifiedIdType()) {
1292 ResultStr += "id ";
1293 ResultStr += PDecl->getNameAsString();
1294 } else {
1295 std::string Name = PDecl->getNameAsString();
1296 QualType QT = PDecl->getType();
1297 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1298 (void)convertBlockPointerToFunctionPointer(QT);
1299 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1300 ResultStr += Name;
1301 }
1302 }
1303 if (OMD->isVariadic())
1304 ResultStr += ", ...";
1305 ResultStr += ") ";
1306
1307 if (FPRetType) {
1308 ResultStr += ")"; // close the precedence "scope" for "*".
1309
1310 // Now, emit the argument types (if any).
1311 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1312 ResultStr += "(";
1313 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1314 if (i) ResultStr += ", ";
1315 std::string ParamStr =
1316 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1317 ResultStr += ParamStr;
1318 }
1319 if (FT->isVariadic()) {
1320 if (FT->getNumParams())
1321 ResultStr += ", ";
1322 ResultStr += "...";
1323 }
1324 ResultStr += ")";
1325 } else {
1326 ResultStr += "()";
1327 }
1328 }
1329}
1330
1331void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1332 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1333 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1334 assert((IMD || CID) && "Unknown implementation type")(((IMD || CID) && "Unknown implementation type") ? static_cast
<void> (0) : __assert_fail ("(IMD || CID) && \"Unknown implementation type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 1334, __PRETTY_FUNCTION__))
;
1335
1336 if (IMD) {
1337 if (IMD->getIvarRBraceLoc().isValid()) {
1338 ReplaceText(IMD->getBeginLoc(), 1, "/** ");
1339 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
1340 }
1341 else {
1342 InsertText(IMD->getBeginLoc(), "// ");
1343 }
1344 }
1345 else
1346 InsertText(CID->getBeginLoc(), "// ");
1347
1348 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
1349 if (!OMD->getBody())
1350 continue;
1351 std::string ResultStr;
1352 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1353 SourceLocation LocStart = OMD->getBeginLoc();
1354 SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1355
1356 const char *startBuf = SM->getCharacterData(LocStart);
1357 const char *endBuf = SM->getCharacterData(LocEnd);
1358 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1359 }
1360
1361 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
1362 if (!OMD->getBody())
1363 continue;
1364 std::string ResultStr;
1365 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1366 SourceLocation LocStart = OMD->getBeginLoc();
1367 SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1368
1369 const char *startBuf = SM->getCharacterData(LocStart);
1370 const char *endBuf = SM->getCharacterData(LocEnd);
1371 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1372 }
1373 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1374 RewritePropertyImplDecl(I, IMD, CID);
1375
1376 InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// ");
1377}
1378
1379void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1380 // Do not synthesize more than once.
1381 if (ObjCSynthesizedStructs.count(ClassDecl))
1382 return;
1383 // Make sure super class's are written before current class is written.
1384 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1385 while (SuperClass) {
1386 RewriteInterfaceDecl(SuperClass);
1387 SuperClass = SuperClass->getSuperClass();
1388 }
1389 std::string ResultStr;
1390 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
1391 // we haven't seen a forward decl - generate a typedef.
1392 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
1393 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1394
1395 RewriteObjCInternalStruct(ClassDecl, ResultStr);
1396 // Mark this typedef as having been written into its c++ equivalent.
1397 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
1398
1399 for (auto *I : ClassDecl->instance_properties())
1400 RewriteProperty(I);
1401 for (auto *I : ClassDecl->instance_methods())
1402 RewriteMethodDeclaration(I);
1403 for (auto *I : ClassDecl->class_methods())
1404 RewriteMethodDeclaration(I);
1405
1406 // Lastly, comment out the @end.
1407 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1408 "/* @end */\n");
1409 }
1410}
1411
1412Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1413 SourceRange OldRange = PseudoOp->getSourceRange();
1414
1415 // We just magically know some things about the structure of this
1416 // expression.
1417 ObjCMessageExpr *OldMsg =
1418 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1419 PseudoOp->getNumSemanticExprs() - 1));
1420
1421 // Because the rewriter doesn't allow us to rewrite rewritten code,
1422 // we need to suppress rewriting the sub-statements.
1423 Expr *Base;
1424 SmallVector<Expr*, 2> Args;
1425 {
1426 DisableReplaceStmtScope S(*this);
1427
1428 // Rebuild the base expression if we have one.
1429 Base = nullptr;
1430 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1431 Base = OldMsg->getInstanceReceiver();
1432 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1433 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1434 }
1435
1436 unsigned numArgs = OldMsg->getNumArgs();
1437 for (unsigned i = 0; i < numArgs; i++) {
1438 Expr *Arg = OldMsg->getArg(i);
1439 if (isa<OpaqueValueExpr>(Arg))
1440 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1441 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1442 Args.push_back(Arg);
1443 }
1444 }
1445
1446 // TODO: avoid this copy.
1447 SmallVector<SourceLocation, 1> SelLocs;
1448 OldMsg->getSelectorLocs(SelLocs);
1449
1450 ObjCMessageExpr *NewMsg = nullptr;
1451 switch (OldMsg->getReceiverKind()) {
1452 case ObjCMessageExpr::Class:
1453 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1454 OldMsg->getValueKind(),
1455 OldMsg->getLeftLoc(),
1456 OldMsg->getClassReceiverTypeInfo(),
1457 OldMsg->getSelector(),
1458 SelLocs,
1459 OldMsg->getMethodDecl(),
1460 Args,
1461 OldMsg->getRightLoc(),
1462 OldMsg->isImplicit());
1463 break;
1464
1465 case ObjCMessageExpr::Instance:
1466 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1467 OldMsg->getValueKind(),
1468 OldMsg->getLeftLoc(),
1469 Base,
1470 OldMsg->getSelector(),
1471 SelLocs,
1472 OldMsg->getMethodDecl(),
1473 Args,
1474 OldMsg->getRightLoc(),
1475 OldMsg->isImplicit());
1476 break;
1477
1478 case ObjCMessageExpr::SuperClass:
1479 case ObjCMessageExpr::SuperInstance:
1480 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1481 OldMsg->getValueKind(),
1482 OldMsg->getLeftLoc(),
1483 OldMsg->getSuperLoc(),
1484 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1485 OldMsg->getSuperType(),
1486 OldMsg->getSelector(),
1487 SelLocs,
1488 OldMsg->getMethodDecl(),
1489 Args,
1490 OldMsg->getRightLoc(),
1491 OldMsg->isImplicit());
1492 break;
1493 }
1494
1495 Stmt *Replacement = SynthMessageExpr(NewMsg);
1496 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1497 return Replacement;
1498}
1499
1500Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1501 SourceRange OldRange = PseudoOp->getSourceRange();
1502
1503 // We just magically know some things about the structure of this
1504 // expression.
1505 ObjCMessageExpr *OldMsg =
1506 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1507
1508 // Because the rewriter doesn't allow us to rewrite rewritten code,
1509 // we need to suppress rewriting the sub-statements.
1510 Expr *Base = nullptr;
1511 SmallVector<Expr*, 1> Args;
1512 {
1513 DisableReplaceStmtScope S(*this);
1514 // Rebuild the base expression if we have one.
1515 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1516 Base = OldMsg->getInstanceReceiver();
1517 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1518 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1519 }
1520 unsigned numArgs = OldMsg->getNumArgs();
1521 for (unsigned i = 0; i < numArgs; i++) {
1522 Expr *Arg = OldMsg->getArg(i);
1523 if (isa<OpaqueValueExpr>(Arg))
1524 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1525 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1526 Args.push_back(Arg);
1527 }
1528 }
1529
1530 // Intentionally empty.
1531 SmallVector<SourceLocation, 1> SelLocs;
1532
1533 ObjCMessageExpr *NewMsg = nullptr;
1534 switch (OldMsg->getReceiverKind()) {
1535 case ObjCMessageExpr::Class:
1536 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1537 OldMsg->getValueKind(),
1538 OldMsg->getLeftLoc(),
1539 OldMsg->getClassReceiverTypeInfo(),
1540 OldMsg->getSelector(),
1541 SelLocs,
1542 OldMsg->getMethodDecl(),
1543 Args,
1544 OldMsg->getRightLoc(),
1545 OldMsg->isImplicit());
1546 break;
1547
1548 case ObjCMessageExpr::Instance:
1549 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1550 OldMsg->getValueKind(),
1551 OldMsg->getLeftLoc(),
1552 Base,
1553 OldMsg->getSelector(),
1554 SelLocs,
1555 OldMsg->getMethodDecl(),
1556 Args,
1557 OldMsg->getRightLoc(),
1558 OldMsg->isImplicit());
1559 break;
1560
1561 case ObjCMessageExpr::SuperClass:
1562 case ObjCMessageExpr::SuperInstance:
1563 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1564 OldMsg->getValueKind(),
1565 OldMsg->getLeftLoc(),
1566 OldMsg->getSuperLoc(),
1567 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1568 OldMsg->getSuperType(),
1569 OldMsg->getSelector(),
1570 SelLocs,
1571 OldMsg->getMethodDecl(),
1572 Args,
1573 OldMsg->getRightLoc(),
1574 OldMsg->isImplicit());
1575 break;
1576 }
1577
1578 Stmt *Replacement = SynthMessageExpr(NewMsg);
1579 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1580 return Replacement;
1581}
1582
1583/// SynthCountByEnumWithState - To print:
1584/// ((NSUInteger (*)
1585/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1586/// (void *)objc_msgSend)((id)l_collection,
1587/// sel_registerName(
1588/// "countByEnumeratingWithState:objects:count:"),
1589/// &enumState,
1590/// (id *)__rw_items, (NSUInteger)16)
1591///
1592void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1593 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1594 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
1595 buf += "\n\t\t";
1596 buf += "((id)l_collection,\n\t\t";
1597 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1598 buf += "\n\t\t";
1599 buf += "&enumState, "
1600 "(id *)__rw_items, (_WIN_NSUInteger)16)";
1601}
1602
1603/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1604/// statement to exit to its outer synthesized loop.
1605///
1606Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1607 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1608 return S;
1609 // replace break with goto __break_label
1610 std::string buf;
1611
1612 SourceLocation startLoc = S->getBeginLoc();
1613 buf = "goto __break_label_";
1614 buf += utostr(ObjCBcLabelNo.back());
1615 ReplaceText(startLoc, strlen("break"), buf);
1616
1617 return nullptr;
1618}
1619
1620void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1621 SourceLocation Loc,
1622 std::string &LineString) {
1623 if (Loc.isFileID() && GenerateLineInfo) {
1624 LineString += "\n#line ";
1625 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1626 LineString += utostr(PLoc.getLine());
1627 LineString += " \"";
1628 LineString += Lexer::Stringify(PLoc.getFilename());
1629 LineString += "\"\n";
1630 }
1631}
1632
1633/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1634/// statement to continue with its inner synthesized loop.
1635///
1636Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1637 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1638 return S;
1639 // replace continue with goto __continue_label
1640 std::string buf;
1641
1642 SourceLocation startLoc = S->getBeginLoc();
1643 buf = "goto __continue_label_";
1644 buf += utostr(ObjCBcLabelNo.back());
1645 ReplaceText(startLoc, strlen("continue"), buf);
1646
1647 return nullptr;
1648}
1649
1650/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1651/// It rewrites:
1652/// for ( type elem in collection) { stmts; }
1653
1654/// Into:
1655/// {
1656/// type elem;
1657/// struct __objcFastEnumerationState enumState = { 0 };
1658/// id __rw_items[16];
1659/// id l_collection = (id)collection;
1660/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
1661/// objects:__rw_items count:16];
1662/// if (limit) {
1663/// unsigned long startMutations = *enumState.mutationsPtr;
1664/// do {
1665/// unsigned long counter = 0;
1666/// do {
1667/// if (startMutations != *enumState.mutationsPtr)
1668/// objc_enumerationMutation(l_collection);
1669/// elem = (type)enumState.itemsPtr[counter++];
1670/// stmts;
1671/// __continue_label: ;
1672/// } while (counter < limit);
1673/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1674/// objects:__rw_items count:16]));
1675/// elem = nil;
1676/// __break_label: ;
1677/// }
1678/// else
1679/// elem = nil;
1680/// }
1681///
1682Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1683 SourceLocation OrigEnd) {
1684 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty")((!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty"
) ? static_cast<void> (0) : __assert_fail ("!Stmts.empty() && \"ObjCForCollectionStmt - Statement stack empty\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 1684, __PRETTY_FUNCTION__))
;
1685 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&((isa<ObjCForCollectionStmt>(Stmts.back()) && "ObjCForCollectionStmt Statement stack mismatch"
) ? static_cast<void> (0) : __assert_fail ("isa<ObjCForCollectionStmt>(Stmts.back()) && \"ObjCForCollectionStmt Statement stack mismatch\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 1686, __PRETTY_FUNCTION__))
1686 "ObjCForCollectionStmt Statement stack mismatch")((isa<ObjCForCollectionStmt>(Stmts.back()) && "ObjCForCollectionStmt Statement stack mismatch"
) ? static_cast<void> (0) : __assert_fail ("isa<ObjCForCollectionStmt>(Stmts.back()) && \"ObjCForCollectionStmt Statement stack mismatch\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 1686, __PRETTY_FUNCTION__))
;
1687 assert(!ObjCBcLabelNo.empty() &&((!ObjCBcLabelNo.empty() && "ObjCForCollectionStmt - Label No stack empty"
) ? static_cast<void> (0) : __assert_fail ("!ObjCBcLabelNo.empty() && \"ObjCForCollectionStmt - Label No stack empty\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 1688, __PRETTY_FUNCTION__))
1688 "ObjCForCollectionStmt - Label No stack empty")((!ObjCBcLabelNo.empty() && "ObjCForCollectionStmt - Label No stack empty"
) ? static_cast<void> (0) : __assert_fail ("!ObjCBcLabelNo.empty() && \"ObjCForCollectionStmt - Label No stack empty\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 1688, __PRETTY_FUNCTION__))
;
1689
1690 SourceLocation startLoc = S->getBeginLoc();
1691 const char *startBuf = SM->getCharacterData(startLoc);
1692 StringRef elementName;
1693 std::string elementTypeAsString;
1694 std::string buf;
1695 // line directive first.
1696 SourceLocation ForEachLoc = S->getForLoc();
1697 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1698 buf += "{\n\t";
1699 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1700 // type elem;
1701 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1702 QualType ElementType = cast<ValueDecl>(D)->getType();
1703 if (ElementType->isObjCQualifiedIdType() ||
1704 ElementType->isObjCQualifiedInterfaceType())
1705 // Simply use 'id' for all qualified types.
1706 elementTypeAsString = "id";
1707 else
1708 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1709 buf += elementTypeAsString;
1710 buf += " ";
1711 elementName = D->getName();
1712 buf += elementName;
1713 buf += ";\n\t";
1714 }
1715 else {
1716 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1717 elementName = DR->getDecl()->getName();
1718 ValueDecl *VD = DR->getDecl();
1719 if (VD->getType()->isObjCQualifiedIdType() ||
1720 VD->getType()->isObjCQualifiedInterfaceType())
1721 // Simply use 'id' for all qualified types.
1722 elementTypeAsString = "id";
1723 else
1724 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1725 }
1726
1727 // struct __objcFastEnumerationState enumState = { 0 };
1728 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1729 // id __rw_items[16];
1730 buf += "id __rw_items[16];\n\t";
1731 // id l_collection = (id)
1732 buf += "id l_collection = (id)";
1733 // Find start location of 'collection' the hard way!
1734 const char *startCollectionBuf = startBuf;
1735 startCollectionBuf += 3; // skip 'for'
1736 startCollectionBuf = strchr(startCollectionBuf, '(');
1737 startCollectionBuf++; // skip '('
1738 // find 'in' and skip it.
1739 while (*startCollectionBuf != ' ' ||
1740 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1741 (*(startCollectionBuf+3) != ' ' &&
1742 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1743 startCollectionBuf++;
1744 startCollectionBuf += 3;
1745
1746 // Replace: "for (type element in" with string constructed thus far.
1747 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1748 // Replace ')' in for '(' type elem in collection ')' with ';'
1749 SourceLocation rightParenLoc = S->getRParenLoc();
1750 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1751 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1752 buf = ";\n\t";
1753
1754 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1755 // objects:__rw_items count:16];
1756 // which is synthesized into:
1757 // NSUInteger limit =
1758 // ((NSUInteger (*)
1759 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1760 // (void *)objc_msgSend)((id)l_collection,
1761 // sel_registerName(
1762 // "countByEnumeratingWithState:objects:count:"),
1763 // (struct __objcFastEnumerationState *)&state,
1764 // (id *)__rw_items, (NSUInteger)16);
1765 buf += "_WIN_NSUInteger limit =\n\t\t";
1766 SynthCountByEnumWithState(buf);
1767 buf += ";\n\t";
1768 /// if (limit) {
1769 /// unsigned long startMutations = *enumState.mutationsPtr;
1770 /// do {
1771 /// unsigned long counter = 0;
1772 /// do {
1773 /// if (startMutations != *enumState.mutationsPtr)
1774 /// objc_enumerationMutation(l_collection);
1775 /// elem = (type)enumState.itemsPtr[counter++];
1776 buf += "if (limit) {\n\t";
1777 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1778 buf += "do {\n\t\t";
1779 buf += "unsigned long counter = 0;\n\t\t";
1780 buf += "do {\n\t\t\t";
1781 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1782 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1783 buf += elementName;
1784 buf += " = (";
1785 buf += elementTypeAsString;
1786 buf += ")enumState.itemsPtr[counter++];";
1787 // Replace ')' in for '(' type elem in collection ')' with all of these.
1788 ReplaceText(lparenLoc, 1, buf);
1789
1790 /// __continue_label: ;
1791 /// } while (counter < limit);
1792 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1793 /// objects:__rw_items count:16]));
1794 /// elem = nil;
1795 /// __break_label: ;
1796 /// }
1797 /// else
1798 /// elem = nil;
1799 /// }
1800 ///
1801 buf = ";\n\t";
1802 buf += "__continue_label_";
1803 buf += utostr(ObjCBcLabelNo.back());
1804 buf += ": ;";
1805 buf += "\n\t\t";
1806 buf += "} while (counter < limit);\n\t";
1807 buf += "} while ((limit = ";
1808 SynthCountByEnumWithState(buf);
1809 buf += "));\n\t";
1810 buf += elementName;
1811 buf += " = ((";
1812 buf += elementTypeAsString;
1813 buf += ")0);\n\t";
1814 buf += "__break_label_";
1815 buf += utostr(ObjCBcLabelNo.back());
1816 buf += ": ;\n\t";
1817 buf += "}\n\t";
1818 buf += "else\n\t\t";
1819 buf += elementName;
1820 buf += " = ((";
1821 buf += elementTypeAsString;
1822 buf += ")0);\n\t";
1823 buf += "}\n";
1824
1825 // Insert all these *after* the statement body.
1826 // FIXME: If this should support Obj-C++, support CXXTryStmt
1827 if (isa<CompoundStmt>(S->getBody())) {
1828 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1829 InsertText(endBodyLoc, buf);
1830 } else {
1831 /* Need to treat single statements specially. For example:
1832 *
1833 * for (A *a in b) if (stuff()) break;
1834 * for (A *a in b) xxxyy;
1835 *
1836 * The following code simply scans ahead to the semi to find the actual end.
1837 */
1838 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1839 const char *semiBuf = strchr(stmtBuf, ';');
1840 assert(semiBuf && "Can't find ';'")((semiBuf && "Can't find ';'") ? static_cast<void>
(0) : __assert_fail ("semiBuf && \"Can't find ';'\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 1840, __PRETTY_FUNCTION__))
;
1841 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1842 InsertText(endBodyLoc, buf);
1843 }
1844 Stmts.pop_back();
1845 ObjCBcLabelNo.pop_back();
1846 return nullptr;
1847}
1848
1849static void Write_RethrowObject(std::string &buf) {
1850 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1851 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1852 buf += "\tid rethrow;\n";
1853 buf += "\t} _fin_force_rethow(_rethrow);";
1854}
1855
1856/// RewriteObjCSynchronizedStmt -
1857/// This routine rewrites @synchronized(expr) stmt;
1858/// into:
1859/// objc_sync_enter(expr);
1860/// @try stmt @finally { objc_sync_exit(expr); }
1861///
1862Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1863 // Get the start location and compute the semi location.
1864 SourceLocation startLoc = S->getBeginLoc();
1865 const char *startBuf = SM->getCharacterData(startLoc);
1866
1867 assert((*startBuf == '@') && "bogus @synchronized location")(((*startBuf == '@') && "bogus @synchronized location"
) ? static_cast<void> (0) : __assert_fail ("(*startBuf == '@') && \"bogus @synchronized location\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 1867, __PRETTY_FUNCTION__))
;
1868
1869 std::string buf;
1870 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1871 ConvertSourceLocationToLineDirective(SynchLoc, buf);
1872 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
1873
1874 const char *lparenBuf = startBuf;
1875 while (*lparenBuf != '(') lparenBuf++;
1876 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1877
1878 buf = "; objc_sync_enter(_sync_obj);\n";
1879 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1880 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1881 buf += "\n\tid sync_exit;";
1882 buf += "\n\t} _sync_exit(_sync_obj);\n";
1883
1884 // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
1885 // the sync expression is typically a message expression that's already
1886 // been rewritten! (which implies the SourceLocation's are invalid).
1887 SourceLocation RParenExprLoc = S->getSynchBody()->getBeginLoc();
1888 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1889 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1890 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1891
1892 SourceLocation LBranceLoc = S->getSynchBody()->getBeginLoc();
1893 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1894 assert (*LBraceLocBuf == '{')((*LBraceLocBuf == '{') ? static_cast<void> (0) : __assert_fail
("*LBraceLocBuf == '{'", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 1894, __PRETTY_FUNCTION__))
;
1895 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
1896
1897 SourceLocation startRBraceLoc = S->getSynchBody()->getEndLoc();
1898 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&(((*SM->getCharacterData(startRBraceLoc) == '}') &&
"bogus @synchronized block") ? static_cast<void> (0) :
__assert_fail ("(*SM->getCharacterData(startRBraceLoc) == '}') && \"bogus @synchronized block\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 1899, __PRETTY_FUNCTION__))
1899 "bogus @synchronized block")(((*SM->getCharacterData(startRBraceLoc) == '}') &&
"bogus @synchronized block") ? static_cast<void> (0) :
__assert_fail ("(*SM->getCharacterData(startRBraceLoc) == '}') && \"bogus @synchronized block\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 1899, __PRETTY_FUNCTION__))
;
1900
1901 buf = "} catch (id e) {_rethrow = e;}\n";
1902 Write_RethrowObject(buf);
1903 buf += "}\n";
1904 buf += "}\n";
1905
1906 ReplaceText(startRBraceLoc, 1, buf);
1907
1908 return nullptr;
1909}
1910
1911void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1912{
1913 // Perform a bottom up traversal of all children.
1914 for (Stmt *SubStmt : S->children())
1915 if (SubStmt)
1916 WarnAboutReturnGotoStmts(SubStmt);
1917
1918 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1919 Diags.Report(Context->getFullLoc(S->getBeginLoc()),
1920 TryFinallyContainsReturnDiag);
1921 }
1922}
1923
1924Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1925 SourceLocation startLoc = S->getAtLoc();
1926 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
1927 ReplaceText(S->getSubStmt()->getBeginLoc(), 1,
1928 "{ __AtAutoreleasePool __autoreleasepool; ");
1929
1930 return nullptr;
1931}
1932
1933Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1934 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
1935 bool noCatch = S->getNumCatchStmts() == 0;
1936 std::string buf;
1937 SourceLocation TryLocation = S->getAtTryLoc();
1938 ConvertSourceLocationToLineDirective(TryLocation, buf);
1939
1940 if (finalStmt) {
1941 if (noCatch)
1942 buf += "{ id volatile _rethrow = 0;\n";
1943 else {
1944 buf += "{ id volatile _rethrow = 0;\ntry {\n";
1945 }
1946 }
1947 // Get the start location and compute the semi location.
1948 SourceLocation startLoc = S->getBeginLoc();
1949 const char *startBuf = SM->getCharacterData(startLoc);
1950
1951 assert((*startBuf == '@') && "bogus @try location")(((*startBuf == '@') && "bogus @try location") ? static_cast
<void> (0) : __assert_fail ("(*startBuf == '@') && \"bogus @try location\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 1951, __PRETTY_FUNCTION__))
;
1952 if (finalStmt)
1953 ReplaceText(startLoc, 1, buf);
1954 else
1955 // @try -> try
1956 ReplaceText(startLoc, 1, "");
1957
1958 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1959 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1960 VarDecl *catchDecl = Catch->getCatchParamDecl();
1961
1962 startLoc = Catch->getBeginLoc();
1963 bool AtRemoved = false;
1964 if (catchDecl) {
1965 QualType t = catchDecl->getType();
1966 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1967 // Should be a pointer to a class.
1968 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1969 if (IDecl) {
1970 std::string Result;
1971 ConvertSourceLocationToLineDirective(Catch->getBeginLoc(), Result);
1972
1973 startBuf = SM->getCharacterData(startLoc);
1974 assert((*startBuf == '@') && "bogus @catch location")(((*startBuf == '@') && "bogus @catch location") ? static_cast
<void> (0) : __assert_fail ("(*startBuf == '@') && \"bogus @catch location\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 1974, __PRETTY_FUNCTION__))
;
1975 SourceLocation rParenLoc = Catch->getRParenLoc();
1976 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1977
1978 // _objc_exc_Foo *_e as argument to catch.
1979 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1980 Result += " *_"; Result += catchDecl->getNameAsString();
1981 Result += ")";
1982 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1983 // Foo *e = (Foo *)_e;
1984 Result.clear();
1985 Result = "{ ";
1986 Result += IDecl->getNameAsString();
1987 Result += " *"; Result += catchDecl->getNameAsString();
1988 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1989 Result += "_"; Result += catchDecl->getNameAsString();
1990
1991 Result += "; ";
1992 SourceLocation lBraceLoc = Catch->getCatchBody()->getBeginLoc();
1993 ReplaceText(lBraceLoc, 1, Result);
1994 AtRemoved = true;
1995 }
1996 }
1997 }
1998 if (!AtRemoved)
1999 // @catch -> catch
2000 ReplaceText(startLoc, 1, "");
2001
2002 }
2003 if (finalStmt) {
2004 buf.clear();
2005 SourceLocation FinallyLoc = finalStmt->getBeginLoc();
2006
2007 if (noCatch) {
2008 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2009 buf += "catch (id e) {_rethrow = e;}\n";
2010 }
2011 else {
2012 buf += "}\n";
2013 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2014 buf += "catch (id e) {_rethrow = e;}\n";
2015 }
2016
2017 SourceLocation startFinalLoc = finalStmt->getBeginLoc();
2018 ReplaceText(startFinalLoc, 8, buf);
2019 Stmt *body = finalStmt->getFinallyBody();
2020 SourceLocation startFinalBodyLoc = body->getBeginLoc();
2021 buf.clear();
2022 Write_RethrowObject(buf);
2023 ReplaceText(startFinalBodyLoc, 1, buf);
2024
2025 SourceLocation endFinalBodyLoc = body->getEndLoc();
2026 ReplaceText(endFinalBodyLoc, 1, "}\n}");
2027 // Now check for any return/continue/go statements within the @try.
2028 WarnAboutReturnGotoStmts(S->getTryBody());
2029 }
2030
2031 return nullptr;
2032}
2033
2034// This can't be done with ReplaceStmt(S, ThrowExpr), since
2035// the throw expression is typically a message expression that's already
2036// been rewritten! (which implies the SourceLocation's are invalid).
2037Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2038 // Get the start location and compute the semi location.
2039 SourceLocation startLoc = S->getBeginLoc();
2040 const char *startBuf = SM->getCharacterData(startLoc);
2041
2042 assert((*startBuf == '@') && "bogus @throw location")(((*startBuf == '@') && "bogus @throw location") ? static_cast
<void> (0) : __assert_fail ("(*startBuf == '@') && \"bogus @throw location\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 2042, __PRETTY_FUNCTION__))
;
2043
2044 std::string buf;
2045 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2046 if (S->getThrowExpr())
2047 buf = "objc_exception_throw(";
2048 else
2049 buf = "throw";
2050
2051 // handle "@ throw" correctly.
2052 const char *wBuf = strchr(startBuf, 'w');
2053 assert((*wBuf == 'w') && "@throw: can't find 'w'")(((*wBuf == 'w') && "@throw: can't find 'w'") ? static_cast
<void> (0) : __assert_fail ("(*wBuf == 'w') && \"@throw: can't find 'w'\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 2053, __PRETTY_FUNCTION__))
;
2054 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2055
2056 SourceLocation endLoc = S->getEndLoc();
2057 const char *endBuf = SM->getCharacterData(endLoc);
2058 const char *semiBuf = strchr(endBuf, ';');
2059 assert((*semiBuf == ';') && "@throw: can't find ';'")(((*semiBuf == ';') && "@throw: can't find ';'") ? static_cast
<void> (0) : __assert_fail ("(*semiBuf == ';') && \"@throw: can't find ';'\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 2059, __PRETTY_FUNCTION__))
;
2060 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
2061 if (S->getThrowExpr())
2062 ReplaceText(semiLoc, 1, ");");
2063 return nullptr;
2064}
2065
2066Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2067 // Create a new string expression.
2068 std::string StrEncoding;
2069 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2070 Expr *Replacement = getStringLiteral(StrEncoding);
2071 ReplaceStmt(Exp, Replacement);
2072
2073 // Replace this subexpr in the parent.
2074 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2075 return Replacement;
2076}
2077
2078Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2079 if (!SelGetUidFunctionDecl)
2080 SynthSelGetUidFunctionDecl();
2081 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl")((SelGetUidFunctionDecl && "Can't find sel_registerName() decl"
) ? static_cast<void> (0) : __assert_fail ("SelGetUidFunctionDecl && \"Can't find sel_registerName() decl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 2081, __PRETTY_FUNCTION__))
;
2082 // Create a call to sel_registerName("selName").
2083 SmallVector<Expr*, 8> SelExprs;
2084 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2085 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2086 SelExprs);
2087 ReplaceStmt(Exp, SelExp);
2088 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2089 return SelExp;
2090}
2091
2092CallExpr *
2093RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2094 ArrayRef<Expr *> Args,
2095 SourceLocation StartLoc,
2096 SourceLocation EndLoc) {
2097 // Get the type, we will need to reference it in a couple spots.
2098 QualType msgSendType = FD->getType();
2099
2100 // Create a reference to the objc_msgSend() declaration.
2101 DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
2102 VK_LValue, SourceLocation());
2103
2104 // Now, we cast the reference to a pointer to the objc_msgSend type.
2105 QualType pToFunc = Context->getPointerType(msgSendType);
2106 ImplicitCastExpr *ICE =
2107 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2108 DRE, nullptr, VK_RValue);
2109
2110 const auto *FT = msgSendType->castAs<FunctionType>();
2111 CallExpr *Exp = CallExpr::Create(
2112 *Context, ICE, Args, FT->getCallResultType(*Context), VK_RValue, EndLoc);
2113 return Exp;
2114}
2115
2116static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2117 const char *&startRef, const char *&endRef) {
2118 while (startBuf < endBuf) {
2119 if (*startBuf == '<')
2120 startRef = startBuf; // mark the start.
2121 if (*startBuf == '>') {
2122 if (startRef && *startRef == '<') {
2123 endRef = startBuf; // mark the end.
2124 return true;
2125 }
2126 return false;
2127 }
2128 startBuf++;
2129 }
2130 return false;
2131}
2132
2133static void scanToNextArgument(const char *&argRef) {
2134 int angle = 0;
2135 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2136 if (*argRef == '<')
2137 angle++;
2138 else if (*argRef == '>')
2139 angle--;
2140 argRef++;
2141 }
2142 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax")((angle == 0 && "scanToNextArgument - bad protocol type syntax"
) ? static_cast<void> (0) : __assert_fail ("angle == 0 && \"scanToNextArgument - bad protocol type syntax\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 2142, __PRETTY_FUNCTION__))
;
2143}
2144
2145bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2146 if (T->isObjCQualifiedIdType())
2147 return true;
2148 if (const PointerType *PT = T->getAs<PointerType>()) {
2149 if (PT->getPointeeType()->isObjCQualifiedIdType())
2150 return true;
2151 }
2152 if (T->isObjCObjectPointerType()) {
2153 T = T->getPointeeType();
2154 return T->isObjCQualifiedInterfaceType();
2155 }
2156 if (T->isArrayType()) {
2157 QualType ElemTy = Context->getBaseElementType(T);
2158 return needToScanForQualifiers(ElemTy);
2159 }
2160 return false;
2161}
2162
2163void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2164 QualType Type = E->getType();
2165 if (needToScanForQualifiers(Type)) {
2166 SourceLocation Loc, EndLoc;
2167
2168 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2169 Loc = ECE->getLParenLoc();
2170 EndLoc = ECE->getRParenLoc();
2171 } else {
2172 Loc = E->getBeginLoc();
2173 EndLoc = E->getEndLoc();
2174 }
2175 // This will defend against trying to rewrite synthesized expressions.
2176 if (Loc.isInvalid() || EndLoc.isInvalid())
2177 return;
2178
2179 const char *startBuf = SM->getCharacterData(Loc);
2180 const char *endBuf = SM->getCharacterData(EndLoc);
2181 const char *startRef = nullptr, *endRef = nullptr;
2182 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2183 // Get the locations of the startRef, endRef.
2184 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2185 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2186 // Comment out the protocol references.
2187 InsertText(LessLoc, "/*");
2188 InsertText(GreaterLoc, "*/");
2189 }
2190 }
2191}
2192
2193void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2194 SourceLocation Loc;
2195 QualType Type;
2196 const FunctionProtoType *proto = nullptr;
2197 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2198 Loc = VD->getLocation();
2199 Type = VD->getType();
2200 }
2201 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2202 Loc = FD->getLocation();
2203 // Check for ObjC 'id' and class types that have been adorned with protocol
2204 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2205 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2206 assert(funcType && "missing function type")((funcType && "missing function type") ? static_cast<
void> (0) : __assert_fail ("funcType && \"missing function type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 2206, __PRETTY_FUNCTION__))
;
2207 proto = dyn_cast<FunctionProtoType>(funcType);
2208 if (!proto)
2209 return;
2210 Type = proto->getReturnType();
2211 }
2212 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2213 Loc = FD->getLocation();
2214 Type = FD->getType();
2215 }
2216 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2217 Loc = TD->getLocation();
2218 Type = TD->getUnderlyingType();
2219 }
2220 else
2221 return;
2222
2223 if (needToScanForQualifiers(Type)) {
2224 // Since types are unique, we need to scan the buffer.
2225
2226 const char *endBuf = SM->getCharacterData(Loc);
2227 const char *startBuf = endBuf;
2228 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2229 startBuf--; // scan backward (from the decl location) for return type.
2230 const char *startRef = nullptr, *endRef = nullptr;
2231 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2232 // Get the locations of the startRef, endRef.
2233 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2234 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2235 // Comment out the protocol references.
2236 InsertText(LessLoc, "/*");
2237 InsertText(GreaterLoc, "*/");
2238 }
2239 }
2240 if (!proto)
2241 return; // most likely, was a variable
2242 // Now check arguments.
2243 const char *startBuf = SM->getCharacterData(Loc);
2244 const char *startFuncBuf = startBuf;
2245 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2246 if (needToScanForQualifiers(proto->getParamType(i))) {
2247 // Since types are unique, we need to scan the buffer.
2248
2249 const char *endBuf = startBuf;
2250 // scan forward (from the decl location) for argument types.
2251 scanToNextArgument(endBuf);
2252 const char *startRef = nullptr, *endRef = nullptr;
2253 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2254 // Get the locations of the startRef, endRef.
2255 SourceLocation LessLoc =
2256 Loc.getLocWithOffset(startRef-startFuncBuf);
2257 SourceLocation GreaterLoc =
2258 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2259 // Comment out the protocol references.
2260 InsertText(LessLoc, "/*");
2261 InsertText(GreaterLoc, "*/");
2262 }
2263 startBuf = ++endBuf;
2264 }
2265 else {
2266 // If the function name is derived from a macro expansion, then the
2267 // argument buffer will not follow the name. Need to speak with Chris.
2268 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2269 startBuf++; // scan forward (from the decl location) for argument types.
2270 startBuf++;
2271 }
2272 }
2273}
2274
2275void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2276 QualType QT = ND->getType();
2277 const Type* TypePtr = QT->getAs<Type>();
2278 if (!isa<TypeOfExprType>(TypePtr))
2279 return;
2280 while (isa<TypeOfExprType>(TypePtr)) {
2281 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2282 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2283 TypePtr = QT->getAs<Type>();
2284 }
2285 // FIXME. This will not work for multiple declarators; as in:
2286 // __typeof__(a) b,c,d;
2287 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2288 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2289 const char *startBuf = SM->getCharacterData(DeclLoc);
2290 if (ND->getInit()) {
2291 std::string Name(ND->getNameAsString());
2292 TypeAsString += " " + Name + " = ";
2293 Expr *E = ND->getInit();
2294 SourceLocation startLoc;
2295 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2296 startLoc = ECE->getLParenLoc();
2297 else
2298 startLoc = E->getBeginLoc();
2299 startLoc = SM->getExpansionLoc(startLoc);
2300 const char *endBuf = SM->getCharacterData(startLoc);
2301 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2302 }
2303 else {
2304 SourceLocation X = ND->getEndLoc();
2305 X = SM->getExpansionLoc(X);
2306 const char *endBuf = SM->getCharacterData(X);
2307 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2308 }
2309}
2310
2311// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2312void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2313 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2314 SmallVector<QualType, 16> ArgTys;
2315 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2316 QualType getFuncType =
2317 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2318 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2319 SourceLocation(),
2320 SourceLocation(),
2321 SelGetUidIdent, getFuncType,
2322 nullptr, SC_Extern);
2323}
2324
2325void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2326 // declared in <objc/objc.h>
2327 if (FD->getIdentifier() &&
2328 FD->getName() == "sel_registerName") {
2329 SelGetUidFunctionDecl = FD;
2330 return;
2331 }
2332 RewriteObjCQualifiedInterfaceTypes(FD);
2333}
2334
2335void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2336 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2337 const char *argPtr = TypeString.c_str();
2338 if (!strchr(argPtr, '^')) {
2339 Str += TypeString;
2340 return;
2341 }
2342 while (*argPtr) {
2343 Str += (*argPtr == '^' ? '*' : *argPtr);
2344 argPtr++;
2345 }
2346}
2347
2348// FIXME. Consolidate this routine with RewriteBlockPointerType.
2349void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2350 ValueDecl *VD) {
2351 QualType Type = VD->getType();
2352 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2353 const char *argPtr = TypeString.c_str();
2354 int paren = 0;
2355 while (*argPtr) {
2356 switch (*argPtr) {
2357 case '(':
2358 Str += *argPtr;
2359 paren++;
2360 break;
2361 case ')':
2362 Str += *argPtr;
2363 paren--;
2364 break;
2365 case '^':
2366 Str += '*';
2367 if (paren == 1)
2368 Str += VD->getNameAsString();
2369 break;
2370 default:
2371 Str += *argPtr;
2372 break;
2373 }
2374 argPtr++;
2375 }
2376}
2377
2378void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2379 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2380 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2381 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2382 if (!proto)
2383 return;
2384 QualType Type = proto->getReturnType();
2385 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2386 FdStr += " ";
2387 FdStr += FD->getName();
2388 FdStr += "(";
2389 unsigned numArgs = proto->getNumParams();
2390 for (unsigned i = 0; i < numArgs; i++) {
2391 QualType ArgType = proto->getParamType(i);
2392 RewriteBlockPointerType(FdStr, ArgType);
2393 if (i+1 < numArgs)
2394 FdStr += ", ";
2395 }
2396 if (FD->isVariadic()) {
2397 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2398 }
2399 else
2400 FdStr += ");\n";
2401 InsertText(FunLocStart, FdStr);
2402}
2403
2404// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2405void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2406 if (SuperConstructorFunctionDecl)
2407 return;
2408 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2409 SmallVector<QualType, 16> ArgTys;
2410 QualType argT = Context->getObjCIdType();
2411 assert(!argT.isNull() && "Can't find 'id' type")((!argT.isNull() && "Can't find 'id' type") ? static_cast
<void> (0) : __assert_fail ("!argT.isNull() && \"Can't find 'id' type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 2411, __PRETTY_FUNCTION__))
;
2412 ArgTys.push_back(argT);
2413 ArgTys.push_back(argT);
2414 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2415 ArgTys);
2416 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2417 SourceLocation(),
2418 SourceLocation(),
2419 msgSendIdent, msgSendType,
2420 nullptr, SC_Extern);
2421}
2422
2423// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2424void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2425 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2426 SmallVector<QualType, 16> ArgTys;
2427 QualType argT = Context->getObjCIdType();
2428 assert(!argT.isNull() && "Can't find 'id' type")((!argT.isNull() && "Can't find 'id' type") ? static_cast
<void> (0) : __assert_fail ("!argT.isNull() && \"Can't find 'id' type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 2428, __PRETTY_FUNCTION__))
;
2429 ArgTys.push_back(argT);
2430 argT = Context->getObjCSelType();
2431 assert(!argT.isNull() && "Can't find 'SEL' type")((!argT.isNull() && "Can't find 'SEL' type") ? static_cast
<void> (0) : __assert_fail ("!argT.isNull() && \"Can't find 'SEL' type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 2431, __PRETTY_FUNCTION__))
;
2432 ArgTys.push_back(argT);
2433 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2434 ArgTys, /*variadic=*/true);
2435 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2436 SourceLocation(),
2437 SourceLocation(),
2438 msgSendIdent, msgSendType, nullptr,
2439 SC_Extern);
2440}
2441
2442// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
2443void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2444 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2445 SmallVector<QualType, 2> ArgTys;
2446 ArgTys.push_back(Context->VoidTy);
2447 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2448 ArgTys, /*variadic=*/true);
2449 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2450 SourceLocation(),
2451 SourceLocation(),
2452 msgSendIdent, msgSendType,
2453 nullptr, SC_Extern);
2454}
2455
2456// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2457void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2458 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2459 SmallVector<QualType, 16> ArgTys;
2460 QualType argT = Context->getObjCIdType();
2461 assert(!argT.isNull() && "Can't find 'id' type")((!argT.isNull() && "Can't find 'id' type") ? static_cast
<void> (0) : __assert_fail ("!argT.isNull() && \"Can't find 'id' type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 2461, __PRETTY_FUNCTION__))
;
2462 ArgTys.push_back(argT);
2463 argT = Context->getObjCSelType();
2464 assert(!argT.isNull() && "Can't find 'SEL' type")((!argT.isNull() && "Can't find 'SEL' type") ? static_cast
<void> (0) : __assert_fail ("!argT.isNull() && \"Can't find 'SEL' type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 2464, __PRETTY_FUNCTION__))
;
2465 ArgTys.push_back(argT);
2466 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2467 ArgTys, /*variadic=*/true);
2468 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2469 SourceLocation(),
2470 SourceLocation(),
2471 msgSendIdent, msgSendType,
2472 nullptr, SC_Extern);
2473}
2474
2475// SynthMsgSendSuperStretFunctionDecl -
2476// id objc_msgSendSuper_stret(void);
2477void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2478 IdentifierInfo *msgSendIdent =
2479 &Context->Idents.get("objc_msgSendSuper_stret");
2480 SmallVector<QualType, 2> ArgTys;
2481 ArgTys.push_back(Context->VoidTy);
2482 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2483 ArgTys, /*variadic=*/true);
2484 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2485 SourceLocation(),
2486 SourceLocation(),
2487 msgSendIdent,
2488 msgSendType, nullptr,
2489 SC_Extern);
2490}
2491
2492// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2493void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2494 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2495 SmallVector<QualType, 16> ArgTys;
2496 QualType argT = Context->getObjCIdType();
2497 assert(!argT.isNull() && "Can't find 'id' type")((!argT.isNull() && "Can't find 'id' type") ? static_cast
<void> (0) : __assert_fail ("!argT.isNull() && \"Can't find 'id' type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 2497, __PRETTY_FUNCTION__))
;
2498 ArgTys.push_back(argT);
2499 argT = Context->getObjCSelType();
2500 assert(!argT.isNull() && "Can't find 'SEL' type")((!argT.isNull() && "Can't find 'SEL' type") ? static_cast
<void> (0) : __assert_fail ("!argT.isNull() && \"Can't find 'SEL' type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 2500, __PRETTY_FUNCTION__))
;
2501 ArgTys.push_back(argT);
2502 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2503 ArgTys, /*variadic=*/true);
2504 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2505 SourceLocation(),
2506 SourceLocation(),
2507 msgSendIdent, msgSendType,
2508 nullptr, SC_Extern);
2509}
2510
2511// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
2512void RewriteModernObjC::SynthGetClassFunctionDecl() {
2513 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2514 SmallVector<QualType, 16> ArgTys;
2515 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2516 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2517 ArgTys);
2518 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2519 SourceLocation(),
2520 SourceLocation(),
2521 getClassIdent, getClassType,
2522 nullptr, SC_Extern);
2523}
2524
2525// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2526void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2527 IdentifierInfo *getSuperClassIdent =
2528 &Context->Idents.get("class_getSuperclass");
2529 SmallVector<QualType, 16> ArgTys;
2530 ArgTys.push_back(Context->getObjCClassType());
2531 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2532 ArgTys);
2533 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2534 SourceLocation(),
2535 SourceLocation(),
2536 getSuperClassIdent,
2537 getClassType, nullptr,
2538 SC_Extern);
2539}
2540
2541// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
2542void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2543 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2544 SmallVector<QualType, 16> ArgTys;
2545 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2546 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2547 ArgTys);
2548 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2549 SourceLocation(),
2550 SourceLocation(),
2551 getClassIdent, getClassType,
2552 nullptr, SC_Extern);
2553}
2554
2555Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2556 assert (Exp != nullptr && "Expected non-null ObjCStringLiteral")((Exp != nullptr && "Expected non-null ObjCStringLiteral"
) ? static_cast<void> (0) : __assert_fail ("Exp != nullptr && \"Expected non-null ObjCStringLiteral\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 2556, __PRETTY_FUNCTION__))
;
2557 QualType strType = getConstantStringStructType();
2558
2559 std::string S = "__NSConstantStringImpl_";
2560
2561 std::string tmpName = InFileName;
2562 unsigned i;
2563 for (i=0; i < tmpName.length(); i++) {
2564 char c = tmpName.at(i);
2565 // replace any non-alphanumeric characters with '_'.
2566 if (!isAlphanumeric(c))
2567 tmpName[i] = '_';
2568 }
2569 S += tmpName;
2570 S += "_";
2571 S += utostr(NumObjCStringLiterals++);
2572
2573 Preamble += "static __NSConstantStringImpl " + S;
2574 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2575 Preamble += "0x000007c8,"; // utf8_str
2576 // The pretty printer for StringLiteral handles escape characters properly.
2577 std::string prettyBufS;
2578 llvm::raw_string_ostream prettyBuf(prettyBufS);
2579 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2580 Preamble += prettyBuf.str();
2581 Preamble += ",";
2582 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2583
2584 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2585 SourceLocation(), &Context->Idents.get(S),
2586 strType, nullptr, SC_Static);
2587 DeclRefExpr *DRE = new (Context)
2588 DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
2589 Expr *Unop = new (Context)
2590 UnaryOperator(DRE, UO_AddrOf, Context->getPointerType(DRE->getType()),
2591 VK_RValue, OK_Ordinary, SourceLocation(), false);
2592 // cast to NSConstantString *
2593 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2594 CK_CPointerToObjCPointerCast, Unop);
2595 ReplaceStmt(Exp, cast);
2596 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2597 return cast;
2598}
2599
2600Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2601 unsigned IntSize =
2602 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2603
2604 Expr *FlagExp = IntegerLiteral::Create(*Context,
2605 llvm::APInt(IntSize, Exp->getValue()),
2606 Context->IntTy, Exp->getLocation());
2607 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2608 CK_BitCast, FlagExp);
2609 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2610 cast);
2611 ReplaceStmt(Exp, PE);
2612 return PE;
2613}
2614
2615Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
2616 // synthesize declaration of helper functions needed in this routine.
2617 if (!SelGetUidFunctionDecl)
2618 SynthSelGetUidFunctionDecl();
2619 // use objc_msgSend() for all.
2620 if (!MsgSendFunctionDecl)
2621 SynthMsgSendFunctionDecl();
2622 if (!GetClassFunctionDecl)
2623 SynthGetClassFunctionDecl();
2624
2625 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2626 SourceLocation StartLoc = Exp->getBeginLoc();
2627 SourceLocation EndLoc = Exp->getEndLoc();
2628
2629 // Synthesize a call to objc_msgSend().
2630 SmallVector<Expr*, 4> MsgExprs;
2631 SmallVector<Expr*, 4> ClsExprs;
2632
2633 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2634 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2635 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
2636
2637 IdentifierInfo *clsName = BoxingClass->getIdentifier();
2638 ClsExprs.push_back(getStringLiteral(clsName->getName()));
2639 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2640 StartLoc, EndLoc);
2641 MsgExprs.push_back(Cls);
2642
2643 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
2644 // it will be the 2nd argument.
2645 SmallVector<Expr*, 4> SelExprs;
2646 SelExprs.push_back(
2647 getStringLiteral(BoxingMethod->getSelector().getAsString()));
2648 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2649 SelExprs, StartLoc, EndLoc);
2650 MsgExprs.push_back(SelExp);
2651
2652 // User provided sub-expression is the 3rd, and last, argument.
2653 Expr *subExpr = Exp->getSubExpr();
2654 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
2655 QualType type = ICE->getType();
2656 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2657 CastKind CK = CK_BitCast;
2658 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2659 CK = CK_IntegralToBoolean;
2660 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
2661 }
2662 MsgExprs.push_back(subExpr);
2663
2664 SmallVector<QualType, 4> ArgTypes;
2665 ArgTypes.push_back(Context->getObjCClassType());
2666 ArgTypes.push_back(Context->getObjCSelType());
2667 for (const auto PI : BoxingMethod->parameters())
2668 ArgTypes.push_back(PI->getType());
2669
2670 QualType returnType = Exp->getType();
2671 // Get the type, we will need to reference it in a couple spots.
2672 QualType msgSendType = MsgSendFlavor->getType();
2673
2674 // Create a reference to the objc_msgSend() declaration.
2675 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2676 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2677
2678 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2679 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2680
2681 // Now do the "normal" pointer to function cast.
2682 QualType castType =
2683 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
2684 castType = Context->getPointerType(castType);
2685 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2686 cast);
2687
2688 // Don't forget the parens to enforce the proper binding.
2689 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2690
2691 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2692 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2693 VK_RValue, EndLoc);
2694 ReplaceStmt(Exp, CE);
2695 return CE;
2696}
2697
2698Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2699 // synthesize declaration of helper functions needed in this routine.
2700 if (!SelGetUidFunctionDecl)
2701 SynthSelGetUidFunctionDecl();
2702 // use objc_msgSend() for all.
2703 if (!MsgSendFunctionDecl)
2704 SynthMsgSendFunctionDecl();
2705 if (!GetClassFunctionDecl)
2706 SynthGetClassFunctionDecl();
2707
2708 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2709 SourceLocation StartLoc = Exp->getBeginLoc();
2710 SourceLocation EndLoc = Exp->getEndLoc();
2711
2712 // Build the expression: __NSContainer_literal(int, ...).arr
2713 QualType IntQT = Context->IntTy;
2714 QualType NSArrayFType =
2715 getSimpleFunctionType(Context->VoidTy, IntQT, true);
2716 std::string NSArrayFName("__NSContainer_literal");
2717 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2718 DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr(
2719 *Context, NSArrayFD, false, NSArrayFType, VK_RValue, SourceLocation());
2720
2721 SmallVector<Expr*, 16> InitExprs;
2722 unsigned NumElements = Exp->getNumElements();
2723 unsigned UnsignedIntSize =
2724 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2725 Expr *count = IntegerLiteral::Create(*Context,
2726 llvm::APInt(UnsignedIntSize, NumElements),
2727 Context->UnsignedIntTy, SourceLocation());
2728 InitExprs.push_back(count);
2729 for (unsigned i = 0; i < NumElements; i++)
2730 InitExprs.push_back(Exp->getElement(i));
2731 Expr *NSArrayCallExpr =
2732 CallExpr::Create(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue,
2733 SourceLocation());
2734
2735 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2736 SourceLocation(),
2737 &Context->Idents.get("arr"),
2738 Context->getPointerType(Context->VoidPtrTy),
2739 nullptr, /*BitWidth=*/nullptr,
2740 /*Mutable=*/true, ICIS_NoInit);
2741 MemberExpr *ArrayLiteralME =
2742 MemberExpr::CreateImplicit(*Context, NSArrayCallExpr, false, ARRFD,
2743 ARRFD->getType(), VK_LValue, OK_Ordinary);
2744 QualType ConstIdT = Context->getObjCIdType().withConst();
2745 CStyleCastExpr * ArrayLiteralObjects =
2746 NoTypeInfoCStyleCastExpr(Context,
2747 Context->getPointerType(ConstIdT),
2748 CK_BitCast,
2749 ArrayLiteralME);
2750
2751 // Synthesize a call to objc_msgSend().
2752 SmallVector<Expr*, 32> MsgExprs;
2753 SmallVector<Expr*, 4> ClsExprs;
2754 QualType expType = Exp->getType();
2755
2756 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2757 ObjCInterfaceDecl *Class =
2758 expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
2759
2760 IdentifierInfo *clsName = Class->getIdentifier();
2761 ClsExprs.push_back(getStringLiteral(clsName->getName()));
2762 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2763 StartLoc, EndLoc);
2764 MsgExprs.push_back(Cls);
2765
2766 // Create a call to sel_registerName("arrayWithObjects:count:").
2767 // it will be the 2nd argument.
2768 SmallVector<Expr*, 4> SelExprs;
2769 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2770 SelExprs.push_back(
2771 getStringLiteral(ArrayMethod->getSelector().getAsString()));
2772 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2773 SelExprs, StartLoc, EndLoc);
2774 MsgExprs.push_back(SelExp);
2775
2776 // (const id [])objects
2777 MsgExprs.push_back(ArrayLiteralObjects);
2778
2779 // (NSUInteger)cnt
2780 Expr *cnt = IntegerLiteral::Create(*Context,
2781 llvm::APInt(UnsignedIntSize, NumElements),
2782 Context->UnsignedIntTy, SourceLocation());
2783 MsgExprs.push_back(cnt);
2784
2785 SmallVector<QualType, 4> ArgTypes;
2786 ArgTypes.push_back(Context->getObjCClassType());
2787 ArgTypes.push_back(Context->getObjCSelType());
2788 for (const auto *PI : ArrayMethod->parameters())
2789 ArgTypes.push_back(PI->getType());
2790
2791 QualType returnType = Exp->getType();
2792 // Get the type, we will need to reference it in a couple spots.
2793 QualType msgSendType = MsgSendFlavor->getType();
2794
2795 // Create a reference to the objc_msgSend() declaration.
2796 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2797 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2798
2799 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2800 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2801
2802 // Now do the "normal" pointer to function cast.
2803 QualType castType =
2804 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
2805 castType = Context->getPointerType(castType);
2806 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2807 cast);
2808
2809 // Don't forget the parens to enforce the proper binding.
2810 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2811
2812 const FunctionType *FT = msgSendType->castAs<FunctionType>();
2813 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2814 VK_RValue, EndLoc);
2815 ReplaceStmt(Exp, CE);
2816 return CE;
2817}
2818
2819Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2820 // synthesize declaration of helper functions needed in this routine.
2821 if (!SelGetUidFunctionDecl)
2822 SynthSelGetUidFunctionDecl();
2823 // use objc_msgSend() for all.
2824 if (!MsgSendFunctionDecl)
2825 SynthMsgSendFunctionDecl();
2826 if (!GetClassFunctionDecl)
2827 SynthGetClassFunctionDecl();
2828
2829 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2830 SourceLocation StartLoc = Exp->getBeginLoc();
2831 SourceLocation EndLoc = Exp->getEndLoc();
2832
2833 // Build the expression: __NSContainer_literal(int, ...).arr
2834 QualType IntQT = Context->IntTy;
2835 QualType NSDictFType =
2836 getSimpleFunctionType(Context->VoidTy, IntQT, true);
2837 std::string NSDictFName("__NSContainer_literal");
2838 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2839 DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr(
2840 *Context, NSDictFD, false, NSDictFType, VK_RValue, SourceLocation());
2841
2842 SmallVector<Expr*, 16> KeyExprs;
2843 SmallVector<Expr*, 16> ValueExprs;
2844
2845 unsigned NumElements = Exp->getNumElements();
2846 unsigned UnsignedIntSize =
2847 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2848 Expr *count = IntegerLiteral::Create(*Context,
2849 llvm::APInt(UnsignedIntSize, NumElements),
2850 Context->UnsignedIntTy, SourceLocation());
2851 KeyExprs.push_back(count);
2852 ValueExprs.push_back(count);
2853 for (unsigned i = 0; i < NumElements; i++) {
2854 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2855 KeyExprs.push_back(Element.Key);
2856 ValueExprs.push_back(Element.Value);
2857 }
2858
2859 // (const id [])objects
2860 Expr *NSValueCallExpr =
2861 CallExpr::Create(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue,
2862 SourceLocation());
2863
2864 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2865 SourceLocation(),
2866 &Context->Idents.get("arr"),
2867 Context->getPointerType(Context->VoidPtrTy),
2868 nullptr, /*BitWidth=*/nullptr,
2869 /*Mutable=*/true, ICIS_NoInit);
2870 MemberExpr *DictLiteralValueME =
2871 MemberExpr::CreateImplicit(*Context, NSValueCallExpr, false, ARRFD,
2872 ARRFD->getType(), VK_LValue, OK_Ordinary);
2873 QualType ConstIdT = Context->getObjCIdType().withConst();
2874 CStyleCastExpr * DictValueObjects =
2875 NoTypeInfoCStyleCastExpr(Context,
2876 Context->getPointerType(ConstIdT),
2877 CK_BitCast,
2878 DictLiteralValueME);
2879 // (const id <NSCopying> [])keys
2880 Expr *NSKeyCallExpr = CallExpr::Create(
2881 *Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue, SourceLocation());
2882
2883 MemberExpr *DictLiteralKeyME =
2884 MemberExpr::CreateImplicit(*Context, NSKeyCallExpr, false, ARRFD,
2885 ARRFD->getType(), VK_LValue, OK_Ordinary);
2886
2887 CStyleCastExpr * DictKeyObjects =
2888 NoTypeInfoCStyleCastExpr(Context,
2889 Context->getPointerType(ConstIdT),
2890 CK_BitCast,
2891 DictLiteralKeyME);
2892
2893 // Synthesize a call to objc_msgSend().
2894 SmallVector<Expr*, 32> MsgExprs;
2895 SmallVector<Expr*, 4> ClsExprs;
2896 QualType expType = Exp->getType();
2897
2898 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2899 ObjCInterfaceDecl *Class =
2900 expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
2901
2902 IdentifierInfo *clsName = Class->getIdentifier();
2903 ClsExprs.push_back(getStringLiteral(clsName->getName()));
2904 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2905 StartLoc, EndLoc);
2906 MsgExprs.push_back(Cls);
2907
2908 // Create a call to sel_registerName("arrayWithObjects:count:").
2909 // it will be the 2nd argument.
2910 SmallVector<Expr*, 4> SelExprs;
2911 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2912 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
2913 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2914 SelExprs, StartLoc, EndLoc);
2915 MsgExprs.push_back(SelExp);
2916
2917 // (const id [])objects
2918 MsgExprs.push_back(DictValueObjects);
2919
2920 // (const id <NSCopying> [])keys
2921 MsgExprs.push_back(DictKeyObjects);
2922
2923 // (NSUInteger)cnt
2924 Expr *cnt = IntegerLiteral::Create(*Context,
2925 llvm::APInt(UnsignedIntSize, NumElements),
2926 Context->UnsignedIntTy, SourceLocation());
2927 MsgExprs.push_back(cnt);
2928
2929 SmallVector<QualType, 8> ArgTypes;
2930 ArgTypes.push_back(Context->getObjCClassType());
2931 ArgTypes.push_back(Context->getObjCSelType());
2932 for (const auto *PI : DictMethod->parameters()) {
2933 QualType T = PI->getType();
2934 if (const PointerType* PT = T->getAs<PointerType>()) {
2935 QualType PointeeTy = PT->getPointeeType();
2936 convertToUnqualifiedObjCType(PointeeTy);
2937 T = Context->getPointerType(PointeeTy);
2938 }
2939 ArgTypes.push_back(T);
2940 }
2941
2942 QualType returnType = Exp->getType();
2943 // Get the type, we will need to reference it in a couple spots.
2944 QualType msgSendType = MsgSendFlavor->getType();
2945
2946 // Create a reference to the objc_msgSend() declaration.
2947 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2948 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2949
2950 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2951 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2952
2953 // Now do the "normal" pointer to function cast.
2954 QualType castType =
2955 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
2956 castType = Context->getPointerType(castType);
2957 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2958 cast);
2959
2960 // Don't forget the parens to enforce the proper binding.
2961 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2962
2963 const FunctionType *FT = msgSendType->castAs<FunctionType>();
2964 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2965 VK_RValue, EndLoc);
2966 ReplaceStmt(Exp, CE);
2967 return CE;
2968}
2969
2970// struct __rw_objc_super {
2971// struct objc_object *object; struct objc_object *superClass;
2972// };
2973QualType RewriteModernObjC::getSuperStructType() {
2974 if (!SuperStructDecl) {
2975 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2976 SourceLocation(), SourceLocation(),
2977 &Context->Idents.get("__rw_objc_super"));
2978 QualType FieldTypes[2];
2979
2980 // struct objc_object *object;
2981 FieldTypes[0] = Context->getObjCIdType();
2982 // struct objc_object *superClass;
2983 FieldTypes[1] = Context->getObjCIdType();
2984
2985 // Create fields
2986 for (unsigned i = 0; i < 2; ++i) {
2987 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2988 SourceLocation(),
2989 SourceLocation(), nullptr,
2990 FieldTypes[i], nullptr,
2991 /*BitWidth=*/nullptr,
2992 /*Mutable=*/false,
2993 ICIS_NoInit));
2994 }
2995
2996 SuperStructDecl->completeDefinition();
2997 }
2998 return Context->getTagDeclType(SuperStructDecl);
2999}
3000
3001QualType RewriteModernObjC::getConstantStringStructType() {
3002 if (!ConstantStringDecl) {
3003 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3004 SourceLocation(), SourceLocation(),
3005 &Context->Idents.get("__NSConstantStringImpl"));
3006 QualType FieldTypes[4];
3007
3008 // struct objc_object *receiver;
3009 FieldTypes[0] = Context->getObjCIdType();
3010 // int flags;
3011 FieldTypes[1] = Context->IntTy;
3012 // char *str;
3013 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3014 // long length;
3015 FieldTypes[3] = Context->LongTy;
3016
3017 // Create fields
3018 for (unsigned i = 0; i < 4; ++i) {
3019 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3020 ConstantStringDecl,
3021 SourceLocation(),
3022 SourceLocation(), nullptr,
3023 FieldTypes[i], nullptr,
3024 /*BitWidth=*/nullptr,
3025 /*Mutable=*/true,
3026 ICIS_NoInit));
3027 }
3028
3029 ConstantStringDecl->completeDefinition();
3030 }
3031 return Context->getTagDeclType(ConstantStringDecl);
3032}
3033
3034/// getFunctionSourceLocation - returns start location of a function
3035/// definition. Complication arises when function has declared as
3036/// extern "C" or extern "C" {...}
3037static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3038 FunctionDecl *FD) {
3039 if (FD->isExternC() && !FD->isMain()) {
3040 const DeclContext *DC = FD->getDeclContext();
3041 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3042 // if it is extern "C" {...}, return function decl's own location.
3043 if (!LSD->getRBraceLoc().isValid())
3044 return LSD->getExternLoc();
3045 }
3046 if (FD->getStorageClass() != SC_None)
3047 R.RewriteBlockLiteralFunctionDecl(FD);
3048 return FD->getTypeSpecStartLoc();
3049}
3050
3051void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3052
3053 SourceLocation Location = D->getLocation();
3054
3055 if (Location.isFileID() && GenerateLineInfo) {
3056 std::string LineString("\n#line ");
3057 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3058 LineString += utostr(PLoc.getLine());
3059 LineString += " \"";
3060 LineString += Lexer::Stringify(PLoc.getFilename());
3061 if (isa<ObjCMethodDecl>(D))
3062 LineString += "\"";
3063 else LineString += "\"\n";
3064
3065 Location = D->getBeginLoc();
3066 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3067 if (FD->isExternC() && !FD->isMain()) {
3068 const DeclContext *DC = FD->getDeclContext();
3069 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3070 // if it is extern "C" {...}, return function decl's own location.
3071 if (!LSD->getRBraceLoc().isValid())
3072 Location = LSD->getExternLoc();
3073 }
3074 }
3075 InsertText(Location, LineString);
3076 }
3077}
3078
3079/// SynthMsgSendStretCallExpr - This routine translates message expression
3080/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3081/// nil check on receiver must be performed before calling objc_msgSend_stret.
3082/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3083/// msgSendType - function type of objc_msgSend_stret(...)
3084/// returnType - Result type of the method being synthesized.
3085/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3086/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3087/// starting with receiver.
3088/// Method - Method being rewritten.
3089Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3090 QualType returnType,
3091 SmallVectorImpl<QualType> &ArgTypes,
3092 SmallVectorImpl<Expr*> &MsgExprs,
3093 ObjCMethodDecl *Method) {
3094 // Now do the "normal" pointer to function cast.
3095 QualType FuncType = getSimpleFunctionType(
3096 returnType, ArgTypes, Method ? Method->isVariadic() : false);
3097 QualType castType = Context->getPointerType(FuncType);
3098
3099 // build type for containing the objc_msgSend_stret object.
3100 static unsigned stretCount=0;
3101 std::string name = "__Stret"; name += utostr(stretCount);
3102 std::string str =
3103 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3104 str += "namespace {\n";
3105 str += "struct "; str += name;
3106 str += " {\n\t";
3107 str += name;
3108 str += "(id receiver, SEL sel";
3109 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3110 std::string ArgName = "arg"; ArgName += utostr(i);
3111 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3112 str += ", "; str += ArgName;
3113 }
3114 // could be vararg.
3115 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3116 std::string ArgName = "arg"; ArgName += utostr(i);
3117 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3118 Context->getPrintingPolicy());
3119 str += ", "; str += ArgName;
3120 }
3121
3122 str += ") {\n";
3123 str += "\t unsigned size = sizeof(";
3124 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3125
3126 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3127
3128 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3129 str += ")(void *)objc_msgSend)(receiver, sel";
3130 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3131 str += ", arg"; str += utostr(i);
3132 }
3133 // could be vararg.
3134 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3135 str += ", arg"; str += utostr(i);
3136 }
3137 str+= ");\n";
3138
3139 str += "\t else if (receiver == 0)\n";
3140 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3141 str += "\t else\n";
3142
3143 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3144 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3145 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3146 str += ", arg"; str += utostr(i);
3147 }
3148 // could be vararg.
3149 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3150 str += ", arg"; str += utostr(i);
3151 }
3152 str += ");\n";
3153
3154 str += "\t}\n";
3155 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3156 str += " s;\n";
3157 str += "};\n};\n\n";
3158 SourceLocation FunLocStart;
3159 if (CurFunctionDef)
3160 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3161 else {
3162 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null")((CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null"
) ? static_cast<void> (0) : __assert_fail ("CurMethodDef && \"SynthMsgSendStretCallExpr - CurMethodDef is null\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 3162, __PRETTY_FUNCTION__))
;
3163 FunLocStart = CurMethodDef->getBeginLoc();
3164 }
3165
3166 InsertText(FunLocStart, str);
3167 ++stretCount;
3168
3169 // AST for __Stretn(receiver, args).s;
3170 IdentifierInfo *ID = &Context->Idents.get(name);
3171 FunctionDecl *FD =
3172 FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(),
3173 ID, FuncType, nullptr, SC_Extern, false, false);
3174 DeclRefExpr *DRE = new (Context)
3175 DeclRefExpr(*Context, FD, false, castType, VK_RValue, SourceLocation());
3176 CallExpr *STCE = CallExpr::Create(*Context, DRE, MsgExprs, castType,
3177 VK_LValue, SourceLocation());
3178
3179 FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3180 SourceLocation(),
3181 &Context->Idents.get("s"),
3182 returnType, nullptr,
3183 /*BitWidth=*/nullptr,
3184 /*Mutable=*/true, ICIS_NoInit);
3185 MemberExpr *ME = MemberExpr::CreateImplicit(
3186 *Context, STCE, false, FieldD, FieldD->getType(), VK_LValue, OK_Ordinary);
3187
3188 return ME;
3189}
3190
3191Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3192 SourceLocation StartLoc,
3193 SourceLocation EndLoc) {
3194 if (!SelGetUidFunctionDecl)
3195 SynthSelGetUidFunctionDecl();
3196 if (!MsgSendFunctionDecl)
3197 SynthMsgSendFunctionDecl();
3198 if (!MsgSendSuperFunctionDecl)
3199 SynthMsgSendSuperFunctionDecl();
3200 if (!MsgSendStretFunctionDecl)
3201 SynthMsgSendStretFunctionDecl();
3202 if (!MsgSendSuperStretFunctionDecl)
3203 SynthMsgSendSuperStretFunctionDecl();
3204 if (!MsgSendFpretFunctionDecl)
3205 SynthMsgSendFpretFunctionDecl();
3206 if (!GetClassFunctionDecl)
3207 SynthGetClassFunctionDecl();
3208 if (!GetSuperClassFunctionDecl)
3209 SynthGetSuperClassFunctionDecl();
3210 if (!GetMetaClassFunctionDecl)
3211 SynthGetMetaClassFunctionDecl();
3212
3213 // default to objc_msgSend().
3214 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3215 // May need to use objc_msgSend_stret() as well.
3216 FunctionDecl *MsgSendStretFlavor = nullptr;
3217 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3218 QualType resultType = mDecl->getReturnType();
3219 if (resultType->isRecordType())
3220 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3221 else if (resultType->isRealFloatingType())
3222 MsgSendFlavor = MsgSendFpretFunctionDecl;
3223 }
3224
3225 // Synthesize a call to objc_msgSend().
3226 SmallVector<Expr*, 8> MsgExprs;
3227 switch (Exp->getReceiverKind()) {
3228 case ObjCMessageExpr::SuperClass: {
3229 MsgSendFlavor = MsgSendSuperFunctionDecl;
3230 if (MsgSendStretFlavor)
3231 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3232 assert(MsgSendFlavor && "MsgSendFlavor is NULL!")((MsgSendFlavor && "MsgSendFlavor is NULL!") ? static_cast
<void> (0) : __assert_fail ("MsgSendFlavor && \"MsgSendFlavor is NULL!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 3232, __PRETTY_FUNCTION__))
;
3233
3234 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3235
3236 SmallVector<Expr*, 4> InitExprs;
3237
3238 // set the receiver to self, the first argument to all methods.
3239 InitExprs.push_back(
3240 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3241 CK_BitCast,
3242 new (Context) DeclRefExpr(*Context,
3243 CurMethodDef->getSelfDecl(),
3244 false,
3245 Context->getObjCIdType(),
3246 VK_RValue,
3247 SourceLocation()))
3248 ); // set the 'receiver'.
3249
3250 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3251 SmallVector<Expr*, 8> ClsExprs;
3252 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3253 // (Class)objc_getClass("CurrentClass")
3254 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3255 ClsExprs, StartLoc, EndLoc);
3256 ClsExprs.clear();
3257 ClsExprs.push_back(Cls);
3258 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3259 StartLoc, EndLoc);
3260
3261 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3262 // To turn off a warning, type-cast to 'id'
3263 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3264 NoTypeInfoCStyleCastExpr(Context,
3265 Context->getObjCIdType(),
3266 CK_BitCast, Cls));
3267 // struct __rw_objc_super
3268 QualType superType = getSuperStructType();
3269 Expr *SuperRep;
3270
3271 if (LangOpts.MicrosoftExt) {
3272 SynthSuperConstructorFunctionDecl();
3273 // Simulate a constructor call...
3274 DeclRefExpr *DRE = new (Context)
3275 DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3276 VK_LValue, SourceLocation());
3277 SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
3278 VK_LValue, SourceLocation());
3279 // The code for super is a little tricky to prevent collision with
3280 // the structure definition in the header. The rewriter has it's own
3281 // internal definition (__rw_objc_super) that is uses. This is why
3282 // we need the cast below. For example:
3283 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3284 //
3285 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3286 Context->getPointerType(SuperRep->getType()),
3287 VK_RValue, OK_Ordinary,
3288 SourceLocation(), false);
3289 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3290 Context->getPointerType(superType),
3291 CK_BitCast, SuperRep);
3292 } else {
3293 // (struct __rw_objc_super) { <exprs from above> }
3294 InitListExpr *ILE =
3295 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3296 SourceLocation());
3297 TypeSourceInfo *superTInfo
3298 = Context->getTrivialTypeSourceInfo(superType);
3299 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3300 superType, VK_LValue,
3301 ILE, false);
3302 // struct __rw_objc_super *
3303 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3304 Context->getPointerType(SuperRep->getType()),
3305 VK_RValue, OK_Ordinary,
3306 SourceLocation(), false);
3307 }
3308 MsgExprs.push_back(SuperRep);
3309 break;
3310 }
3311
3312 case ObjCMessageExpr::Class: {
3313 SmallVector<Expr*, 8> ClsExprs;
3314 ObjCInterfaceDecl *Class
3315 = Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
3316 IdentifierInfo *clsName = Class->getIdentifier();
3317 ClsExprs.push_back(getStringLiteral(clsName->getName()));
3318 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3319 StartLoc, EndLoc);
3320 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3321 Context->getObjCIdType(),
3322 CK_BitCast, Cls);
3323 MsgExprs.push_back(ArgExpr);
3324 break;
3325 }
3326
3327 case ObjCMessageExpr::SuperInstance:{
3328 MsgSendFlavor = MsgSendSuperFunctionDecl;
3329 if (MsgSendStretFlavor)
3330 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3331 assert(MsgSendFlavor && "MsgSendFlavor is NULL!")((MsgSendFlavor && "MsgSendFlavor is NULL!") ? static_cast
<void> (0) : __assert_fail ("MsgSendFlavor && \"MsgSendFlavor is NULL!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 3331, __PRETTY_FUNCTION__))
;
3332 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3333 SmallVector<Expr*, 4> InitExprs;
3334
3335 InitExprs.push_back(
3336 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3337 CK_BitCast,
3338 new (Context) DeclRefExpr(*Context,
3339 CurMethodDef->getSelfDecl(),
3340 false,
3341 Context->getObjCIdType(),
3342 VK_RValue, SourceLocation()))
3343 ); // set the 'receiver'.
3344
3345 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3346 SmallVector<Expr*, 8> ClsExprs;
3347 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3348 // (Class)objc_getClass("CurrentClass")
3349 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3350 StartLoc, EndLoc);
3351 ClsExprs.clear();
3352 ClsExprs.push_back(Cls);
3353 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3354 StartLoc, EndLoc);
3355
3356 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3357 // To turn off a warning, type-cast to 'id'
3358 InitExprs.push_back(
3359 // set 'super class', using class_getSuperclass().
3360 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3361 CK_BitCast, Cls));
3362 // struct __rw_objc_super
3363 QualType superType = getSuperStructType();
3364 Expr *SuperRep;
3365
3366 if (LangOpts.MicrosoftExt) {
3367 SynthSuperConstructorFunctionDecl();
3368 // Simulate a constructor call...
3369 DeclRefExpr *DRE = new (Context)
3370 DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3371 VK_LValue, SourceLocation());
3372 SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
3373 VK_LValue, SourceLocation());
3374 // The code for super is a little tricky to prevent collision with
3375 // the structure definition in the header. The rewriter has it's own
3376 // internal definition (__rw_objc_super) that is uses. This is why
3377 // we need the cast below. For example:
3378 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3379 //
3380 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3381 Context->getPointerType(SuperRep->getType()),
3382 VK_RValue, OK_Ordinary,
3383 SourceLocation(), false);
3384 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3385 Context->getPointerType(superType),
3386 CK_BitCast, SuperRep);
3387 } else {
3388 // (struct __rw_objc_super) { <exprs from above> }
3389 InitListExpr *ILE =
3390 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3391 SourceLocation());
3392 TypeSourceInfo *superTInfo
3393 = Context->getTrivialTypeSourceInfo(superType);
3394 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3395 superType, VK_RValue, ILE,
3396 false);
3397 }
3398 MsgExprs.push_back(SuperRep);
3399 break;
3400 }
3401
3402 case ObjCMessageExpr::Instance: {
3403 // Remove all type-casts because it may contain objc-style types; e.g.
3404 // Foo<Proto> *.
3405 Expr *recExpr = Exp->getInstanceReceiver();
3406 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3407 recExpr = CE->getSubExpr();
3408 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3409 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3410 ? CK_BlockPointerToObjCPointerCast
3411 : CK_CPointerToObjCPointerCast;
3412
3413 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3414 CK, recExpr);
3415 MsgExprs.push_back(recExpr);
3416 break;
3417 }
3418 }
3419
3420 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3421 SmallVector<Expr*, 8> SelExprs;
3422 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
3423 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3424 SelExprs, StartLoc, EndLoc);
3425 MsgExprs.push_back(SelExp);
3426
3427 // Now push any user supplied arguments.
3428 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3429 Expr *userExpr = Exp->getArg(i);
3430 // Make all implicit casts explicit...ICE comes in handy:-)
3431 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3432 // Reuse the ICE type, it is exactly what the doctor ordered.
3433 QualType type = ICE->getType();
3434 if (needToScanForQualifiers(type))
3435 type = Context->getObjCIdType();
3436 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3437 (void)convertBlockPointerToFunctionPointer(type);
3438 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3439 CastKind CK;
3440 if (SubExpr->getType()->isIntegralType(*Context) &&
3441 type->isBooleanType()) {
3442 CK = CK_IntegralToBoolean;
3443 } else if (type->isObjCObjectPointerType()) {
3444 if (SubExpr->getType()->isBlockPointerType()) {
3445 CK = CK_BlockPointerToObjCPointerCast;
3446 } else if (SubExpr->getType()->isPointerType()) {
3447 CK = CK_CPointerToObjCPointerCast;
3448 } else {
3449 CK = CK_BitCast;
3450 }
3451 } else {
3452 CK = CK_BitCast;
3453 }
3454
3455 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3456 }
3457 // Make id<P...> cast into an 'id' cast.
3458 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3459 if (CE->getType()->isObjCQualifiedIdType()) {
3460 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3461 userExpr = CE->getSubExpr();
3462 CastKind CK;
3463 if (userExpr->getType()->isIntegralType(*Context)) {
3464 CK = CK_IntegralToPointer;
3465 } else if (userExpr->getType()->isBlockPointerType()) {
3466 CK = CK_BlockPointerToObjCPointerCast;
3467 } else if (userExpr->getType()->isPointerType()) {
3468 CK = CK_CPointerToObjCPointerCast;
3469 } else {
3470 CK = CK_BitCast;
3471 }
3472 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3473 CK, userExpr);
3474 }
3475 }
3476 MsgExprs.push_back(userExpr);
3477 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3478 // out the argument in the original expression (since we aren't deleting
3479 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3480 //Exp->setArg(i, 0);
3481 }
3482 // Generate the funky cast.
3483 CastExpr *cast;
3484 SmallVector<QualType, 8> ArgTypes;
3485 QualType returnType;
3486
3487 // Push 'id' and 'SEL', the 2 implicit arguments.
3488 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3489 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3490 else
3491 ArgTypes.push_back(Context->getObjCIdType());
3492 ArgTypes.push_back(Context->getObjCSelType());
3493 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3494 // Push any user argument types.
3495 for (const auto *PI : OMD->parameters()) {
3496 QualType t = PI->getType()->isObjCQualifiedIdType()
3497 ? Context->getObjCIdType()
3498 : PI->getType();
3499 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3500 (void)convertBlockPointerToFunctionPointer(t);
3501 ArgTypes.push_back(t);
3502 }
3503 returnType = Exp->getType();
3504 convertToUnqualifiedObjCType(returnType);
3505 (void)convertBlockPointerToFunctionPointer(returnType);
3506 } else {
3507 returnType = Context->getObjCIdType();
3508 }
3509 // Get the type, we will need to reference it in a couple spots.
3510 QualType msgSendType = MsgSendFlavor->getType();
3511
3512 // Create a reference to the objc_msgSend() declaration.
3513 DeclRefExpr *DRE = new (Context) DeclRefExpr(
3514 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
3515
3516 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3517 // If we don't do this cast, we get the following bizarre warning/note:
3518 // xx.m:13: warning: function called through a non-compatible type
3519 // xx.m:13: note: if this code is reached, the program will abort
3520 cast = NoTypeInfoCStyleCastExpr(Context,
3521 Context->getPointerType(Context->VoidTy),
3522 CK_BitCast, DRE);
3523
3524 // Now do the "normal" pointer to function cast.
3525 // If we don't have a method decl, force a variadic cast.
3526 const ObjCMethodDecl *MD = Exp->getMethodDecl();
3527 QualType castType =
3528 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
3529 castType = Context->getPointerType(castType);
3530 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3531 cast);
3532
3533 // Don't forget the parens to enforce the proper binding.
3534 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3535
3536 const FunctionType *FT = msgSendType->castAs<FunctionType>();
3537 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
3538 VK_RValue, EndLoc);
3539 Stmt *ReplacingStmt = CE;
3540 if (MsgSendStretFlavor) {
3541 // We have the method which returns a struct/union. Must also generate
3542 // call to objc_msgSend_stret and hang both varieties on a conditional
3543 // expression which dictate which one to envoke depending on size of
3544 // method's return type.
3545
3546 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3547 returnType,
3548 ArgTypes, MsgExprs,
3549 Exp->getMethodDecl());
3550 ReplacingStmt = STCE;
3551 }
3552 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3553 return ReplacingStmt;
3554}
3555
3556Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3557 Stmt *ReplacingStmt =
3558 SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
3559
3560 // Now do the actual rewrite.
3561 ReplaceStmt(Exp, ReplacingStmt);
3562
3563 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3564 return ReplacingStmt;
3565}
3566
3567// typedef struct objc_object Protocol;
3568QualType RewriteModernObjC::getProtocolType() {
3569 if (!ProtocolTypeDecl) {
3570 TypeSourceInfo *TInfo
3571 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3572 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3573 SourceLocation(), SourceLocation(),
3574 &Context->Idents.get("Protocol"),
3575 TInfo);
3576 }
3577 return Context->getTypeDeclType(ProtocolTypeDecl);
3578}
3579
3580/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3581/// a synthesized/forward data reference (to the protocol's metadata).
3582/// The forward references (and metadata) are generated in
3583/// RewriteModernObjC::HandleTranslationUnit().
3584Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3585 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3586 Exp->getProtocol()->getNameAsString();
3587 IdentifierInfo *ID = &Context->Idents.get(Name);
3588 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3589 SourceLocation(), ID, getProtocolType(),
3590 nullptr, SC_Extern);
3591 DeclRefExpr *DRE = new (Context) DeclRefExpr(
3592 *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3593 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(
3594 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
3595 ReplaceStmt(Exp, castExpr);
3596 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3597 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3598 return castExpr;
3599}
3600
3601/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3602/// is defined inside an objective-c class. If so, it returns true.
3603bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
3604 TagDecl *Tag,
3605 bool &IsNamedDefinition) {
3606 if (!IDecl)
3607 return false;
3608 SourceLocation TagLocation;
3609 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3610 RD = RD->getDefinition();
3611 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
3612 return false;
3613 IsNamedDefinition = true;
3614 TagLocation = RD->getLocation();
3615 return Context->getSourceManager().isBeforeInTranslationUnit(
3616 IDecl->getLocation(), TagLocation);
3617 }
3618 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3619 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3620 return false;
3621 IsNamedDefinition = true;
3622 TagLocation = ED->getLocation();
3623 return Context->getSourceManager().isBeforeInTranslationUnit(
3624 IDecl->getLocation(), TagLocation);
3625 }
3626 return false;
3627}
3628
3629/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
3630/// It handles elaborated types, as well as enum types in the process.
3631bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3632 std::string &Result) {
3633 if (isa<TypedefType>(Type)) {
3634 Result += "\t";
3635 return false;
3636 }
3637
3638 if (Type->isArrayType()) {
3639 QualType ElemTy = Context->getBaseElementType(Type);
3640 return RewriteObjCFieldDeclType(ElemTy, Result);
3641 }
3642 else if (Type->isRecordType()) {
3643 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
3644 if (RD->isCompleteDefinition()) {
3645 if (RD->isStruct())
3646 Result += "\n\tstruct ";
3647 else if (RD->isUnion())
3648 Result += "\n\tunion ";
3649 else
3650 assert(false && "class not allowed as an ivar type")((false && "class not allowed as an ivar type") ? static_cast
<void> (0) : __assert_fail ("false && \"class not allowed as an ivar type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 3650, __PRETTY_FUNCTION__))
;
3651
3652 Result += RD->getName();
3653 if (GlobalDefinedTags.count(RD)) {
3654 // struct/union is defined globally, use it.
3655 Result += " ";
3656 return true;
3657 }
3658 Result += " {\n";
3659 for (auto *FD : RD->fields())
3660 RewriteObjCFieldDecl(FD, Result);
3661 Result += "\t} ";
3662 return true;
3663 }
3664 }
3665 else if (Type->isEnumeralType()) {
3666 EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
3667 if (ED->isCompleteDefinition()) {
3668 Result += "\n\tenum ";
3669 Result += ED->getName();
3670 if (GlobalDefinedTags.count(ED)) {
3671 // Enum is globall defined, use it.
3672 Result += " ";
3673 return true;
3674 }
3675
3676 Result += " {\n";
3677 for (const auto *EC : ED->enumerators()) {
3678 Result += "\t"; Result += EC->getName(); Result += " = ";
3679 llvm::APSInt Val = EC->getInitVal();
3680 Result += Val.toString(10);
3681 Result += ",\n";
3682 }
3683 Result += "\t} ";
3684 return true;
3685 }
3686 }
3687
3688 Result += "\t";
3689 convertObjCTypeToCStyleType(Type);
3690 return false;
3691}
3692
3693
3694/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3695/// It handles elaborated types, as well as enum types in the process.
3696void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3697 std::string &Result) {
3698 QualType Type = fieldDecl->getType();
3699 std::string Name = fieldDecl->getNameAsString();
3700
3701 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3702 if (!EleboratedType)
3703 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3704 Result += Name;
3705 if (fieldDecl->isBitField()) {
3706 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3707 }
3708 else if (EleboratedType && Type->isArrayType()) {
3709 const ArrayType *AT = Context->getAsArrayType(Type);
3710 do {
3711 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3712 Result += "[";
3713 llvm::APInt Dim = CAT->getSize();
3714 Result += utostr(Dim.getZExtValue());
3715 Result += "]";
3716 }
3717 AT = Context->getAsArrayType(AT->getElementType());
3718 } while (AT);
3719 }
3720
3721 Result += ";\n";
3722}
3723
3724/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3725/// named aggregate types into the input buffer.
3726void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3727 std::string &Result) {
3728 QualType Type = fieldDecl->getType();
3729 if (isa<TypedefType>(Type))
3730 return;
3731 if (Type->isArrayType())
3732 Type = Context->getBaseElementType(Type);
3733
3734 auto *IDecl = dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
3735
3736 TagDecl *TD = nullptr;
3737 if (Type->isRecordType()) {
3738 TD = Type->castAs<RecordType>()->getDecl();
3739 }
3740 else if (Type->isEnumeralType()) {
3741 TD = Type->castAs<EnumType>()->getDecl();
3742 }
3743
3744 if (TD) {
3745 if (GlobalDefinedTags.count(TD))
3746 return;
3747
3748 bool IsNamedDefinition = false;
3749 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3750 RewriteObjCFieldDeclType(Type, Result);
3751 Result += ";";
3752 }
3753 if (IsNamedDefinition)
3754 GlobalDefinedTags.insert(TD);
3755 }
3756}
3757
3758unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3759 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3760 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3761 return IvarGroupNumber[IV];
3762 }
3763 unsigned GroupNo = 0;
3764 SmallVector<const ObjCIvarDecl *, 8> IVars;
3765 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3766 IVD; IVD = IVD->getNextIvar())
3767 IVars.push_back(IVD);
3768
3769 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3770 if (IVars[i]->isBitField()) {
3771 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3772 while (i < e && IVars[i]->isBitField())
3773 IvarGroupNumber[IVars[i++]] = GroupNo;
3774 if (i < e)
3775 --i;
3776 }
3777
3778 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3779 return IvarGroupNumber[IV];
3780}
3781
3782QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3783 ObjCIvarDecl *IV,
3784 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3785 std::string StructTagName;
3786 ObjCIvarBitfieldGroupType(IV, StructTagName);
3787 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3788 Context->getTranslationUnitDecl(),
3789 SourceLocation(), SourceLocation(),
3790 &Context->Idents.get(StructTagName));
3791 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3792 ObjCIvarDecl *Ivar = IVars[i];
3793 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3794 &Context->Idents.get(Ivar->getName()),
3795 Ivar->getType(),
3796 nullptr, /*Expr *BW */Ivar->getBitWidth(),
3797 false, ICIS_NoInit));
3798 }
3799 RD->completeDefinition();
3800 return Context->getTagDeclType(RD);
3801}
3802
3803QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3804 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3805 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3806 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3807 if (GroupRecordType.count(tuple))
3808 return GroupRecordType[tuple];
3809
3810 SmallVector<ObjCIvarDecl *, 8> IVars;
3811 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3812 IVD; IVD = IVD->getNextIvar()) {
3813 if (IVD->isBitField())
3814 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3815 else {
3816 if (!IVars.empty()) {
3817 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3818 // Generate the struct type for this group of bitfield ivars.
3819 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3820 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3821 IVars.clear();
3822 }
3823 }
3824 }
3825 if (!IVars.empty()) {
3826 // Do the last one.
3827 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3828 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3829 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3830 }
3831 QualType RetQT = GroupRecordType[tuple];
3832 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL")((!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL"
) ? static_cast<void> (0) : __assert_fail ("!RetQT.isNull() && \"GetGroupRecordTypeForObjCIvarBitfield struct type is NULL\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 3832, __PRETTY_FUNCTION__))
;
3833
3834 return RetQT;
3835}
3836
3837/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3838/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3839void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3840 std::string &Result) {
3841 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3842 Result += CDecl->getName();
3843 Result += "__GRBF_";
3844 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3845 Result += utostr(GroupNo);
3846}
3847
3848/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3849/// Name of the struct would be: classname__T_n where n is the group number for
3850/// this ivar.
3851void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3852 std::string &Result) {
3853 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3854 Result += CDecl->getName();
3855 Result += "__T_";
3856 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3857 Result += utostr(GroupNo);
3858}
3859
3860/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3861/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3862/// this ivar.
3863void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3864 std::string &Result) {
3865 Result += "OBJC_IVAR_$_";
3866 ObjCIvarBitfieldGroupDecl(IV, Result);
3867}
3868
3869#define SKIP_BITFIELDS(IX, ENDIX, VEC){ while ((IX < ENDIX) && VEC[IX]->isBitField())
++IX; if (IX < ENDIX) --IX; }
{ \
3870 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3871 ++IX; \
3872 if (IX < ENDIX) \
3873 --IX; \
3874}
3875
3876/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3877/// an objective-c class with ivars.
3878void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3879 std::string &Result) {
3880 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct")((CDecl && "Class missing in SynthesizeObjCInternalStruct"
) ? static_cast<void> (0) : __assert_fail ("CDecl && \"Class missing in SynthesizeObjCInternalStruct\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 3880, __PRETTY_FUNCTION__))
;
3881 assert(CDecl->getName() != "" &&((CDecl->getName() != "" && "Name missing in SynthesizeObjCInternalStruct"
) ? static_cast<void> (0) : __assert_fail ("CDecl->getName() != \"\" && \"Name missing in SynthesizeObjCInternalStruct\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 3882, __PRETTY_FUNCTION__))
3882 "Name missing in SynthesizeObjCInternalStruct")((CDecl->getName() != "" && "Name missing in SynthesizeObjCInternalStruct"
) ? static_cast<void> (0) : __assert_fail ("CDecl->getName() != \"\" && \"Name missing in SynthesizeObjCInternalStruct\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 3882, __PRETTY_FUNCTION__))
;
3883 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3884 SmallVector<ObjCIvarDecl *, 8> IVars;
3885 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3886 IVD; IVD = IVD->getNextIvar())
3887 IVars.push_back(IVD);
3888
3889 SourceLocation LocStart = CDecl->getBeginLoc();
3890 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3891
3892 const char *startBuf = SM->getCharacterData(LocStart);
3893 const char *endBuf = SM->getCharacterData(LocEnd);
3894
3895 // If no ivars and no root or if its root, directly or indirectly,
3896 // have no ivars (thus not synthesized) then no need to synthesize this class.
3897 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
3898 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3899 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3900 ReplaceText(LocStart, endBuf-startBuf, Result);
3901 return;
3902 }
3903
3904 // Insert named struct/union definitions inside class to
3905 // outer scope. This follows semantics of locally defined
3906 // struct/unions in objective-c classes.
3907 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3908 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3909
3910 // Insert named structs which are syntheized to group ivar bitfields
3911 // to outer scope as well.
3912 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3913 if (IVars[i]->isBitField()) {
3914 ObjCIvarDecl *IV = IVars[i];
3915 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3916 RewriteObjCFieldDeclType(QT, Result);
3917 Result += ";";
3918 // skip over ivar bitfields in this group.
3919 SKIP_BITFIELDS(i , e, IVars){ while ((i < e) && IVars[i]->isBitField()) ++i
; if (i < e) --i; }
;
3920 }
3921
3922 Result += "\nstruct ";
3923 Result += CDecl->getNameAsString();
3924 Result += "_IMPL {\n";
3925
3926 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3927 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3928 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3929 Result += "_IVARS;\n";
3930 }
3931
3932 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3933 if (IVars[i]->isBitField()) {
3934 ObjCIvarDecl *IV = IVars[i];
3935 Result += "\tstruct ";
3936 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3937 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3938 // skip over ivar bitfields in this group.
3939 SKIP_BITFIELDS(i , e, IVars){ while ((i < e) && IVars[i]->isBitField()) ++i
; if (i < e) --i; }
;
3940 }
3941 else
3942 RewriteObjCFieldDecl(IVars[i], Result);
3943 }
3944
3945 Result += "};\n";
3946 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3947 ReplaceText(LocStart, endBuf-startBuf, Result);
3948 // Mark this struct as having been generated.
3949 if (!ObjCSynthesizedStructs.insert(CDecl).second)
3950 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct")::llvm::llvm_unreachable_internal("struct already synthesize- RewriteObjCInternalStruct"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 3950)
;
3951}
3952
3953/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3954/// have been referenced in an ivar access expression.
3955void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3956 std::string &Result) {
3957 // write out ivar offset symbols which have been referenced in an ivar
3958 // access expression.
3959 llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3960
3961 if (Ivars.empty())
3962 return;
3963
3964 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
3965 for (ObjCIvarDecl *IvarDecl : Ivars) {
3966 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
3967 unsigned GroupNo = 0;
3968 if (IvarDecl->isBitField()) {
3969 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
3970 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
3971 continue;
3972 }
3973 Result += "\n";
3974 if (LangOpts.MicrosoftExt)
3975 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3976 Result += "extern \"C\" ";
3977 if (LangOpts.MicrosoftExt &&
3978 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3979 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3980 Result += "__declspec(dllimport) ";
3981
3982 Result += "unsigned long ";
3983 if (IvarDecl->isBitField()) {
3984 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
3985 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
3986 }
3987 else
3988 WriteInternalIvarName(CDecl, IvarDecl, Result);
3989 Result += ";";
3990 }
3991}
3992
3993//===----------------------------------------------------------------------===//
3994// Meta Data Emission
3995//===----------------------------------------------------------------------===//
3996
3997/// RewriteImplementations - This routine rewrites all method implementations
3998/// and emits meta-data.
3999
4000void RewriteModernObjC::RewriteImplementations() {
4001 int ClsDefCount = ClassImplementation.size();
4002 int CatDefCount = CategoryImplementation.size();
4003
4004 // Rewrite implemented methods
4005 for (int i = 0; i < ClsDefCount; i++) {
4006 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4007 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4008 if (CDecl->isImplicitInterfaceDecl())
4009 assert(false &&((false && "Legacy implicit interface rewriting not supported in moder abi"
) ? static_cast<void> (0) : __assert_fail ("false && \"Legacy implicit interface rewriting not supported in moder abi\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4010, __PRETTY_FUNCTION__))
4010 "Legacy implicit interface rewriting not supported in moder abi")((false && "Legacy implicit interface rewriting not supported in moder abi"
) ? static_cast<void> (0) : __assert_fail ("false && \"Legacy implicit interface rewriting not supported in moder abi\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4010, __PRETTY_FUNCTION__))
;
4011 RewriteImplementationDecl(OIMP);
4012 }
4013
4014 for (int i = 0; i < CatDefCount; i++) {
4015 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4016 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4017 if (CDecl->isImplicitInterfaceDecl())
4018 assert(false &&((false && "Legacy implicit interface rewriting not supported in moder abi"
) ? static_cast<void> (0) : __assert_fail ("false && \"Legacy implicit interface rewriting not supported in moder abi\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4019, __PRETTY_FUNCTION__))
4019 "Legacy implicit interface rewriting not supported in moder abi")((false && "Legacy implicit interface rewriting not supported in moder abi"
) ? static_cast<void> (0) : __assert_fail ("false && \"Legacy implicit interface rewriting not supported in moder abi\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4019, __PRETTY_FUNCTION__))
;
4020 RewriteImplementationDecl(CIMP);
4021 }
4022}
4023
4024void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4025 const std::string &Name,
4026 ValueDecl *VD, bool def) {
4027 assert(BlockByRefDeclNo.count(VD) &&((BlockByRefDeclNo.count(VD) && "RewriteByRefString: ByRef decl missing"
) ? static_cast<void> (0) : __assert_fail ("BlockByRefDeclNo.count(VD) && \"RewriteByRefString: ByRef decl missing\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4028, __PRETTY_FUNCTION__))
4028 "RewriteByRefString: ByRef decl missing")((BlockByRefDeclNo.count(VD) && "RewriteByRefString: ByRef decl missing"
) ? static_cast<void> (0) : __assert_fail ("BlockByRefDeclNo.count(VD) && \"RewriteByRefString: ByRef decl missing\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4028, __PRETTY_FUNCTION__))
;
4029 if (def)
4030 ResultStr += "struct ";
4031 ResultStr += "__Block_byref_" + Name +
4032 "_" + utostr(BlockByRefDeclNo[VD]) ;
4033}
4034
4035static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4036 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4037 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4038 return false;
4039}
4040
4041std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4042 StringRef funcName,
4043 std::string Tag) {
4044 const FunctionType *AFT = CE->getFunctionType();
4045 QualType RT = AFT->getReturnType();
4046 std::string StructRef = "struct " + Tag;
4047 SourceLocation BlockLoc = CE->getExprLoc();
4048 std::string S;
4049 ConvertSourceLocationToLineDirective(BlockLoc, S);
4050
4051 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4052 funcName.str() + "_block_func_" + utostr(i);
4053
4054 BlockDecl *BD = CE->getBlockDecl();
4055
4056 if (isa<FunctionNoProtoType>(AFT)) {
4057 // No user-supplied arguments. Still need to pass in a pointer to the
4058 // block (to reference imported block decl refs).
4059 S += "(" + StructRef + " *__cself)";
4060 } else if (BD->param_empty()) {
4061 S += "(" + StructRef + " *__cself)";
4062 } else {
4063 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4064 assert(FT && "SynthesizeBlockFunc: No function proto")((FT && "SynthesizeBlockFunc: No function proto") ? static_cast
<void> (0) : __assert_fail ("FT && \"SynthesizeBlockFunc: No function proto\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4064, __PRETTY_FUNCTION__))
;
4065 S += '(';
4066 // first add the implicit argument.
4067 S += StructRef + " *__cself, ";
4068 std::string ParamStr;
4069 for (BlockDecl::param_iterator AI = BD->param_begin(),
4070 E = BD->param_end(); AI != E; ++AI) {
4071 if (AI != BD->param_begin()) S += ", ";
4072 ParamStr = (*AI)->getNameAsString();
4073 QualType QT = (*AI)->getType();
4074 (void)convertBlockPointerToFunctionPointer(QT);
4075 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
4076 S += ParamStr;
4077 }
4078 if (FT->isVariadic()) {
4079 if (!BD->param_empty()) S += ", ";
4080 S += "...";
4081 }
4082 S += ')';
4083 }
4084 S += " {\n";
4085
4086 // Create local declarations to avoid rewriting all closure decl ref exprs.
4087 // First, emit a declaration for all "by ref" decls.
4088 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4089 E = BlockByRefDecls.end(); I != E; ++I) {
4090 S += " ";
4091 std::string Name = (*I)->getNameAsString();
4092 std::string TypeString;
4093 RewriteByRefString(TypeString, Name, (*I));
4094 TypeString += " *";
4095 Name = TypeString + Name;
4096 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4097 }
4098 // Next, emit a declaration for all "by copy" declarations.
4099 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4100 E = BlockByCopyDecls.end(); I != E; ++I) {
4101 S += " ";
4102 // Handle nested closure invocation. For example:
4103 //
4104 // void (^myImportedClosure)(void);
4105 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4106 //
4107 // void (^anotherClosure)(void);
4108 // anotherClosure = ^(void) {
4109 // myImportedClosure(); // import and invoke the closure
4110 // };
4111 //
4112 if (isTopLevelBlockPointerType((*I)->getType())) {
4113 RewriteBlockPointerTypeVariable(S, (*I));
4114 S += " = (";
4115 RewriteBlockPointerType(S, (*I)->getType());
4116 S += ")";
4117 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4118 }
4119 else {
4120 std::string Name = (*I)->getNameAsString();
4121 QualType QT = (*I)->getType();
4122 if (HasLocalVariableExternalStorage(*I))
4123 QT = Context->getPointerType(QT);
4124 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4125 S += Name + " = __cself->" +
4126 (*I)->getNameAsString() + "; // bound by copy\n";
4127 }
4128 }
4129 std::string RewrittenStr = RewrittenBlockExprs[CE];
4130 const char *cstr = RewrittenStr.c_str();
4131 while (*cstr++ != '{') ;
4132 S += cstr;
4133 S += "\n";
4134 return S;
4135}
4136
4137std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4138 StringRef funcName,
4139 std::string Tag) {
4140 std::string StructRef = "struct " + Tag;
4141 std::string S = "static void __";
4142
4143 S += funcName;
4144 S += "_block_copy_" + utostr(i);
4145 S += "(" + StructRef;
4146 S += "*dst, " + StructRef;
4147 S += "*src) {";
4148 for (ValueDecl *VD : ImportedBlockDecls) {
4149 S += "_Block_object_assign((void*)&dst->";
4150 S += VD->getNameAsString();
4151 S += ", (void*)src->";
4152 S += VD->getNameAsString();
4153 if (BlockByRefDeclsPtrSet.count(VD))
4154 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4155 else if (VD->getType()->isBlockPointerType())
4156 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4157 else
4158 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4159 }
4160 S += "}\n";
4161
4162 S += "\nstatic void __";
4163 S += funcName;
4164 S += "_block_dispose_" + utostr(i);
4165 S += "(" + StructRef;
4166 S += "*src) {";
4167 for (ValueDecl *VD : ImportedBlockDecls) {
4168 S += "_Block_object_dispose((void*)src->";
4169 S += VD->getNameAsString();
4170 if (BlockByRefDeclsPtrSet.count(VD))
4171 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4172 else if (VD->getType()->isBlockPointerType())
4173 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4174 else
4175 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4176 }
4177 S += "}\n";
4178 return S;
4179}
4180
4181std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4182 std::string Desc) {
4183 std::string S = "\nstruct " + Tag;
4184 std::string Constructor = " " + Tag;
4185
4186 S += " {\n struct __block_impl impl;\n";
4187 S += " struct " + Desc;
4188 S += "* Desc;\n";
4189
4190 Constructor += "(void *fp, "; // Invoke function pointer.
4191 Constructor += "struct " + Desc; // Descriptor pointer.
4192 Constructor += " *desc";
4193
4194 if (BlockDeclRefs.size()) {
4195 // Output all "by copy" declarations.
4196 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4197 E = BlockByCopyDecls.end(); I != E; ++I) {
4198 S += " ";
4199 std::string FieldName = (*I)->getNameAsString();
4200 std::string ArgName = "_" + FieldName;
4201 // Handle nested closure invocation. For example:
4202 //
4203 // void (^myImportedBlock)(void);
4204 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4205 //
4206 // void (^anotherBlock)(void);
4207 // anotherBlock = ^(void) {
4208 // myImportedBlock(); // import and invoke the closure
4209 // };
4210 //
4211 if (isTopLevelBlockPointerType((*I)->getType())) {
4212 S += "struct __block_impl *";
4213 Constructor += ", void *" + ArgName;
4214 } else {
4215 QualType QT = (*I)->getType();
4216 if (HasLocalVariableExternalStorage(*I))
4217 QT = Context->getPointerType(QT);
4218 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4219 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4220 Constructor += ", " + ArgName;
4221 }
4222 S += FieldName + ";\n";
4223 }
4224 // Output all "by ref" declarations.
4225 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4226 E = BlockByRefDecls.end(); I != E; ++I) {
4227 S += " ";
4228 std::string FieldName = (*I)->getNameAsString();
4229 std::string ArgName = "_" + FieldName;
4230 {
4231 std::string TypeString;
4232 RewriteByRefString(TypeString, FieldName, (*I));
4233 TypeString += " *";
4234 FieldName = TypeString + FieldName;
4235 ArgName = TypeString + ArgName;
4236 Constructor += ", " + ArgName;
4237 }
4238 S += FieldName + "; // by ref\n";
4239 }
4240 // Finish writing the constructor.
4241 Constructor += ", int flags=0)";
4242 // Initialize all "by copy" arguments.
4243 bool firsTime = true;
4244 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4245 E = BlockByCopyDecls.end(); I != E; ++I) {
4246 std::string Name = (*I)->getNameAsString();
4247 if (firsTime) {
4248 Constructor += " : ";
4249 firsTime = false;
4250 }
4251 else
4252 Constructor += ", ";
4253 if (isTopLevelBlockPointerType((*I)->getType()))
4254 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4255 else
4256 Constructor += Name + "(_" + Name + ")";
4257 }
4258 // Initialize all "by ref" arguments.
4259 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4260 E = BlockByRefDecls.end(); I != E; ++I) {
4261 std::string Name = (*I)->getNameAsString();
4262 if (firsTime) {
4263 Constructor += " : ";
4264 firsTime = false;
4265 }
4266 else
4267 Constructor += ", ";
4268 Constructor += Name + "(_" + Name + "->__forwarding)";
4269 }
4270
4271 Constructor += " {\n";
4272 if (GlobalVarDecl)
4273 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4274 else
4275 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4276 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4277
4278 Constructor += " Desc = desc;\n";
4279 } else {
4280 // Finish writing the constructor.
4281 Constructor += ", int flags=0) {\n";
4282 if (GlobalVarDecl)
4283 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4284 else
4285 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4286 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4287 Constructor += " Desc = desc;\n";
4288 }
4289 Constructor += " ";
4290 Constructor += "}\n";
4291 S += Constructor;
4292 S += "};\n";
4293 return S;
4294}
4295
4296std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4297 std::string ImplTag, int i,
4298 StringRef FunName,
4299 unsigned hasCopy) {
4300 std::string S = "\nstatic struct " + DescTag;
4301
4302 S += " {\n size_t reserved;\n";
4303 S += " size_t Block_size;\n";
4304 if (hasCopy) {
4305 S += " void (*copy)(struct ";
4306 S += ImplTag; S += "*, struct ";
4307 S += ImplTag; S += "*);\n";
4308
4309 S += " void (*dispose)(struct ";
4310 S += ImplTag; S += "*);\n";
4311 }
4312 S += "} ";
4313
4314 S += DescTag + "_DATA = { 0, sizeof(struct ";
4315 S += ImplTag + ")";
4316 if (hasCopy) {
4317 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4318 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4319 }
4320 S += "};\n";
4321 return S;
4322}
4323
4324void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4325 StringRef FunName) {
4326 bool RewriteSC = (GlobalVarDecl &&
4327 !Blocks.empty() &&
4328 GlobalVarDecl->getStorageClass() == SC_Static &&
4329 GlobalVarDecl->getType().getCVRQualifiers());
4330 if (RewriteSC) {
4331 std::string SC(" void __");
4332 SC += GlobalVarDecl->getNameAsString();
4333 SC += "() {}";
4334 InsertText(FunLocStart, SC);
4335 }
4336
4337 // Insert closures that were part of the function.
4338 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4339 CollectBlockDeclRefInfo(Blocks[i]);
4340 // Need to copy-in the inner copied-in variables not actually used in this
4341 // block.
4342 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4343 DeclRefExpr *Exp = InnerDeclRefs[count++];
4344 ValueDecl *VD = Exp->getDecl();
4345 BlockDeclRefs.push_back(Exp);
4346 if (!VD->hasAttr<BlocksAttr>()) {
4347 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4348 BlockByCopyDeclsPtrSet.insert(VD);
4349 BlockByCopyDecls.push_back(VD);
4350 }
4351 continue;
4352 }
4353
4354 if (!BlockByRefDeclsPtrSet.count(VD)) {
4355 BlockByRefDeclsPtrSet.insert(VD);
4356 BlockByRefDecls.push_back(VD);
4357 }
4358
4359 // imported objects in the inner blocks not used in the outer
4360 // blocks must be copied/disposed in the outer block as well.
4361 if (VD->getType()->isObjCObjectPointerType() ||
4362 VD->getType()->isBlockPointerType())
4363 ImportedBlockDecls.insert(VD);
4364 }
4365
4366 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4367 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4368
4369 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4370
4371 InsertText(FunLocStart, CI);
4372
4373 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4374
4375 InsertText(FunLocStart, CF);
4376
4377 if (ImportedBlockDecls.size()) {
4378 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4379 InsertText(FunLocStart, HF);
4380 }
4381 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4382 ImportedBlockDecls.size() > 0);
4383 InsertText(FunLocStart, BD);
4384
4385 BlockDeclRefs.clear();
4386 BlockByRefDecls.clear();
4387 BlockByRefDeclsPtrSet.clear();
4388 BlockByCopyDecls.clear();
4389 BlockByCopyDeclsPtrSet.clear();
4390 ImportedBlockDecls.clear();
4391 }
4392 if (RewriteSC) {
4393 // Must insert any 'const/volatile/static here. Since it has been
4394 // removed as result of rewriting of block literals.
4395 std::string SC;
4396 if (GlobalVarDecl->getStorageClass() == SC_Static)
4397 SC = "static ";
4398 if (GlobalVarDecl->getType().isConstQualified())
4399 SC += "const ";
4400 if (GlobalVarDecl->getType().isVolatileQualified())
4401 SC += "volatile ";
4402 if (GlobalVarDecl->getType().isRestrictQualified())
4403 SC += "restrict ";
4404 InsertText(FunLocStart, SC);
4405 }
4406 if (GlobalConstructionExp) {
4407 // extra fancy dance for global literal expression.
4408
4409 // Always the latest block expression on the block stack.
4410 std::string Tag = "__";
4411 Tag += FunName;
4412 Tag += "_block_impl_";
4413 Tag += utostr(Blocks.size()-1);
4414 std::string globalBuf = "static ";
4415 globalBuf += Tag; globalBuf += " ";
4416 std::string SStr;
4417
4418 llvm::raw_string_ostream constructorExprBuf(SStr);
4419 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4420 PrintingPolicy(LangOpts));
4421 globalBuf += constructorExprBuf.str();
4422 globalBuf += ";\n";
4423 InsertText(FunLocStart, globalBuf);
4424 GlobalConstructionExp = nullptr;
4425 }
4426
4427 Blocks.clear();
4428 InnerDeclRefsCount.clear();
4429 InnerDeclRefs.clear();
4430 RewrittenBlockExprs.clear();
4431}
4432
4433void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4434 SourceLocation FunLocStart =
4435 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4436 : FD->getTypeSpecStartLoc();
4437 StringRef FuncName = FD->getName();
4438
4439 SynthesizeBlockLiterals(FunLocStart, FuncName);
4440}
4441
4442static void BuildUniqueMethodName(std::string &Name,
4443 ObjCMethodDecl *MD) {
4444 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4445 Name = std::string(IFace->getName());
4446 Name += "__" + MD->getSelector().getAsString();
4447 // Convert colons to underscores.
4448 std::string::size_type loc = 0;
4449 while ((loc = Name.find(':', loc)) != std::string::npos)
4450 Name.replace(loc, 1, "_");
4451}
4452
4453void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4454 // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4455 // SourceLocation FunLocStart = MD->getBeginLoc();
4456 SourceLocation FunLocStart = MD->getBeginLoc();
4457 std::string FuncName;
4458 BuildUniqueMethodName(FuncName, MD);
4459 SynthesizeBlockLiterals(FunLocStart, FuncName);
4460}
4461
4462void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4463 for (Stmt *SubStmt : S->children())
4464 if (SubStmt) {
4465 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
4466 GetBlockDeclRefExprs(CBE->getBody());
4467 else
4468 GetBlockDeclRefExprs(SubStmt);
4469 }
4470 // Handle specific things.
4471 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4472 if (DRE->refersToEnclosingVariableOrCapture() ||
4473 HasLocalVariableExternalStorage(DRE->getDecl()))
4474 // FIXME: Handle enums.
4475 BlockDeclRefs.push_back(DRE);
4476}
4477
4478void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4479 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
4480 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
4481 for (Stmt *SubStmt : S->children())
4482 if (SubStmt) {
4483 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
4484 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4485 GetInnerBlockDeclRefExprs(CBE->getBody(),
4486 InnerBlockDeclRefs,
4487 InnerContexts);
4488 }
4489 else
4490 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
4491 }
4492 // Handle specific things.
4493 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4494 if (DRE->refersToEnclosingVariableOrCapture() ||
4495 HasLocalVariableExternalStorage(DRE->getDecl())) {
4496 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
4497 InnerBlockDeclRefs.push_back(DRE);
4498 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
4499 if (Var->isFunctionOrMethodVarDecl())
4500 ImportedLocalExternalDecls.insert(Var);
4501 }
4502 }
4503}
4504
4505/// convertObjCTypeToCStyleType - This routine converts such objc types
4506/// as qualified objects, and blocks to their closest c/c++ types that
4507/// it can. It returns true if input type was modified.
4508bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4509 QualType oldT = T;
4510 convertBlockPointerToFunctionPointer(T);
4511 if (T->isFunctionPointerType()) {
4512 QualType PointeeTy;
4513 if (const PointerType* PT = T->getAs<PointerType>()) {
4514 PointeeTy = PT->getPointeeType();
4515 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4516 T = convertFunctionTypeOfBlocks(FT);
4517 T = Context->getPointerType(T);
4518 }
4519 }
4520 }
4521
4522 convertToUnqualifiedObjCType(T);
4523 return T != oldT;
4524}
4525
4526/// convertFunctionTypeOfBlocks - This routine converts a function type
4527/// whose result type may be a block pointer or whose argument type(s)
4528/// might be block pointers to an equivalent function type replacing
4529/// all block pointers to function pointers.
4530QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4531 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4532 // FTP will be null for closures that don't take arguments.
4533 // Generate a funky cast.
4534 SmallVector<QualType, 8> ArgTypes;
4535 QualType Res = FT->getReturnType();
4536 bool modified = convertObjCTypeToCStyleType(Res);
4537
4538 if (FTP) {
4539 for (auto &I : FTP->param_types()) {
4540 QualType t = I;
4541 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4542 if (convertObjCTypeToCStyleType(t))
4543 modified = true;
4544 ArgTypes.push_back(t);
4545 }
4546 }
4547 QualType FuncType;
4548 if (modified)
4549 FuncType = getSimpleFunctionType(Res, ArgTypes);
4550 else FuncType = QualType(FT, 0);
4551 return FuncType;
4552}
4553
4554Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4555 // Navigate to relevant type information.
4556 const BlockPointerType *CPT = nullptr;
4557
4558 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4559 CPT = DRE->getType()->getAs<BlockPointerType>();
4560 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4561 CPT = MExpr->getType()->getAs<BlockPointerType>();
4562 }
4563 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4564 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4565 }
4566 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4567 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4568 else if (const ConditionalOperator *CEXPR =
4569 dyn_cast<ConditionalOperator>(BlockExp)) {
4570 Expr *LHSExp = CEXPR->getLHS();
4571 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4572 Expr *RHSExp = CEXPR->getRHS();
4573 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4574 Expr *CONDExp = CEXPR->getCond();
4575 ConditionalOperator *CondExpr =
4576 new (Context) ConditionalOperator(CONDExp,
4577 SourceLocation(), cast<Expr>(LHSStmt),
4578 SourceLocation(), cast<Expr>(RHSStmt),
4579 Exp->getType(), VK_RValue, OK_Ordinary);
4580 return CondExpr;
4581 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4582 CPT = IRE->getType()->getAs<BlockPointerType>();
4583 } else if (const PseudoObjectExpr *POE
4584 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4585 CPT = POE->getType()->castAs<BlockPointerType>();
4586 } else {
4587 assert(false && "RewriteBlockClass: Bad type")((false && "RewriteBlockClass: Bad type") ? static_cast
<void> (0) : __assert_fail ("false && \"RewriteBlockClass: Bad type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4587, __PRETTY_FUNCTION__))
;
4588 }
4589 assert(CPT && "RewriteBlockClass: Bad type")((CPT && "RewriteBlockClass: Bad type") ? static_cast
<void> (0) : __assert_fail ("CPT && \"RewriteBlockClass: Bad type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4589, __PRETTY_FUNCTION__))
;
4590 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4591 assert(FT && "RewriteBlockClass: Bad type")((FT && "RewriteBlockClass: Bad type") ? static_cast<
void> (0) : __assert_fail ("FT && \"RewriteBlockClass: Bad type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4591, __PRETTY_FUNCTION__))
;
4592 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4593 // FTP will be null for closures that don't take arguments.
4594
4595 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4596 SourceLocation(), SourceLocation(),
4597 &Context->Idents.get("__block_impl"));
4598 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4599
4600 // Generate a funky cast.
4601 SmallVector<QualType, 8> ArgTypes;
4602
4603 // Push the block argument type.
4604 ArgTypes.push_back(PtrBlock);
4605 if (FTP) {
4606 for (auto &I : FTP->param_types()) {
4607 QualType t = I;
4608 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4609 if (!convertBlockPointerToFunctionPointer(t))
4610 convertToUnqualifiedObjCType(t);
4611 ArgTypes.push_back(t);
4612 }
4613 }
4614 // Now do the pointer to function cast.
4615 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
4616
4617 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4618
4619 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4620 CK_BitCast,
4621 const_cast<Expr*>(BlockExp));
4622 // Don't forget the parens to enforce the proper binding.
4623 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4624 BlkCast);
4625 //PE->dump();
4626
4627 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4628 SourceLocation(),
4629 &Context->Idents.get("FuncPtr"),
4630 Context->VoidPtrTy, nullptr,
4631 /*BitWidth=*/nullptr, /*Mutable=*/true,
4632 ICIS_NoInit);
4633 MemberExpr *ME = MemberExpr::CreateImplicit(
4634 *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
4635
4636 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4637 CK_BitCast, ME);
4638 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4639
4640 SmallVector<Expr*, 8> BlkExprs;
4641 // Add the implicit argument.
4642 BlkExprs.push_back(BlkCast);
4643 // Add the user arguments.
4644 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4645 E = Exp->arg_end(); I != E; ++I) {
4646 BlkExprs.push_back(*I);
4647 }
4648 CallExpr *CE = CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(),
4649 VK_RValue, SourceLocation());
4650 return CE;
4651}
4652
4653// We need to return the rewritten expression to handle cases where the
4654// DeclRefExpr is embedded in another expression being rewritten.
4655// For example:
4656//
4657// int main() {
4658// __block Foo *f;
4659// __block int i;
4660//
4661// void (^myblock)() = ^() {
4662// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
4663// i = 77;
4664// };
4665//}
4666Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
4667 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4668 // for each DeclRefExp where BYREFVAR is name of the variable.
4669 ValueDecl *VD = DeclRefExp->getDecl();
4670 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
4671 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
4672
4673 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4674 SourceLocation(),
4675 &Context->Idents.get("__forwarding"),
4676 Context->VoidPtrTy, nullptr,
4677 /*BitWidth=*/nullptr, /*Mutable=*/true,
4678 ICIS_NoInit);
4679 MemberExpr *ME = MemberExpr::CreateImplicit(
4680 *Context, DeclRefExp, isArrow, FD, FD->getType(), VK_LValue, OK_Ordinary);
4681
4682 StringRef Name = VD->getName();
4683 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
4684 &Context->Idents.get(Name),
4685 Context->VoidPtrTy, nullptr,
4686 /*BitWidth=*/nullptr, /*Mutable=*/true,
4687 ICIS_NoInit);
4688 ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
4689 VK_LValue, OK_Ordinary);
4690
4691 // Need parens to enforce precedence.
4692 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4693 DeclRefExp->getExprLoc(),
4694 ME);
4695 ReplaceStmt(DeclRefExp, PE);
4696 return PE;
4697}
4698
4699// Rewrites the imported local variable V with external storage
4700// (static, extern, etc.) as *V
4701//
4702Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4703 ValueDecl *VD = DRE->getDecl();
4704 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4705 if (!ImportedLocalExternalDecls.count(Var))
4706 return DRE;
4707 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4708 VK_LValue, OK_Ordinary,
4709 DRE->getLocation(), false);
4710 // Need parens to enforce precedence.
4711 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4712 Exp);
4713 ReplaceStmt(DRE, PE);
4714 return PE;
4715}
4716
4717void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4718 SourceLocation LocStart = CE->getLParenLoc();
4719 SourceLocation LocEnd = CE->getRParenLoc();
4720
4721 // Need to avoid trying to rewrite synthesized casts.
4722 if (LocStart.isInvalid())
4723 return;
4724 // Need to avoid trying to rewrite casts contained in macros.
4725 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4726 return;
4727
4728 const char *startBuf = SM->getCharacterData(LocStart);
4729 const char *endBuf = SM->getCharacterData(LocEnd);
4730 QualType QT = CE->getType();
4731 const Type* TypePtr = QT->getAs<Type>();
4732 if (isa<TypeOfExprType>(TypePtr)) {
4733 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4734 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4735 std::string TypeAsString = "(";
4736 RewriteBlockPointerType(TypeAsString, QT);
4737 TypeAsString += ")";
4738 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4739 return;
4740 }
4741 // advance the location to startArgList.
4742 const char *argPtr = startBuf;
4743
4744 while (*argPtr++ && (argPtr < endBuf)) {
4745 switch (*argPtr) {
4746 case '^':
4747 // Replace the '^' with '*'.
4748 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4749 ReplaceText(LocStart, 1, "*");
4750 break;
4751 }
4752 }
4753}
4754
4755void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4756 CastKind CastKind = IC->getCastKind();
4757 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4758 CastKind != CK_AnyPointerToBlockPointerCast)
4759 return;
4760
4761 QualType QT = IC->getType();
4762 (void)convertBlockPointerToFunctionPointer(QT);
4763 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4764 std::string Str = "(";
4765 Str += TypeString;
4766 Str += ")";
4767 InsertText(IC->getSubExpr()->getBeginLoc(), Str);
4768}
4769
4770void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4771 SourceLocation DeclLoc = FD->getLocation();
4772 unsigned parenCount = 0;
4773
4774 // We have 1 or more arguments that have closure pointers.
4775 const char *startBuf = SM->getCharacterData(DeclLoc);
4776 const char *startArgList = strchr(startBuf, '(');
4777
4778 assert((*startArgList == '(') && "Rewriter fuzzy parser confused")(((*startArgList == '(') && "Rewriter fuzzy parser confused"
) ? static_cast<void> (0) : __assert_fail ("(*startArgList == '(') && \"Rewriter fuzzy parser confused\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4778, __PRETTY_FUNCTION__))
;
4779
4780 parenCount++;
4781 // advance the location to startArgList.
4782 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4783 assert((DeclLoc.isValid()) && "Invalid DeclLoc")(((DeclLoc.isValid()) && "Invalid DeclLoc") ? static_cast
<void> (0) : __assert_fail ("(DeclLoc.isValid()) && \"Invalid DeclLoc\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4783, __PRETTY_FUNCTION__))
;
4784
4785 const char *argPtr = startArgList;
4786
4787 while (*argPtr++ && parenCount) {
4788 switch (*argPtr) {
4789 case '^':
4790 // Replace the '^' with '*'.
4791 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4792 ReplaceText(DeclLoc, 1, "*");
4793 break;
4794 case '(':
4795 parenCount++;
4796 break;
4797 case ')':
4798 parenCount--;
4799 break;
4800 }
4801 }
4802}
4803
4804bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4805 const FunctionProtoType *FTP;
4806 const PointerType *PT = QT->getAs<PointerType>();
4807 if (PT) {
4808 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4809 } else {
4810 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4811 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type")((BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type"
) ? static_cast<void> (0) : __assert_fail ("BPT && \"BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4811, __PRETTY_FUNCTION__))
;
4812 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4813 }
4814 if (FTP) {
4815 for (const auto &I : FTP->param_types())
4816 if (isTopLevelBlockPointerType(I))
4817 return true;
4818 }
4819 return false;
4820}
4821
4822bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4823 const FunctionProtoType *FTP;
4824 const PointerType *PT = QT->getAs<PointerType>();
4825 if (PT) {
4826 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4827 } else {
4828 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4829 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type")((BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type"
) ? static_cast<void> (0) : __assert_fail ("BPT && \"BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4829, __PRETTY_FUNCTION__))
;
4830 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4831 }
4832 if (FTP) {
4833 for (const auto &I : FTP->param_types()) {
4834 if (I->isObjCQualifiedIdType())
4835 return true;
4836 if (I->isObjCObjectPointerType() &&
4837 I->getPointeeType()->isObjCQualifiedInterfaceType())
4838 return true;
4839 }
4840
4841 }
4842 return false;
4843}
4844
4845void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4846 const char *&RParen) {
4847 const char *argPtr = strchr(Name, '(');
4848 assert((*argPtr == '(') && "Rewriter fuzzy parser confused")(((*argPtr == '(') && "Rewriter fuzzy parser confused"
) ? static_cast<void> (0) : __assert_fail ("(*argPtr == '(') && \"Rewriter fuzzy parser confused\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4848, __PRETTY_FUNCTION__))
;
4849
4850 LParen = argPtr; // output the start.
4851 argPtr++; // skip past the left paren.
4852 unsigned parenCount = 1;
4853
4854 while (*argPtr && parenCount) {
4855 switch (*argPtr) {
4856 case '(': parenCount++; break;
4857 case ')': parenCount--; break;
4858 default: break;
4859 }
4860 if (parenCount) argPtr++;
4861 }
4862 assert((*argPtr == ')') && "Rewriter fuzzy parser confused")(((*argPtr == ')') && "Rewriter fuzzy parser confused"
) ? static_cast<void> (0) : __assert_fail ("(*argPtr == ')') && \"Rewriter fuzzy parser confused\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4862, __PRETTY_FUNCTION__))
;
4863 RParen = argPtr; // output the end
4864}
4865
4866void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4867 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4868 RewriteBlockPointerFunctionArgs(FD);
4869 return;
4870 }
4871 // Handle Variables and Typedefs.
4872 SourceLocation DeclLoc = ND->getLocation();
4873 QualType DeclT;
4874 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4875 DeclT = VD->getType();
4876 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4877 DeclT = TDD->getUnderlyingType();
4878 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4879 DeclT = FD->getType();
4880 else
4881 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled")::llvm::llvm_unreachable_internal("RewriteBlockPointerDecl(): Decl type not yet handled"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 4881)
;
4882
4883 const char *startBuf = SM->getCharacterData(DeclLoc);
4884 const char *endBuf = startBuf;
4885 // scan backward (from the decl location) for the end of the previous decl.
4886 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4887 startBuf--;
4888 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4889 std::string buf;
4890 unsigned OrigLength=0;
4891 // *startBuf != '^' if we are dealing with a pointer to function that
4892 // may take block argument types (which will be handled below).
4893 if (*startBuf == '^') {
4894 // Replace the '^' with '*', computing a negative offset.
4895 buf = '*';
4896 startBuf++;
4897 OrigLength++;
4898 }
4899 while (*startBuf != ')') {
4900 buf += *startBuf;
4901 startBuf++;
4902 OrigLength++;
4903 }
4904 buf += ')';
4905 OrigLength++;
4906
4907 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4908 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4909 // Replace the '^' with '*' for arguments.
4910 // Replace id<P> with id/*<>*/
4911 DeclLoc = ND->getLocation();
4912 startBuf = SM->getCharacterData(DeclLoc);
4913 const char *argListBegin, *argListEnd;
4914 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4915 while (argListBegin < argListEnd) {
4916 if (*argListBegin == '^')
4917 buf += '*';
4918 else if (*argListBegin == '<') {
4919 buf += "/*";
4920 buf += *argListBegin++;
4921 OrigLength++;
4922 while (*argListBegin != '>') {
4923 buf += *argListBegin++;
4924 OrigLength++;
4925 }
4926 buf += *argListBegin;
4927 buf += "*/";
4928 }
4929 else
4930 buf += *argListBegin;
4931 argListBegin++;
4932 OrigLength++;
4933 }
4934 buf += ')';
4935 OrigLength++;
4936 }
4937 ReplaceText(Start, OrigLength, buf);
4938}
4939
4940/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4941/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4942/// struct Block_byref_id_object *src) {
4943/// _Block_object_assign (&_dest->object, _src->object,
4944/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4945/// [|BLOCK_FIELD_IS_WEAK]) // object
4946/// _Block_object_assign(&_dest->object, _src->object,
4947/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4948/// [|BLOCK_FIELD_IS_WEAK]) // block
4949/// }
4950/// And:
4951/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4952/// _Block_object_dispose(_src->object,
4953/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4954/// [|BLOCK_FIELD_IS_WEAK]) // object
4955/// _Block_object_dispose(_src->object,
4956/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4957/// [|BLOCK_FIELD_IS_WEAK]) // block
4958/// }
4959
4960std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4961 int flag) {
4962 std::string S;
4963 if (CopyDestroyCache.count(flag))
4964 return S;
4965 CopyDestroyCache.insert(flag);
4966 S = "static void __Block_byref_id_object_copy_";
4967 S += utostr(flag);
4968 S += "(void *dst, void *src) {\n";
4969
4970 // offset into the object pointer is computed as:
4971 // void * + void* + int + int + void* + void *
4972 unsigned IntSize =
4973 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4974 unsigned VoidPtrSize =
4975 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4976
4977 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4978 S += " _Block_object_assign((char*)dst + ";
4979 S += utostr(offset);
4980 S += ", *(void * *) ((char*)src + ";
4981 S += utostr(offset);
4982 S += "), ";
4983 S += utostr(flag);
4984 S += ");\n}\n";
4985
4986 S += "static void __Block_byref_id_object_dispose_";
4987 S += utostr(flag);
4988 S += "(void *src) {\n";
4989 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4990 S += utostr(offset);
4991 S += "), ";
4992 S += utostr(flag);
4993 S += ");\n}\n";
4994 return S;
4995}
4996
4997/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4998/// the declaration into:
4999/// struct __Block_byref_ND {
5000/// void *__isa; // NULL for everything except __weak pointers
5001/// struct __Block_byref_ND *__forwarding;
5002/// int32_t __flags;
5003/// int32_t __size;
5004/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5005/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5006/// typex ND;
5007/// };
5008///
5009/// It then replaces declaration of ND variable with:
5010/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5011/// __size=sizeof(struct __Block_byref_ND),
5012/// ND=initializer-if-any};
5013///
5014///
5015void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5016 bool lastDecl) {
5017 int flag = 0;
5018 int isa = 0;
5019 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5020 if (DeclLoc.isInvalid())
5021 // If type location is missing, it is because of missing type (a warning).
5022 // Use variable's location which is good for this case.
5023 DeclLoc = ND->getLocation();
5024 const char *startBuf = SM->getCharacterData(DeclLoc);
5025 SourceLocation X = ND->getEndLoc();
5026 X = SM->getExpansionLoc(X);
5027 const char *endBuf = SM->getCharacterData(X);
5028 std::string Name(ND->getNameAsString());
5029 std::string ByrefType;
5030 RewriteByRefString(ByrefType, Name, ND, true);
5031 ByrefType += " {\n";
5032 ByrefType += " void *__isa;\n";
5033 RewriteByRefString(ByrefType, Name, ND);
5034 ByrefType += " *__forwarding;\n";
5035 ByrefType += " int __flags;\n";
5036 ByrefType += " int __size;\n";
5037 // Add void *__Block_byref_id_object_copy;
5038 // void *__Block_byref_id_object_dispose; if needed.
5039 QualType Ty = ND->getType();
5040 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
5041 if (HasCopyAndDispose) {
5042 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5043 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5044 }
5045
5046 QualType T = Ty;
5047 (void)convertBlockPointerToFunctionPointer(T);
5048 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5049
5050 ByrefType += " " + Name + ";\n";
5051 ByrefType += "};\n";
5052 // Insert this type in global scope. It is needed by helper function.
5053 SourceLocation FunLocStart;
5054 if (CurFunctionDef)
5055 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
5056 else {
5057 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null")((CurMethodDef && "RewriteByRefVar - CurMethodDef is null"
) ? static_cast<void> (0) : __assert_fail ("CurMethodDef && \"RewriteByRefVar - CurMethodDef is null\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 5057, __PRETTY_FUNCTION__))
;
5058 FunLocStart = CurMethodDef->getBeginLoc();
5059 }
5060 InsertText(FunLocStart, ByrefType);
5061
5062 if (Ty.isObjCGCWeak()) {
5063 flag |= BLOCK_FIELD_IS_WEAK;
5064 isa = 1;
5065 }
5066 if (HasCopyAndDispose) {
5067 flag = BLOCK_BYREF_CALLER;
5068 QualType Ty = ND->getType();
5069 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5070 if (Ty->isBlockPointerType())
5071 flag |= BLOCK_FIELD_IS_BLOCK;
5072 else
5073 flag |= BLOCK_FIELD_IS_OBJECT;
5074 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5075 if (!HF.empty())
5076 Preamble += HF;
5077 }
5078
5079 // struct __Block_byref_ND ND =
5080 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5081 // initializer-if-any};
5082 bool hasInit = (ND->getInit() != nullptr);
5083 // FIXME. rewriter does not support __block c++ objects which
5084 // require construction.
5085 if (hasInit)
5086 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5087 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5088 if (CXXDecl && CXXDecl->isDefaultConstructor())
5089 hasInit = false;
5090 }
5091
5092 unsigned flags = 0;
5093 if (HasCopyAndDispose)
5094 flags |= BLOCK_HAS_COPY_DISPOSE;
5095 Name = ND->getNameAsString();
5096 ByrefType.clear();
5097 RewriteByRefString(ByrefType, Name, ND);
5098 std::string ForwardingCastType("(");
5099 ForwardingCastType += ByrefType + " *)";
5100 ByrefType += " " + Name + " = {(void*)";
5101 ByrefType += utostr(isa);
5102 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5103 ByrefType += utostr(flags);
5104 ByrefType += ", ";
5105 ByrefType += "sizeof(";
5106 RewriteByRefString(ByrefType, Name, ND);
5107 ByrefType += ")";
5108 if (HasCopyAndDispose) {
5109 ByrefType += ", __Block_byref_id_object_copy_";
5110 ByrefType += utostr(flag);
5111 ByrefType += ", __Block_byref_id_object_dispose_";
5112 ByrefType += utostr(flag);
5113 }
5114
5115 if (!firstDecl) {
5116 // In multiple __block declarations, and for all but 1st declaration,
5117 // find location of the separating comma. This would be start location
5118 // where new text is to be inserted.
5119 DeclLoc = ND->getLocation();
5120 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5121 const char *commaBuf = startDeclBuf;
5122 while (*commaBuf != ',')
5123 commaBuf--;
5124 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','")(((*commaBuf == ',') && "RewriteByRefVar: can't find ','"
) ? static_cast<void> (0) : __assert_fail ("(*commaBuf == ',') && \"RewriteByRefVar: can't find ','\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 5124, __PRETTY_FUNCTION__))
;
5125 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5126 startBuf = commaBuf;
5127 }
5128
5129 if (!hasInit) {
5130 ByrefType += "};\n";
5131 unsigned nameSize = Name.size();
5132 // for block or function pointer declaration. Name is already
5133 // part of the declaration.
5134 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5135 nameSize = 1;
5136 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5137 }
5138 else {
5139 ByrefType += ", ";
5140 SourceLocation startLoc;
5141 Expr *E = ND->getInit();
5142 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5143 startLoc = ECE->getLParenLoc();
5144 else
5145 startLoc = E->getBeginLoc();
5146 startLoc = SM->getExpansionLoc(startLoc);
5147 endBuf = SM->getCharacterData(startLoc);
5148 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
5149
5150 const char separator = lastDecl ? ';' : ',';
5151 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5152 const char *separatorBuf = strchr(startInitializerBuf, separator);
5153 assert((*separatorBuf == separator) &&(((*separatorBuf == separator) && "RewriteByRefVar: can't find ';' or ','"
) ? static_cast<void> (0) : __assert_fail ("(*separatorBuf == separator) && \"RewriteByRefVar: can't find ';' or ','\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 5154, __PRETTY_FUNCTION__))
5154 "RewriteByRefVar: can't find ';' or ','")(((*separatorBuf == separator) && "RewriteByRefVar: can't find ';' or ','"
) ? static_cast<void> (0) : __assert_fail ("(*separatorBuf == separator) && \"RewriteByRefVar: can't find ';' or ','\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 5154, __PRETTY_FUNCTION__))
;
5155 SourceLocation separatorLoc =
5156 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5157
5158 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
5159 }
5160}
5161
5162void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5163 // Add initializers for any closure decl refs.
5164 GetBlockDeclRefExprs(Exp->getBody());
5165 if (BlockDeclRefs.size()) {
5166 // Unique all "by copy" declarations.
5167 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5168 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5169 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5170 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5171 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5172 }
5173 }
5174 // Unique all "by ref" declarations.
5175 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5176 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5177 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5178 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5179 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5180 }
5181 }
5182 // Find any imported blocks...they will need special attention.
5183 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5184 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5185 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5186 BlockDeclRefs[i]->getType()->isBlockPointerType())
5187 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5188 }
5189}
5190
5191FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5192 IdentifierInfo *ID = &Context->Idents.get(name);
5193 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5194 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5195 SourceLocation(), ID, FType, nullptr, SC_Extern,
5196 false, false);
5197}
5198
5199Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
5200 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
5201 const BlockDecl *block = Exp->getBlockDecl();
5202
5203 Blocks.push_back(Exp);
5204
5205 CollectBlockDeclRefInfo(Exp);
5206
5207 // Add inner imported variables now used in current block.
5208 int countOfInnerDecls = 0;
5209 if (!InnerBlockDeclRefs.empty()) {
5210 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5211 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
5212 ValueDecl *VD = Exp->getDecl();
5213 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
5214 // We need to save the copied-in variables in nested
5215 // blocks because it is needed at the end for some of the API generations.
5216 // See SynthesizeBlockLiterals routine.
5217 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5218 BlockDeclRefs.push_back(Exp);
5219 BlockByCopyDeclsPtrSet.insert(VD);
5220 BlockByCopyDecls.push_back(VD);
5221 }
5222 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
5223 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5224 BlockDeclRefs.push_back(Exp);
5225 BlockByRefDeclsPtrSet.insert(VD);
5226 BlockByRefDecls.push_back(VD);
5227 }
5228 }
5229 // Find any imported blocks...they will need special attention.
5230 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5231 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5232 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5233 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5234 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5235 }
5236 InnerDeclRefsCount.push_back(countOfInnerDecls);
5237
5238 std::string FuncName;
5239
5240 if (CurFunctionDef)
5241 FuncName = CurFunctionDef->getNameAsString();
5242 else if (CurMethodDef)
5243 BuildUniqueMethodName(FuncName, CurMethodDef);
5244 else if (GlobalVarDecl)
5245 FuncName = std::string(GlobalVarDecl->getNameAsString());
5246
5247 bool GlobalBlockExpr =
5248 block->getDeclContext()->getRedeclContext()->isFileContext();
5249
5250 if (GlobalBlockExpr && !GlobalVarDecl) {
5251 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5252 GlobalBlockExpr = false;
5253 }
5254
5255 std::string BlockNumber = utostr(Blocks.size()-1);
5256
5257 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5258
5259 // Get a pointer to the function type so we can cast appropriately.
5260 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5261 QualType FType = Context->getPointerType(BFT);
5262
5263 FunctionDecl *FD;
5264 Expr *NewRep;
5265
5266 // Simulate a constructor call...
5267 std::string Tag;
5268
5269 if (GlobalBlockExpr)
5270 Tag = "__global_";
5271 else
5272 Tag = "__";
5273 Tag += FuncName + "_block_impl_" + BlockNumber;
5274
5275 FD = SynthBlockInitFunctionDecl(Tag);
5276 DeclRefExpr *DRE = new (Context)
5277 DeclRefExpr(*Context, FD, false, FType, VK_RValue, SourceLocation());
5278
5279 SmallVector<Expr*, 4> InitExprs;
5280
5281 // Initialize the block function.
5282 FD = SynthBlockInitFunctionDecl(Func);
5283 DeclRefExpr *Arg = new (Context) DeclRefExpr(
5284 *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
5285 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5286 CK_BitCast, Arg);
5287 InitExprs.push_back(castExpr);
5288
5289 // Initialize the block descriptor.
5290 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5291
5292 VarDecl *NewVD = VarDecl::Create(
5293 *Context, TUDecl, SourceLocation(), SourceLocation(),
5294 &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
5295 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5296 new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
5297 VK_LValue, SourceLocation()),
5298 UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_RValue,
5299 OK_Ordinary, SourceLocation(), false);
5300 InitExprs.push_back(DescRefExpr);
5301
5302 // Add initializers for any closure decl refs.
5303 if (BlockDeclRefs.size()) {
5304 Expr *Exp;
5305 // Output all "by copy" declarations.
5306 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
5307 E = BlockByCopyDecls.end(); I != E; ++I) {
5308 if (isObjCType((*I)->getType())) {
5309 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5310 FD = SynthBlockInitFunctionDecl((*I)->getName());
5311 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5312 VK_LValue, SourceLocation());
5313 if (HasLocalVariableExternalStorage(*I)) {
5314 QualType QT = (*I)->getType();
5315 QT = Context->getPointerType(QT);
5316 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5317 OK_Ordinary, SourceLocation(),
5318 false);
5319 }
5320 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5321 FD = SynthBlockInitFunctionDecl((*I)->getName());
5322 Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5323 VK_LValue, SourceLocation());
5324 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5325 CK_BitCast, Arg);
5326 } else {
5327 FD = SynthBlockInitFunctionDecl((*I)->getName());
5328 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5329 VK_LValue, SourceLocation());
5330 if (HasLocalVariableExternalStorage(*I)) {
5331 QualType QT = (*I)->getType();
5332 QT = Context->getPointerType(QT);
5333 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5334 OK_Ordinary, SourceLocation(),
5335 false);
5336 }
5337
5338 }
5339 InitExprs.push_back(Exp);
5340 }
5341 // Output all "by ref" declarations.
5342 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
5343 E = BlockByRefDecls.end(); I != E; ++I) {
5344 ValueDecl *ND = (*I);
5345 std::string Name(ND->getNameAsString());
5346 std::string RecName;
5347 RewriteByRefString(RecName, Name, ND, true);
5348 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5349 + sizeof("struct"));
5350 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5351 SourceLocation(), SourceLocation(),
5352 II);
5353 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl")((RD && "SynthBlockInitExpr(): Can't find RecordDecl"
) ? static_cast<void> (0) : __assert_fail ("RD && \"SynthBlockInitExpr(): Can't find RecordDecl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 5353, __PRETTY_FUNCTION__))
;
5354 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5355
5356 FD = SynthBlockInitFunctionDecl((*I)->getName());
5357 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5358 VK_LValue, SourceLocation());
5359 bool isNestedCapturedVar = false;
5360 if (block)
5361 for (const auto &CI : block->captures()) {
5362 const VarDecl *variable = CI.getVariable();
5363 if (variable == ND && CI.isNested()) {
5364 assert (CI.isByRef() &&((CI.isByRef() && "SynthBlockInitExpr - captured block variable is not byref"
) ? static_cast<void> (0) : __assert_fail ("CI.isByRef() && \"SynthBlockInitExpr - captured block variable is not byref\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 5365, __PRETTY_FUNCTION__))
5365 "SynthBlockInitExpr - captured block variable is not byref")((CI.isByRef() && "SynthBlockInitExpr - captured block variable is not byref"
) ? static_cast<void> (0) : __assert_fail ("CI.isByRef() && \"SynthBlockInitExpr - captured block variable is not byref\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 5365, __PRETTY_FUNCTION__))
;
5366 isNestedCapturedVar = true;
5367 break;
5368 }
5369 }
5370 // captured nested byref variable has its address passed. Do not take
5371 // its address again.
5372 if (!isNestedCapturedVar)
5373 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5374 Context->getPointerType(Exp->getType()),
5375 VK_RValue, OK_Ordinary, SourceLocation(),
5376 false);
5377 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5378 InitExprs.push_back(Exp);
5379 }
5380 }
5381 if (ImportedBlockDecls.size()) {
5382 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5383 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5384 unsigned IntSize =
5385 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5386 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5387 Context->IntTy, SourceLocation());
5388 InitExprs.push_back(FlagExp);
5389 }
5390 NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
5391 SourceLocation());
5392
5393 if (GlobalBlockExpr) {
5394 assert (!GlobalConstructionExp &&((!GlobalConstructionExp && "SynthBlockInitExpr - GlobalConstructionExp must be null"
) ? static_cast<void> (0) : __assert_fail ("!GlobalConstructionExp && \"SynthBlockInitExpr - GlobalConstructionExp must be null\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 5395, __PRETTY_FUNCTION__))
5395 "SynthBlockInitExpr - GlobalConstructionExp must be null")((!GlobalConstructionExp && "SynthBlockInitExpr - GlobalConstructionExp must be null"
) ? static_cast<void> (0) : __assert_fail ("!GlobalConstructionExp && \"SynthBlockInitExpr - GlobalConstructionExp must be null\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 5395, __PRETTY_FUNCTION__))
;
5396 GlobalConstructionExp = NewRep;
5397 NewRep = DRE;
5398 }
5399
5400 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5401 Context->getPointerType(NewRep->getType()),
5402 VK_RValue, OK_Ordinary, SourceLocation(), false);
5403 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5404 NewRep);
5405 // Put Paren around the call.
5406 NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5407 NewRep);
5408
5409 BlockDeclRefs.clear();
5410 BlockByRefDecls.clear();
5411 BlockByRefDeclsPtrSet.clear();
5412 BlockByCopyDecls.clear();
5413 BlockByCopyDeclsPtrSet.clear();
5414 ImportedBlockDecls.clear();
5415 return NewRep;
5416}
5417
5418bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5419 if (const ObjCForCollectionStmt * CS =
5420 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5421 return CS->getElement() == DS;
5422 return false;
5423}
5424
5425//===----------------------------------------------------------------------===//
5426// Function Body / Expression rewriting
5427//===----------------------------------------------------------------------===//
5428
5429Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5430 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5431 isa<DoStmt>(S) || isa<ForStmt>(S))
5432 Stmts.push_back(S);
5433 else if (isa<ObjCForCollectionStmt>(S)) {
5434 Stmts.push_back(S);
5435 ObjCBcLabelNo.push_back(++BcLabelCount);
5436 }
5437
5438 // Pseudo-object operations and ivar references need special
5439 // treatment because we're going to recursively rewrite them.
5440 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5441 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5442 return RewritePropertyOrImplicitSetter(PseudoOp);
5443 } else {
5444 return RewritePropertyOrImplicitGetter(PseudoOp);
5445 }
5446 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5447 return RewriteObjCIvarRefExpr(IvarRefExpr);
5448 }
5449 else if (isa<OpaqueValueExpr>(S))
5450 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
5451
5452 SourceRange OrigStmtRange = S->getSourceRange();
5453
5454 // Perform a bottom up rewrite of all children.
5455 for (Stmt *&childStmt : S->children())
5456 if (childStmt) {
5457 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5458 if (newStmt) {
5459 childStmt = newStmt;
5460 }
5461 }
5462
5463 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5464 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
5465 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5466 InnerContexts.insert(BE->getBlockDecl());
5467 ImportedLocalExternalDecls.clear();
5468 GetInnerBlockDeclRefExprs(BE->getBody(),
5469 InnerBlockDeclRefs, InnerContexts);
5470 // Rewrite the block body in place.
5471 Stmt *SaveCurrentBody = CurrentBody;
5472 CurrentBody = BE->getBody();
5473 PropParentMap = nullptr;
5474 // block literal on rhs of a property-dot-sytax assignment
5475 // must be replaced by its synthesize ast so getRewrittenText
5476 // works as expected. In this case, what actually ends up on RHS
5477 // is the blockTranscribed which is the helper function for the
5478 // block literal; as in: self.c = ^() {[ace ARR];};
5479 bool saveDisableReplaceStmt = DisableReplaceStmt;
5480 DisableReplaceStmt = false;
5481 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5482 DisableReplaceStmt = saveDisableReplaceStmt;
5483 CurrentBody = SaveCurrentBody;
5484 PropParentMap = nullptr;
5485 ImportedLocalExternalDecls.clear();
5486 // Now we snarf the rewritten text and stash it away for later use.
5487 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5488 RewrittenBlockExprs[BE] = Str;
5489
5490 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5491
5492 //blockTranscribed->dump();
5493 ReplaceStmt(S, blockTranscribed);
5494 return blockTranscribed;
5495 }
5496 // Handle specific things.
5497 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5498 return RewriteAtEncode(AtEncode);
5499
5500 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5501 return RewriteAtSelector(AtSelector);
5502
5503 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5504 return RewriteObjCStringLiteral(AtString);
5505
5506 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5507 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
5508
5509 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5510 return RewriteObjCBoxedExpr(BoxedExpr);
5511
5512 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5513 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
5514
5515 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5516 dyn_cast<ObjCDictionaryLiteral>(S))
5517 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
5518
5519 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5520#if 0
5521 // Before we rewrite it, put the original message expression in a comment.
5522 SourceLocation startLoc = MessExpr->getBeginLoc();
5523 SourceLocation endLoc = MessExpr->getEndLoc();
5524
5525 const char *startBuf = SM->getCharacterData(startLoc);
5526 const char *endBuf = SM->getCharacterData(endLoc);
5527
5528 std::string messString;
5529 messString += "// ";
5530 messString.append(startBuf, endBuf-startBuf+1);
5531 messString += "\n";
5532
5533 // FIXME: Missing definition of
5534 // InsertText(clang::SourceLocation, char const*, unsigned int).
5535 // InsertText(startLoc, messString);
5536 // Tried this, but it didn't work either...
5537 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5538#endif
5539 return RewriteMessageExpr(MessExpr);
5540 }
5541
5542 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5543 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5544 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5545 }
5546
5547 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5548 return RewriteObjCTryStmt(StmtTry);
5549
5550 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5551 return RewriteObjCSynchronizedStmt(StmtTry);
5552
5553 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5554 return RewriteObjCThrowStmt(StmtThrow);
5555
5556 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5557 return RewriteObjCProtocolExpr(ProtocolExp);
5558
5559 if (ObjCForCollectionStmt *StmtForCollection =
5560 dyn_cast<ObjCForCollectionStmt>(S))
5561 return RewriteObjCForCollectionStmt(StmtForCollection,
5562 OrigStmtRange.getEnd());
5563 if (BreakStmt *StmtBreakStmt =
5564 dyn_cast<BreakStmt>(S))
5565 return RewriteBreakStmt(StmtBreakStmt);
5566 if (ContinueStmt *StmtContinueStmt =
5567 dyn_cast<ContinueStmt>(S))
5568 return RewriteContinueStmt(StmtContinueStmt);
5569
5570 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5571 // and cast exprs.
5572 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5573 // FIXME: What we're doing here is modifying the type-specifier that
5574 // precedes the first Decl. In the future the DeclGroup should have
5575 // a separate type-specifier that we can rewrite.
5576 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5577 // the context of an ObjCForCollectionStmt. For example:
5578 // NSArray *someArray;
5579 // for (id <FooProtocol> index in someArray) ;
5580 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5581 // and it depends on the original text locations/positions.
5582 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5583 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5584
5585 // Blocks rewrite rules.
5586 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5587 DI != DE; ++DI) {
5588 Decl *SD = *DI;
5589 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5590 if (isTopLevelBlockPointerType(ND->getType()))
5591 RewriteBlockPointerDecl(ND);
5592 else if (ND->getType()->isFunctionPointerType())
5593 CheckFunctionPointerDecl(ND->getType(), ND);
5594 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5595 if (VD->hasAttr<BlocksAttr>()) {
5596 static unsigned uniqueByrefDeclCount = 0;
5597 assert(!BlockByRefDeclNo.count(ND) &&((!BlockByRefDeclNo.count(ND) && "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl"
) ? static_cast<void> (0) : __assert_fail ("!BlockByRefDeclNo.count(ND) && \"RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 5598, __PRETTY_FUNCTION__))
5598 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl")((!BlockByRefDeclNo.count(ND) && "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl"
) ? static_cast<void> (0) : __assert_fail ("!BlockByRefDeclNo.count(ND) && \"RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 5598, __PRETTY_FUNCTION__))
;
5599 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5600 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
5601 }
5602 else
5603 RewriteTypeOfDecl(VD);
5604 }
5605 }
5606 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5607 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5608 RewriteBlockPointerDecl(TD);
5609 else if (TD->getUnderlyingType()->isFunctionPointerType())
5610 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5611 }
5612 }
5613 }
5614
5615 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5616 RewriteObjCQualifiedInterfaceTypes(CE);
5617
5618 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5619 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5620 assert(!Stmts.empty() && "Statement stack is empty")((!Stmts.empty() && "Statement stack is empty") ? static_cast
<void> (0) : __assert_fail ("!Stmts.empty() && \"Statement stack is empty\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 5620, __PRETTY_FUNCTION__))
;
5621 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||(((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>
(Stmts.back()) || isa<DoStmt>(Stmts.back()) || isa<ForStmt
>(Stmts.back())) && "Statement stack mismatch") ? static_cast
<void> (0) : __assert_fail ("(isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) || isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back())) && \"Statement stack mismatch\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 5623, __PRETTY_FUNCTION__))
5622 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))(((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>
(Stmts.back()) || isa<DoStmt>(Stmts.back()) || isa<ForStmt
>(Stmts.back())) && "Statement stack mismatch") ? static_cast
<void> (0) : __assert_fail ("(isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) || isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back())) && \"Statement stack mismatch\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 5623, __PRETTY_FUNCTION__))
5623 && "Statement stack mismatch")(((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>
(Stmts.back()) || isa<DoStmt>(Stmts.back()) || isa<ForStmt
>(Stmts.back())) && "Statement stack mismatch") ? static_cast
<void> (0) : __assert_fail ("(isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) || isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back())) && \"Statement stack mismatch\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 5623, __PRETTY_FUNCTION__))
;
5624 Stmts.pop_back();
5625 }
5626 // Handle blocks rewriting.
5627 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5628 ValueDecl *VD = DRE->getDecl();
5629 if (VD->hasAttr<BlocksAttr>())
5630 return RewriteBlockDeclRefExpr(DRE);
5631 if (HasLocalVariableExternalStorage(VD))
5632 return RewriteLocalVariableExternalStorage(DRE);
5633 }
5634
5635 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5636 if (CE->getCallee()->getType()->isBlockPointerType()) {
5637 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5638 ReplaceStmt(S, BlockCall);
5639 return BlockCall;
5640 }
5641 }
5642 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5643 RewriteCastExpr(CE);
5644 }
5645 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5646 RewriteImplicitCastObjCExpr(ICE);
5647 }
5648#if 0
5649
5650 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5651 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5652 ICE->getSubExpr(),
5653 SourceLocation());
5654 // Get the new text.
5655 std::string SStr;
5656 llvm::raw_string_ostream Buf(SStr);
5657 Replacement->printPretty(Buf);
5658 const std::string &Str = Buf.str();
5659
5660 printf("CAST = %s\n", &Str[0]);
5661 InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
5662 delete S;
5663 return Replacement;
5664 }
5665#endif
5666 // Return this stmt unmodified.
5667 return S;
5668}
5669
5670void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5671 for (auto *FD : RD->fields()) {
5672 if (isTopLevelBlockPointerType(FD->getType()))
5673 RewriteBlockPointerDecl(FD);
5674 if (FD->getType()->isObjCQualifiedIdType() ||
5675 FD->getType()->isObjCQualifiedInterfaceType())
5676 RewriteObjCQualifiedInterfaceTypes(FD);
5677 }
5678}
5679
5680/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5681/// main file of the input.
5682void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5683 switch (D->getKind()) {
5684 case Decl::Function: {
5685 FunctionDecl *FD = cast<FunctionDecl>(D);
5686 if (FD->isOverloadedOperator())
5687 return;
5688
5689 // Since function prototypes don't have ParmDecl's, we check the function
5690 // prototype. This enables us to rewrite function declarations and
5691 // definitions using the same code.
5692 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5693
5694 if (!FD->isThisDeclarationADefinition())
5695 break;
5696
5697 // FIXME: If this should support Obj-C++, support CXXTryStmt
5698 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5699 CurFunctionDef = FD;
5700 CurrentBody = Body;
5701 Body =
5702 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5703 FD->setBody(Body);
5704 CurrentBody = nullptr;
5705 if (PropParentMap) {
5706 delete PropParentMap;
5707 PropParentMap = nullptr;
5708 }
5709 // This synthesizes and inserts the block "impl" struct, invoke function,
5710 // and any copy/dispose helper functions.
5711 InsertBlockLiteralsWithinFunction(FD);
5712 RewriteLineDirective(D);
5713 CurFunctionDef = nullptr;
5714 }
5715 break;
5716 }
5717 case Decl::ObjCMethod: {
5718 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5719 if (CompoundStmt *Body = MD->getCompoundBody()) {
5720 CurMethodDef = MD;
5721 CurrentBody = Body;
5722 Body =
5723 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5724 MD->setBody(Body);
5725 CurrentBody = nullptr;
5726 if (PropParentMap) {
5727 delete PropParentMap;
5728 PropParentMap = nullptr;
5729 }
5730 InsertBlockLiteralsWithinMethod(MD);
5731 RewriteLineDirective(D);
5732 CurMethodDef = nullptr;
5733 }
5734 break;
5735 }
5736 case Decl::ObjCImplementation: {
5737 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5738 ClassImplementation.push_back(CI);
5739 break;
5740 }
5741 case Decl::ObjCCategoryImpl: {
5742 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5743 CategoryImplementation.push_back(CI);
5744 break;
5745 }
5746 case Decl::Var: {
5747 VarDecl *VD = cast<VarDecl>(D);
5748 RewriteObjCQualifiedInterfaceTypes(VD);
5749 if (isTopLevelBlockPointerType(VD->getType()))
5750 RewriteBlockPointerDecl(VD);
5751 else if (VD->getType()->isFunctionPointerType()) {
5752 CheckFunctionPointerDecl(VD->getType(), VD);
5753 if (VD->getInit()) {
5754 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5755 RewriteCastExpr(CE);
5756 }
5757 }
5758 } else if (VD->getType()->isRecordType()) {
5759 RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
5760 if (RD->isCompleteDefinition())
5761 RewriteRecordBody(RD);
5762 }
5763 if (VD->getInit()) {
5764 GlobalVarDecl = VD;
5765 CurrentBody = VD->getInit();
5766 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5767 CurrentBody = nullptr;
5768 if (PropParentMap) {
5769 delete PropParentMap;
5770 PropParentMap = nullptr;
5771 }
5772 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5773 GlobalVarDecl = nullptr;
5774
5775 // This is needed for blocks.
5776 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5777 RewriteCastExpr(CE);
5778 }
5779 }
5780 break;
5781 }
5782 case Decl::TypeAlias:
5783 case Decl::Typedef: {
5784 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5785 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5786 RewriteBlockPointerDecl(TD);
5787 else if (TD->getUnderlyingType()->isFunctionPointerType())
5788 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5789 else
5790 RewriteObjCQualifiedInterfaceTypes(TD);
5791 }
5792 break;
5793 }
5794 case Decl::CXXRecord:
5795 case Decl::Record: {
5796 RecordDecl *RD = cast<RecordDecl>(D);
5797 if (RD->isCompleteDefinition())
5798 RewriteRecordBody(RD);
5799 break;
5800 }
5801 default:
5802 break;
5803 }
5804 // Nothing yet.
5805}
5806
5807/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5808/// protocol reference symbols in the for of:
5809/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5810static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5811 ObjCProtocolDecl *PDecl,
5812 std::string &Result) {
5813 // Also output .objc_protorefs$B section and its meta-data.
5814 if (Context->getLangOpts().MicrosoftExt)
5815 Result += "static ";
5816 Result += "struct _protocol_t *";
5817 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5818 Result += PDecl->getNameAsString();
5819 Result += " = &";
5820 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5821 Result += ";\n";
5822}
5823
5824void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5825 if (Diags.hasErrorOccurred())
5826 return;
5827
5828 RewriteInclude();
5829
5830 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
5831 // translation of function bodies were postponed until all class and
5832 // their extensions and implementations are seen. This is because, we
5833 // cannot build grouping structs for bitfields until they are all seen.
5834 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5835 HandleTopLevelSingleDecl(FDecl);
5836 }
5837
5838 // Here's a great place to add any extra declarations that may be needed.
5839 // Write out meta data for each @protocol(<expr>).
5840 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5841 RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5842 Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
5843 }
5844
5845 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5846
5847 if (ClassImplementation.size() || CategoryImplementation.size())
5848 RewriteImplementations();
5849
5850 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5851 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5852 // Write struct declaration for the class matching its ivar declarations.
5853 // Note that for modern abi, this is postponed until the end of TU
5854 // because class extensions and the implementation might declare their own
5855 // private ivars.
5856 RewriteInterfaceDecl(CDecl);
5857 }
5858
5859 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5860 // we are done.
5861 if (const RewriteBuffer *RewriteBuf =
5862 Rewrite.getRewriteBufferFor(MainFileID)) {
5863 //printf("Changed:\n");
5864 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5865 } else {
5866 llvm::errs() << "No changes\n";
5867 }
5868
5869 if (ClassImplementation.size() || CategoryImplementation.size() ||
5870 ProtocolExprDecls.size()) {
5871 // Rewrite Objective-c meta data*
5872 std::string ResultStr;
5873 RewriteMetaDataIntoBuffer(ResultStr);
5874 // Emit metadata.
5875 *OutFile << ResultStr;
5876 }
5877 // Emit ImageInfo;
5878 {
5879 std::string ResultStr;
5880 WriteImageInfo(ResultStr);
5881 *OutFile << ResultStr;
5882 }
5883 OutFile->flush();
5884}
5885
5886void RewriteModernObjC::Initialize(ASTContext &context) {
5887 InitializeCommon(context);
5888
5889 Preamble += "#ifndef __OBJC2__\n";
5890 Preamble += "#define __OBJC2__\n";
5891 Preamble += "#endif\n";
5892
5893 // declaring objc_selector outside the parameter list removes a silly
5894 // scope related warning...
5895 if (IsHeader)
5896 Preamble = "#pragma once\n";
5897 Preamble += "struct objc_selector; struct objc_class;\n";
5898 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5899 Preamble += "\n\tstruct objc_object *superClass; ";
5900 // Add a constructor for creating temporary objects.
5901 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5902 Preamble += ": object(o), superClass(s) {} ";
5903 Preamble += "\n};\n";
5904
5905 if (LangOpts.MicrosoftExt) {
5906 // Define all sections using syntax that makes sense.
5907 // These are currently generated.
5908 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
5909 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
5910 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
5911 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5912 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
5913 // These are generated but not necessary for functionality.
5914 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
5915 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5916 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
5917 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
5918
5919 // These need be generated for performance. Currently they are not,
5920 // using API calls instead.
5921 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5922 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5923 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5924
5925 }
5926 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5927 Preamble += "typedef struct objc_object Protocol;\n";
5928 Preamble += "#define _REWRITER_typedef_Protocol\n";
5929 Preamble += "#endif\n";
5930 if (LangOpts.MicrosoftExt) {
5931 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5932 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5933 }
5934 else
5935 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5936
5937 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5938 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5939 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5940 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5941 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5942
5943 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
5944 Preamble += "(const char *);\n";
5945 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5946 Preamble += "(struct objc_class *);\n";
5947 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
5948 Preamble += "(const char *);\n";
5949 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
5950 // @synchronized hooks.
5951 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5952 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
5953 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5954 Preamble += "#ifdef _WIN64\n";
5955 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
5956 Preamble += "#else\n";
5957 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
5958 Preamble += "#endif\n";
5959 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5960 Preamble += "struct __objcFastEnumerationState {\n\t";
5961 Preamble += "unsigned long state;\n\t";
5962 Preamble += "void **itemsPtr;\n\t";
5963 Preamble += "unsigned long *mutationsPtr;\n\t";
5964 Preamble += "unsigned long extra[5];\n};\n";
5965 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5966 Preamble += "#define __FASTENUMERATIONSTATE\n";
5967 Preamble += "#endif\n";
5968 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5969 Preamble += "struct __NSConstantStringImpl {\n";
5970 Preamble += " int *isa;\n";
5971 Preamble += " int flags;\n";
5972 Preamble += " char *str;\n";
5973 Preamble += "#if _WIN64\n";
5974 Preamble += " long long length;\n";
5975 Preamble += "#else\n";
5976 Preamble += " long length;\n";
5977 Preamble += "#endif\n";
5978 Preamble += "};\n";
5979 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5980 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5981 Preamble += "#else\n";
5982 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5983 Preamble += "#endif\n";
5984 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5985 Preamble += "#endif\n";
5986 // Blocks preamble.
5987 Preamble += "#ifndef BLOCK_IMPL\n";
5988 Preamble += "#define BLOCK_IMPL\n";
5989 Preamble += "struct __block_impl {\n";
5990 Preamble += " void *isa;\n";
5991 Preamble += " int Flags;\n";
5992 Preamble += " int Reserved;\n";
5993 Preamble += " void *FuncPtr;\n";
5994 Preamble += "};\n";
5995 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5996 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5997 Preamble += "extern \"C\" __declspec(dllexport) "
5998 "void _Block_object_assign(void *, const void *, const int);\n";
5999 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6000 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6001 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6002 Preamble += "#else\n";
6003 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6004 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6005 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6006 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6007 Preamble += "#endif\n";
6008 Preamble += "#endif\n";
6009 if (LangOpts.MicrosoftExt) {
6010 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6011 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6012 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6013 Preamble += "#define __attribute__(X)\n";
6014 Preamble += "#endif\n";
6015 Preamble += "#ifndef __weak\n";
6016 Preamble += "#define __weak\n";
6017 Preamble += "#endif\n";
6018 Preamble += "#ifndef __block\n";
6019 Preamble += "#define __block\n";
6020 Preamble += "#endif\n";
6021 }
6022 else {
6023 Preamble += "#define __block\n";
6024 Preamble += "#define __weak\n";
6025 }
6026
6027 // Declarations required for modern objective-c array and dictionary literals.
6028 Preamble += "\n#include <stdarg.h>\n";
6029 Preamble += "struct __NSContainer_literal {\n";
6030 Preamble += " void * *arr;\n";
6031 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
6032 Preamble += "\tva_list marker;\n";
6033 Preamble += "\tva_start(marker, count);\n";
6034 Preamble += "\tarr = new void *[count];\n";
6035 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6036 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6037 Preamble += "\tva_end( marker );\n";
6038 Preamble += " };\n";
6039 Preamble += " ~__NSContainer_literal() {\n";
6040 Preamble += "\tdelete[] arr;\n";
6041 Preamble += " }\n";
6042 Preamble += "};\n";
6043
6044 // Declaration required for implementation of @autoreleasepool statement.
6045 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6046 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6047 Preamble += "struct __AtAutoreleasePool {\n";
6048 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6049 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6050 Preamble += " void * atautoreleasepoolobj;\n";
6051 Preamble += "};\n";
6052
6053 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6054 // as this avoids warning in any 64bit/32bit compilation model.
6055 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6056}
6057
6058/// RewriteIvarOffsetComputation - This routine synthesizes computation of
6059/// ivar offset.
6060void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6061 std::string &Result) {
6062 Result += "__OFFSETOFIVAR__(struct ";
6063 Result += ivar->getContainingInterface()->getNameAsString();
6064 if (LangOpts.MicrosoftExt)
6065 Result += "_IMPL";
6066 Result += ", ";
6067 if (ivar->isBitField())
6068 ObjCIvarBitfieldGroupDecl(ivar, Result);
6069 else
6070 Result += ivar->getNameAsString();
6071 Result += ")";
6072}
6073
6074/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6075/// struct _prop_t {
6076/// const char *name;
6077/// char *attributes;
6078/// }
6079
6080/// struct _prop_list_t {
6081/// uint32_t entsize; // sizeof(struct _prop_t)
6082/// uint32_t count_of_properties;
6083/// struct _prop_t prop_list[count_of_properties];
6084/// }
6085
6086/// struct _protocol_t;
6087
6088/// struct _protocol_list_t {
6089/// long protocol_count; // Note, this is 32/64 bit
6090/// struct _protocol_t * protocol_list[protocol_count];
6091/// }
6092
6093/// struct _objc_method {
6094/// SEL _cmd;
6095/// const char *method_type;
6096/// char *_imp;
6097/// }
6098
6099/// struct _method_list_t {
6100/// uint32_t entsize; // sizeof(struct _objc_method)
6101/// uint32_t method_count;
6102/// struct _objc_method method_list[method_count];
6103/// }
6104
6105/// struct _protocol_t {
6106/// id isa; // NULL
6107/// const char *protocol_name;
6108/// const struct _protocol_list_t * protocol_list; // super protocols
6109/// const struct method_list_t *instance_methods;
6110/// const struct method_list_t *class_methods;
6111/// const struct method_list_t *optionalInstanceMethods;
6112/// const struct method_list_t *optionalClassMethods;
6113/// const struct _prop_list_t * properties;
6114/// const uint32_t size; // sizeof(struct _protocol_t)
6115/// const uint32_t flags; // = 0
6116/// const char ** extendedMethodTypes;
6117/// }
6118
6119/// struct _ivar_t {
6120/// unsigned long int *offset; // pointer to ivar offset location
6121/// const char *name;
6122/// const char *type;
6123/// uint32_t alignment;
6124/// uint32_t size;
6125/// }
6126
6127/// struct _ivar_list_t {
6128/// uint32 entsize; // sizeof(struct _ivar_t)
6129/// uint32 count;
6130/// struct _ivar_t list[count];
6131/// }
6132
6133/// struct _class_ro_t {
6134/// uint32_t flags;
6135/// uint32_t instanceStart;
6136/// uint32_t instanceSize;
6137/// uint32_t reserved; // only when building for 64bit targets
6138/// const uint8_t *ivarLayout;
6139/// const char *name;
6140/// const struct _method_list_t *baseMethods;
6141/// const struct _protocol_list_t *baseProtocols;
6142/// const struct _ivar_list_t *ivars;
6143/// const uint8_t *weakIvarLayout;
6144/// const struct _prop_list_t *properties;
6145/// }
6146
6147/// struct _class_t {
6148/// struct _class_t *isa;
6149/// struct _class_t *superclass;
6150/// void *cache;
6151/// IMP *vtable;
6152/// struct _class_ro_t *ro;
6153/// }
6154
6155/// struct _category_t {
6156/// const char *name;
6157/// struct _class_t *cls;
6158/// const struct _method_list_t *instance_methods;
6159/// const struct _method_list_t *class_methods;
6160/// const struct _protocol_list_t *protocols;
6161/// const struct _prop_list_t *properties;
6162/// }
6163
6164/// MessageRefTy - LLVM for:
6165/// struct _message_ref_t {
6166/// IMP messenger;
6167/// SEL name;
6168/// };
6169
6170/// SuperMessageRefTy - LLVM for:
6171/// struct _super_message_ref_t {
6172/// SUPER_IMP messenger;
6173/// SEL name;
6174/// };
6175
6176static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
6177 static bool meta_data_declared = false;
6178 if (meta_data_declared)
6179 return;
6180
6181 Result += "\nstruct _prop_t {\n";
6182 Result += "\tconst char *name;\n";
6183 Result += "\tconst char *attributes;\n";
6184 Result += "};\n";
6185
6186 Result += "\nstruct _protocol_t;\n";
6187
6188 Result += "\nstruct _objc_method {\n";
6189 Result += "\tstruct objc_selector * _cmd;\n";
6190 Result += "\tconst char *method_type;\n";
6191 Result += "\tvoid *_imp;\n";
6192 Result += "};\n";
6193
6194 Result += "\nstruct _protocol_t {\n";
6195 Result += "\tvoid * isa; // NULL\n";
6196 Result += "\tconst char *protocol_name;\n";
6197 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
6198 Result += "\tconst struct method_list_t *instance_methods;\n";
6199 Result += "\tconst struct method_list_t *class_methods;\n";
6200 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6201 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6202 Result += "\tconst struct _prop_list_t * properties;\n";
6203 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6204 Result += "\tconst unsigned int flags; // = 0\n";
6205 Result += "\tconst char ** extendedMethodTypes;\n";
6206 Result += "};\n";
6207
6208 Result += "\nstruct _ivar_t {\n";
6209 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
6210 Result += "\tconst char *name;\n";
6211 Result += "\tconst char *type;\n";
6212 Result += "\tunsigned int alignment;\n";
6213 Result += "\tunsigned int size;\n";
6214 Result += "};\n";
6215
6216 Result += "\nstruct _class_ro_t {\n";
6217 Result += "\tunsigned int flags;\n";
6218 Result += "\tunsigned int instanceStart;\n";
6219 Result += "\tunsigned int instanceSize;\n";
6220 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6221 if (Triple.getArch() == llvm::Triple::x86_64)
6222 Result += "\tunsigned int reserved;\n";
6223 Result += "\tconst unsigned char *ivarLayout;\n";
6224 Result += "\tconst char *name;\n";
6225 Result += "\tconst struct _method_list_t *baseMethods;\n";
6226 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6227 Result += "\tconst struct _ivar_list_t *ivars;\n";
6228 Result += "\tconst unsigned char *weakIvarLayout;\n";
6229 Result += "\tconst struct _prop_list_t *properties;\n";
6230 Result += "};\n";
6231
6232 Result += "\nstruct _class_t {\n";
6233 Result += "\tstruct _class_t *isa;\n";
6234 Result += "\tstruct _class_t *superclass;\n";
6235 Result += "\tvoid *cache;\n";
6236 Result += "\tvoid *vtable;\n";
6237 Result += "\tstruct _class_ro_t *ro;\n";
6238 Result += "};\n";
6239
6240 Result += "\nstruct _category_t {\n";
6241 Result += "\tconst char *name;\n";
6242 Result += "\tstruct _class_t *cls;\n";
6243 Result += "\tconst struct _method_list_t *instance_methods;\n";
6244 Result += "\tconst struct _method_list_t *class_methods;\n";
6245 Result += "\tconst struct _protocol_list_t *protocols;\n";
6246 Result += "\tconst struct _prop_list_t *properties;\n";
6247 Result += "};\n";
6248
6249 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
6250 Result += "#pragma warning(disable:4273)\n";
6251 meta_data_declared = true;
6252}
6253
6254static void Write_protocol_list_t_TypeDecl(std::string &Result,
6255 long super_protocol_count) {
6256 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6257 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6258 Result += "\tstruct _protocol_t *super_protocols[";
6259 Result += utostr(super_protocol_count); Result += "];\n";
6260 Result += "}";
6261}
6262
6263static void Write_method_list_t_TypeDecl(std::string &Result,
6264 unsigned int method_count) {
6265 Result += "struct /*_method_list_t*/"; Result += " {\n";
6266 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6267 Result += "\tunsigned int method_count;\n";
6268 Result += "\tstruct _objc_method method_list[";
6269 Result += utostr(method_count); Result += "];\n";
6270 Result += "}";
6271}
6272
6273static void Write__prop_list_t_TypeDecl(std::string &Result,
6274 unsigned int property_count) {
6275 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6276 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6277 Result += "\tunsigned int count_of_properties;\n";
6278 Result += "\tstruct _prop_t prop_list[";
6279 Result += utostr(property_count); Result += "];\n";
6280 Result += "}";
6281}
6282
6283static void Write__ivar_list_t_TypeDecl(std::string &Result,
6284 unsigned int ivar_count) {
6285 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6286 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6287 Result += "\tunsigned int count;\n";
6288 Result += "\tstruct _ivar_t ivar_list[";
6289 Result += utostr(ivar_count); Result += "];\n";
6290 Result += "}";
6291}
6292
6293static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6294 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6295 StringRef VarName,
6296 StringRef ProtocolName) {
6297 if (SuperProtocols.size() > 0) {
6298 Result += "\nstatic ";
6299 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6300 Result += " "; Result += VarName;
6301 Result += ProtocolName;
6302 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6303 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6304 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6305 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6306 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6307 Result += SuperPD->getNameAsString();
6308 if (i == e-1)
6309 Result += "\n};\n";
6310 else
6311 Result += ",\n";
6312 }
6313 }
6314}
6315
6316static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6317 ASTContext *Context, std::string &Result,
6318 ArrayRef<ObjCMethodDecl *> Methods,
6319 StringRef VarName,
6320 StringRef TopLevelDeclName,
6321 bool MethodImpl) {
6322 if (Methods.size() > 0) {
6323 Result += "\nstatic ";
6324 Write_method_list_t_TypeDecl(Result, Methods.size());
6325 Result += " "; Result += VarName;
6326 Result += TopLevelDeclName;
6327 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6328 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6329 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6330 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6331 ObjCMethodDecl *MD = Methods[i];
6332 if (i == 0)
6333 Result += "\t{{(struct objc_selector *)\"";
6334 else
6335 Result += "\t{(struct objc_selector *)\"";
6336 Result += (MD)->getSelector().getAsString(); Result += "\"";
6337 Result += ", ";
6338 std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD);
6339 Result += "\""; Result += MethodTypeString; Result += "\"";
6340 Result += ", ";
6341 if (!MethodImpl)
6342 Result += "0";
6343 else {
6344 Result += "(void *)";
6345 Result += RewriteObj.MethodInternalNames[MD];
6346 }
6347 if (i == e-1)
6348 Result += "}}\n";
6349 else
6350 Result += "},\n";
6351 }
6352 Result += "};\n";
6353 }
6354}
6355
6356static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
6357 ASTContext *Context, std::string &Result,
6358 ArrayRef<ObjCPropertyDecl *> Properties,
6359 const Decl *Container,
6360 StringRef VarName,
6361 StringRef ProtocolName) {
6362 if (Properties.size() > 0) {
6363 Result += "\nstatic ";
6364 Write__prop_list_t_TypeDecl(Result, Properties.size());
6365 Result += " "; Result += VarName;
6366 Result += ProtocolName;
6367 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6368 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6369 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6370 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6371 ObjCPropertyDecl *PropDecl = Properties[i];
6372 if (i == 0)
6373 Result += "\t{{\"";
6374 else
6375 Result += "\t{\"";
6376 Result += PropDecl->getName(); Result += "\",";
6377 std::string PropertyTypeString =
6378 Context->getObjCEncodingForPropertyDecl(PropDecl, Container);
6379 std::string QuotePropertyTypeString;
6380 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6381 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6382 if (i == e-1)
6383 Result += "}}\n";
6384 else
6385 Result += "},\n";
6386 }
6387 Result += "};\n";
6388 }
6389}
6390
6391// Metadata flags
6392enum MetaDataDlags {
6393 CLS = 0x0,
6394 CLS_META = 0x1,
6395 CLS_ROOT = 0x2,
6396 OBJC2_CLS_HIDDEN = 0x10,
6397 CLS_EXCEPTION = 0x20,
6398
6399 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6400 CLS_HAS_IVAR_RELEASER = 0x40,
6401 /// class was compiled with -fobjc-arr
6402 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6403};
6404
6405static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6406 unsigned int flags,
6407 const std::string &InstanceStart,
6408 const std::string &InstanceSize,
6409 ArrayRef<ObjCMethodDecl *>baseMethods,
6410 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6411 ArrayRef<ObjCIvarDecl *>ivars,
6412 ArrayRef<ObjCPropertyDecl *>Properties,
6413 StringRef VarName,
6414 StringRef ClassName) {
6415 Result += "\nstatic struct _class_ro_t ";
6416 Result += VarName; Result += ClassName;
6417 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6418 Result += "\t";
6419 Result += llvm::utostr(flags); Result += ", ";
6420 Result += InstanceStart; Result += ", ";
6421 Result += InstanceSize; Result += ", \n";
6422 Result += "\t";
6423 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6424 if (Triple.getArch() == llvm::Triple::x86_64)
6425 // uint32_t const reserved; // only when building for 64bit targets
6426 Result += "(unsigned int)0, \n\t";
6427 // const uint8_t * const ivarLayout;
6428 Result += "0, \n\t";
6429 Result += "\""; Result += ClassName; Result += "\",\n\t";
6430 bool metaclass = ((flags & CLS_META) != 0);
6431 if (baseMethods.size() > 0) {
6432 Result += "(const struct _method_list_t *)&";
6433 if (metaclass)
6434 Result += "_OBJC_$_CLASS_METHODS_";
6435 else
6436 Result += "_OBJC_$_INSTANCE_METHODS_";
6437 Result += ClassName;
6438 Result += ",\n\t";
6439 }
6440 else
6441 Result += "0, \n\t";
6442
6443 if (!metaclass && baseProtocols.size() > 0) {
6444 Result += "(const struct _objc_protocol_list *)&";
6445 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6446 Result += ",\n\t";
6447 }
6448 else
6449 Result += "0, \n\t";
6450
6451 if (!metaclass && ivars.size() > 0) {
6452 Result += "(const struct _ivar_list_t *)&";
6453 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6454 Result += ",\n\t";
6455 }
6456 else
6457 Result += "0, \n\t";
6458
6459 // weakIvarLayout
6460 Result += "0, \n\t";
6461 if (!metaclass && Properties.size() > 0) {
6462 Result += "(const struct _prop_list_t *)&";
6463 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
6464 Result += ",\n";
6465 }
6466 else
6467 Result += "0, \n";
6468
6469 Result += "};\n";
6470}
6471
6472static void Write_class_t(ASTContext *Context, std::string &Result,
6473 StringRef VarName,
6474 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6475 bool rootClass = (!CDecl->getSuperClass());
6476 const ObjCInterfaceDecl *RootClass = CDecl;
6477
6478 if (!rootClass) {
6479 // Find the Root class
6480 RootClass = CDecl->getSuperClass();
6481 while (RootClass->getSuperClass()) {
6482 RootClass = RootClass->getSuperClass();
6483 }
6484 }
6485
6486 if (metaclass && rootClass) {
6487 // Need to handle a case of use of forward declaration.
6488 Result += "\n";
6489 Result += "extern \"C\" ";
6490 if (CDecl->getImplementation())
6491 Result += "__declspec(dllexport) ";
6492 else
6493 Result += "__declspec(dllimport) ";
6494
6495 Result += "struct _class_t OBJC_CLASS_$_";
6496 Result += CDecl->getNameAsString();
6497 Result += ";\n";
6498 }
6499 // Also, for possibility of 'super' metadata class not having been defined yet.
6500 if (!rootClass) {
6501 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
6502 Result += "\n";
6503 Result += "extern \"C\" ";
6504 if (SuperClass->getImplementation())
6505 Result += "__declspec(dllexport) ";
6506 else
6507 Result += "__declspec(dllimport) ";
6508
6509 Result += "struct _class_t ";
6510 Result += VarName;
6511 Result += SuperClass->getNameAsString();
6512 Result += ";\n";
6513
6514 if (metaclass && RootClass != SuperClass) {
6515 Result += "extern \"C\" ";
6516 if (RootClass->getImplementation())
6517 Result += "__declspec(dllexport) ";
6518 else
6519 Result += "__declspec(dllimport) ";
6520
6521 Result += "struct _class_t ";
6522 Result += VarName;
6523 Result += RootClass->getNameAsString();
6524 Result += ";\n";
6525 }
6526 }
6527
6528 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6529 Result += VarName; Result += CDecl->getNameAsString();
6530 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6531 Result += "\t";
6532 if (metaclass) {
6533 if (!rootClass) {
6534 Result += "0, // &"; Result += VarName;
6535 Result += RootClass->getNameAsString();
6536 Result += ",\n\t";
6537 Result += "0, // &"; Result += VarName;
6538 Result += CDecl->getSuperClass()->getNameAsString();
6539 Result += ",\n\t";
6540 }
6541 else {
6542 Result += "0, // &"; Result += VarName;
6543 Result += CDecl->getNameAsString();
6544 Result += ",\n\t";
6545 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6546 Result += ",\n\t";
6547 }
6548 }
6549 else {
6550 Result += "0, // &OBJC_METACLASS_$_";
6551 Result += CDecl->getNameAsString();
6552 Result += ",\n\t";
6553 if (!rootClass) {
6554 Result += "0, // &"; Result += VarName;
6555 Result += CDecl->getSuperClass()->getNameAsString();
6556 Result += ",\n\t";
6557 }
6558 else
6559 Result += "0,\n\t";
6560 }
6561 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6562 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6563 if (metaclass)
6564 Result += "&_OBJC_METACLASS_RO_$_";
6565 else
6566 Result += "&_OBJC_CLASS_RO_$_";
6567 Result += CDecl->getNameAsString();
6568 Result += ",\n};\n";
6569
6570 // Add static function to initialize some of the meta-data fields.
6571 // avoid doing it twice.
6572 if (metaclass)
6573 return;
6574
6575 const ObjCInterfaceDecl *SuperClass =
6576 rootClass ? CDecl : CDecl->getSuperClass();
6577
6578 Result += "static void OBJC_CLASS_SETUP_$_";
6579 Result += CDecl->getNameAsString();
6580 Result += "(void ) {\n";
6581 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6582 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6583 Result += RootClass->getNameAsString(); Result += ";\n";
6584
6585 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6586 Result += ".superclass = ";
6587 if (rootClass)
6588 Result += "&OBJC_CLASS_$_";
6589 else
6590 Result += "&OBJC_METACLASS_$_";
6591
6592 Result += SuperClass->getNameAsString(); Result += ";\n";
6593
6594 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6595 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6596
6597 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6598 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6599 Result += CDecl->getNameAsString(); Result += ";\n";
6600
6601 if (!rootClass) {
6602 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6603 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6604 Result += SuperClass->getNameAsString(); Result += ";\n";
6605 }
6606
6607 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6608 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6609 Result += "}\n";
6610}
6611
6612static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6613 std::string &Result,
6614 ObjCCategoryDecl *CatDecl,
6615 ObjCInterfaceDecl *ClassDecl,
6616 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6617 ArrayRef<ObjCMethodDecl *> ClassMethods,
6618 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6619 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
6620 StringRef CatName = CatDecl->getName();
6621 StringRef ClassName = ClassDecl->getName();
6622 // must declare an extern class object in case this class is not implemented
6623 // in this TU.
6624 Result += "\n";
6625 Result += "extern \"C\" ";
6626 if (ClassDecl->getImplementation())
6627 Result += "__declspec(dllexport) ";
6628 else
6629 Result += "__declspec(dllimport) ";
6630
6631 Result += "struct _class_t ";
6632 Result += "OBJC_CLASS_$_"; Result += ClassName;
6633 Result += ";\n";
6634
6635 Result += "\nstatic struct _category_t ";
6636 Result += "_OBJC_$_CATEGORY_";
6637 Result += ClassName; Result += "_$_"; Result += CatName;
6638 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6639 Result += "{\n";
6640 Result += "\t\""; Result += ClassName; Result += "\",\n";
6641 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
6642 Result += ",\n";
6643 if (InstanceMethods.size() > 0) {
6644 Result += "\t(const struct _method_list_t *)&";
6645 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6646 Result += ClassName; Result += "_$_"; Result += CatName;
6647 Result += ",\n";
6648 }
6649 else
6650 Result += "\t0,\n";
6651
6652 if (ClassMethods.size() > 0) {
6653 Result += "\t(const struct _method_list_t *)&";
6654 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6655 Result += ClassName; Result += "_$_"; Result += CatName;
6656 Result += ",\n";
6657 }
6658 else
6659 Result += "\t0,\n";
6660
6661 if (RefedProtocols.size() > 0) {
6662 Result += "\t(const struct _protocol_list_t *)&";
6663 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6664 Result += ClassName; Result += "_$_"; Result += CatName;
6665 Result += ",\n";
6666 }
6667 else
6668 Result += "\t0,\n";
6669
6670 if (ClassProperties.size() > 0) {
6671 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6672 Result += ClassName; Result += "_$_"; Result += CatName;
6673 Result += ",\n";
6674 }
6675 else
6676 Result += "\t0,\n";
6677
6678 Result += "};\n";
6679
6680 // Add static function to initialize the class pointer in the category structure.
6681 Result += "static void OBJC_CATEGORY_SETUP_$_";
6682 Result += ClassDecl->getNameAsString();
6683 Result += "_$_";
6684 Result += CatName;
6685 Result += "(void ) {\n";
6686 Result += "\t_OBJC_$_CATEGORY_";
6687 Result += ClassDecl->getNameAsString();
6688 Result += "_$_";
6689 Result += CatName;
6690 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6691 Result += ";\n}\n";
6692}
6693
6694static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6695 ASTContext *Context, std::string &Result,
6696 ArrayRef<ObjCMethodDecl *> Methods,
6697 StringRef VarName,
6698 StringRef ProtocolName) {
6699 if (Methods.size() == 0)
6700 return;
6701
6702 Result += "\nstatic const char *";
6703 Result += VarName; Result += ProtocolName;
6704 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6705 Result += "{\n";
6706 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6707 ObjCMethodDecl *MD = Methods[i];
6708 std::string MethodTypeString =
6709 Context->getObjCEncodingForMethodDecl(MD, true);
6710 std::string QuoteMethodTypeString;
6711 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6712 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6713 if (i == e-1)
6714 Result += "\n};\n";
6715 else {
6716 Result += ",\n";
6717 }
6718 }
6719}
6720
6721static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6722 ASTContext *Context,
6723 std::string &Result,
6724 ArrayRef<ObjCIvarDecl *> Ivars,
6725 ObjCInterfaceDecl *CDecl) {
6726 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6727 // this is what happens:
6728 /**
6729 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6730 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6731 Class->getVisibility() == HiddenVisibility)
6732 Visibility should be: HiddenVisibility;
6733 else
6734 Visibility should be: DefaultVisibility;
6735 */
6736
6737 Result += "\n";
6738 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6739 ObjCIvarDecl *IvarDecl = Ivars[i];
6740 if (Context->getLangOpts().MicrosoftExt)
6741 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6742
6743 if (!Context->getLangOpts().MicrosoftExt ||
6744 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
6745 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
6746 Result += "extern \"C\" unsigned long int ";
6747 else
6748 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
6749 if (Ivars[i]->isBitField())
6750 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6751 else
6752 WriteInternalIvarName(CDecl, IvarDecl, Result);
6753 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6754 Result += " = ";
6755 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6756 Result += ";\n";
6757 if (Ivars[i]->isBitField()) {
6758 // skip over rest of the ivar bitfields.
6759 SKIP_BITFIELDS(i , e, Ivars){ while ((i < e) && Ivars[i]->isBitField()) ++i
; if (i < e) --i; }
;
6760 }
6761 }
6762}
6763
6764static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6765 ASTContext *Context, std::string &Result,
6766 ArrayRef<ObjCIvarDecl *> OriginalIvars,
6767 StringRef VarName,
6768 ObjCInterfaceDecl *CDecl) {
6769 if (OriginalIvars.size() > 0) {
6770 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6771 SmallVector<ObjCIvarDecl *, 8> Ivars;
6772 // strip off all but the first ivar bitfield from each group of ivars.
6773 // Such ivars in the ivar list table will be replaced by their grouping struct
6774 // 'ivar'.
6775 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6776 if (OriginalIvars[i]->isBitField()) {
6777 Ivars.push_back(OriginalIvars[i]);
6778 // skip over rest of the ivar bitfields.
6779 SKIP_BITFIELDS(i , e, OriginalIvars){ while ((i < e) && OriginalIvars[i]->isBitField
()) ++i; if (i < e) --i; }
;
6780 }
6781 else
6782 Ivars.push_back(OriginalIvars[i]);
6783 }
6784
6785 Result += "\nstatic ";
6786 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6787 Result += " "; Result += VarName;
6788 Result += CDecl->getNameAsString();
6789 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6790 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6791 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6792 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6793 ObjCIvarDecl *IvarDecl = Ivars[i];
6794 if (i == 0)
6795 Result += "\t{{";
6796 else
6797 Result += "\t {";
6798 Result += "(unsigned long int *)&";
6799 if (Ivars[i]->isBitField())
6800 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6801 else
6802 WriteInternalIvarName(CDecl, IvarDecl, Result);
6803 Result += ", ";
6804
6805 Result += "\"";
6806 if (Ivars[i]->isBitField())
6807 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6808 else
6809 Result += IvarDecl->getName();
6810 Result += "\", ";
6811
6812 QualType IVQT = IvarDecl->getType();
6813 if (IvarDecl->isBitField())
6814 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6815
6816 std::string IvarTypeString, QuoteIvarTypeString;
6817 Context->getObjCEncodingForType(IVQT, IvarTypeString,
6818 IvarDecl);
6819 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6820 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6821
6822 // FIXME. this alignment represents the host alignment and need be changed to
6823 // represent the target alignment.
6824 unsigned Align = Context->getTypeAlign(IVQT)/8;
6825 Align = llvm::Log2_32(Align);
6826 Result += llvm::utostr(Align); Result += ", ";
6827 CharUnits Size = Context->getTypeSizeInChars(IVQT);
6828 Result += llvm::utostr(Size.getQuantity());
6829 if (i == e-1)
6830 Result += "}}\n";
6831 else
6832 Result += "},\n";
6833 }
6834 Result += "};\n";
6835 }
6836}
6837
6838/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
6839void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6840 std::string &Result) {
6841
6842 // Do not synthesize the protocol more than once.
6843 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6844 return;
6845 WriteModernMetadataDeclarations(Context, Result);
6846
6847 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6848 PDecl = Def;
6849 // Must write out all protocol definitions in current qualifier list,
6850 // and in their nested qualifiers before writing out current definition.
6851 for (auto *I : PDecl->protocols())
6852 RewriteObjCProtocolMetaData(I, Result);
6853
6854 // Construct method lists.
6855 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6856 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6857 for (auto *MD : PDecl->instance_methods()) {
6858 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6859 OptInstanceMethods.push_back(MD);
6860 } else {
6861 InstanceMethods.push_back(MD);
6862 }
6863 }
6864
6865 for (auto *MD : PDecl->class_methods()) {
6866 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6867 OptClassMethods.push_back(MD);
6868 } else {
6869 ClassMethods.push_back(MD);
6870 }
6871 }
6872 std::vector<ObjCMethodDecl *> AllMethods;
6873 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6874 AllMethods.push_back(InstanceMethods[i]);
6875 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6876 AllMethods.push_back(ClassMethods[i]);
6877 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6878 AllMethods.push_back(OptInstanceMethods[i]);
6879 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6880 AllMethods.push_back(OptClassMethods[i]);
6881
6882 Write__extendedMethodTypes_initializer(*this, Context, Result,
6883 AllMethods,
6884 "_OBJC_PROTOCOL_METHOD_TYPES_",
6885 PDecl->getNameAsString());
6886 // Protocol's super protocol list
6887 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
6888 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6889 "_OBJC_PROTOCOL_REFS_",
6890 PDecl->getNameAsString());
6891
6892 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6893 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
6894 PDecl->getNameAsString(), false);
6895
6896 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6897 "_OBJC_PROTOCOL_CLASS_METHODS_",
6898 PDecl->getNameAsString(), false);
6899
6900 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
6901 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
6902 PDecl->getNameAsString(), false);
6903
6904 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
6905 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
6906 PDecl->getNameAsString(), false);
6907
6908 // Protocol's property metadata.
6909 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
6910 PDecl->instance_properties());
6911 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
6912 /* Container */nullptr,
6913 "_OBJC_PROTOCOL_PROPERTIES_",
6914 PDecl->getNameAsString());
6915
6916 // Writer out root metadata for current protocol: struct _protocol_t
6917 Result += "\n";
6918 if (LangOpts.MicrosoftExt)
6919 Result += "static ";
6920 Result += "struct _protocol_t _OBJC_PROTOCOL_";
6921 Result += PDecl->getNameAsString();
6922 Result += " __attribute__ ((used)) = {\n";
6923 Result += "\t0,\n"; // id is; is null
6924 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
6925 if (SuperProtocols.size() > 0) {
6926 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6927 Result += PDecl->getNameAsString(); Result += ",\n";
6928 }
6929 else
6930 Result += "\t0,\n";
6931 if (InstanceMethods.size() > 0) {
6932 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6933 Result += PDecl->getNameAsString(); Result += ",\n";
6934 }
6935 else
6936 Result += "\t0,\n";
6937
6938 if (ClassMethods.size() > 0) {
6939 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6940 Result += PDecl->getNameAsString(); Result += ",\n";
6941 }
6942 else
6943 Result += "\t0,\n";
6944
6945 if (OptInstanceMethods.size() > 0) {
6946 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6947 Result += PDecl->getNameAsString(); Result += ",\n";
6948 }
6949 else
6950 Result += "\t0,\n";
6951
6952 if (OptClassMethods.size() > 0) {
6953 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6954 Result += PDecl->getNameAsString(); Result += ",\n";
6955 }
6956 else
6957 Result += "\t0,\n";
6958
6959 if (ProtocolProperties.size() > 0) {
6960 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6961 Result += PDecl->getNameAsString(); Result += ",\n";
6962 }
6963 else
6964 Result += "\t0,\n";
6965
6966 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6967 Result += "\t0,\n";
6968
6969 if (AllMethods.size() > 0) {
6970 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6971 Result += PDecl->getNameAsString();
6972 Result += "\n};\n";
6973 }
6974 else
6975 Result += "\t0\n};\n";
6976
6977 if (LangOpts.MicrosoftExt)
6978 Result += "static ";
6979 Result += "struct _protocol_t *";
6980 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6981 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6982 Result += ";\n";
6983
6984 // Mark this protocol as having been generated.
6985 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
6986 llvm_unreachable("protocol already synthesized")::llvm::llvm_unreachable_internal("protocol already synthesized"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 6986)
;
6987}
6988
6989/// hasObjCExceptionAttribute - Return true if this class or any super
6990/// class has the __objc_exception__ attribute.
6991/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6992static bool hasObjCExceptionAttribute(ASTContext &Context,
6993 const ObjCInterfaceDecl *OID) {
6994 if (OID->hasAttr<ObjCExceptionAttr>())
6995 return true;
6996 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6997 return hasObjCExceptionAttribute(Context, Super);
6998 return false;
6999}
7000
7001void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7002 std::string &Result) {
7003 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7004
7005 // Explicitly declared @interface's are already synthesized.
7006 if (CDecl->isImplicitInterfaceDecl())
7007 assert(false &&((false && "Legacy implicit interface rewriting not supported in moder abi"
) ? static_cast<void> (0) : __assert_fail ("false && \"Legacy implicit interface rewriting not supported in moder abi\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 7008, __PRETTY_FUNCTION__))
7008 "Legacy implicit interface rewriting not supported in moder abi")((false && "Legacy implicit interface rewriting not supported in moder abi"
) ? static_cast<void> (0) : __assert_fail ("false && \"Legacy implicit interface rewriting not supported in moder abi\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 7008, __PRETTY_FUNCTION__))
;
7009
7010 WriteModernMetadataDeclarations(Context, Result);
7011 SmallVector<ObjCIvarDecl *, 8> IVars;
7012
7013 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7014 IVD; IVD = IVD->getNextIvar()) {
7015 // Ignore unnamed bit-fields.
7016 if (!IVD->getDeclName())
7017 continue;
7018 IVars.push_back(IVD);
7019 }
7020
7021 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
7022 "_OBJC_$_INSTANCE_VARIABLES_",
7023 CDecl);
7024
7025 // Build _objc_method_list for class's instance methods if needed
7026 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7027
7028 // If any of our property implementations have associated getters or
7029 // setters, produce metadata for them as well.
7030 for (const auto *Prop : IDecl->property_impls()) {
7031 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7032 continue;
7033 if (!Prop->getPropertyIvarDecl())
7034 continue;
7035 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7036 if (!PD)
7037 continue;
7038 if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
7039 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
7040 InstanceMethods.push_back(Getter);
7041 if (PD->isReadOnly())
7042 continue;
7043 if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
7044 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
7045 InstanceMethods.push_back(Setter);
7046 }
7047
7048 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7049 "_OBJC_$_INSTANCE_METHODS_",
7050 IDecl->getNameAsString(), true);
7051
7052 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7053
7054 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7055 "_OBJC_$_CLASS_METHODS_",
7056 IDecl->getNameAsString(), true);
7057
7058 // Protocols referenced in class declaration?
7059 // Protocol's super protocol list
7060 std::vector<ObjCProtocolDecl *> RefedProtocols;
7061 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7062 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7063 E = Protocols.end();
7064 I != E; ++I) {
7065 RefedProtocols.push_back(*I);
7066 // Must write out all protocol definitions in current qualifier list,
7067 // and in their nested qualifiers before writing out current definition.
7068 RewriteObjCProtocolMetaData(*I, Result);
7069 }
7070
7071 Write_protocol_list_initializer(Context, Result,
7072 RefedProtocols,
7073 "_OBJC_CLASS_PROTOCOLS_$_",
7074 IDecl->getNameAsString());
7075
7076 // Protocol's property metadata.
7077 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7078 CDecl->instance_properties());
7079 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7080 /* Container */IDecl,
7081 "_OBJC_$_PROP_LIST_",
7082 CDecl->getNameAsString());
7083
7084 // Data for initializing _class_ro_t metaclass meta-data
7085 uint32_t flags = CLS_META;
7086 std::string InstanceSize;
7087 std::string InstanceStart;
7088
7089 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7090 if (classIsHidden)
7091 flags |= OBJC2_CLS_HIDDEN;
7092
7093 if (!CDecl->getSuperClass())
7094 // class is root
7095 flags |= CLS_ROOT;
7096 InstanceSize = "sizeof(struct _class_t)";
7097 InstanceStart = InstanceSize;
7098 Write__class_ro_t_initializer(Context, Result, flags,
7099 InstanceStart, InstanceSize,
7100 ClassMethods,
7101 nullptr,
7102 nullptr,
7103 nullptr,
7104 "_OBJC_METACLASS_RO_$_",
7105 CDecl->getNameAsString());
7106
7107 // Data for initializing _class_ro_t meta-data
7108 flags = CLS;
7109 if (classIsHidden)
7110 flags |= OBJC2_CLS_HIDDEN;
7111
7112 if (hasObjCExceptionAttribute(*Context, CDecl))
7113 flags |= CLS_EXCEPTION;
7114
7115 if (!CDecl->getSuperClass())
7116 // class is root
7117 flags |= CLS_ROOT;
7118
7119 InstanceSize.clear();
7120 InstanceStart.clear();
7121 if (!ObjCSynthesizedStructs.count(CDecl)) {
7122 InstanceSize = "0";
7123 InstanceStart = "0";
7124 }
7125 else {
7126 InstanceSize = "sizeof(struct ";
7127 InstanceSize += CDecl->getNameAsString();
7128 InstanceSize += "_IMPL)";
7129
7130 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7131 if (IVD) {
7132 RewriteIvarOffsetComputation(IVD, InstanceStart);
7133 }
7134 else
7135 InstanceStart = InstanceSize;
7136 }
7137 Write__class_ro_t_initializer(Context, Result, flags,
7138 InstanceStart, InstanceSize,
7139 InstanceMethods,
7140 RefedProtocols,
7141 IVars,
7142 ClassProperties,
7143 "_OBJC_CLASS_RO_$_",
7144 CDecl->getNameAsString());
7145
7146 Write_class_t(Context, Result,
7147 "OBJC_METACLASS_$_",
7148 CDecl, /*metaclass*/true);
7149
7150 Write_class_t(Context, Result,
7151 "OBJC_CLASS_$_",
7152 CDecl, /*metaclass*/false);
7153
7154 if (ImplementationIsNonLazy(IDecl))
7155 DefinedNonLazyClasses.push_back(CDecl);
7156}
7157
7158void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7159 int ClsDefCount = ClassImplementation.size();
7160 if (!ClsDefCount)
7161 return;
7162 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7163 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7164 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7165 for (int i = 0; i < ClsDefCount; i++) {
7166 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7167 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7168 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7169 Result += CDecl->getName(); Result += ",\n";
7170 }
7171 Result += "};\n";
7172}
7173
7174void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7175 int ClsDefCount = ClassImplementation.size();
7176 int CatDefCount = CategoryImplementation.size();
7177
7178 // For each implemented class, write out all its meta data.
7179 for (int i = 0; i < ClsDefCount; i++)
7180 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7181
7182 RewriteClassSetupInitHook(Result);
7183
7184 // For each implemented category, write out all its meta data.
7185 for (int i = 0; i < CatDefCount; i++)
7186 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7187
7188 RewriteCategorySetupInitHook(Result);
7189
7190 if (ClsDefCount > 0) {
7191 if (LangOpts.MicrosoftExt)
7192 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
7193 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7194 Result += llvm::utostr(ClsDefCount); Result += "]";
7195 Result +=
7196 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7197 "regular,no_dead_strip\")))= {\n";
7198 for (int i = 0; i < ClsDefCount; i++) {
7199 Result += "\t&OBJC_CLASS_$_";
7200 Result += ClassImplementation[i]->getNameAsString();
7201 Result += ",\n";
7202 }
7203 Result += "};\n";
7204
7205 if (!DefinedNonLazyClasses.empty()) {
7206 if (LangOpts.MicrosoftExt)
7207 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7208 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7209 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7210 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7211 Result += ",\n";
7212 }
7213 Result += "};\n";
7214 }
7215 }
7216
7217 if (CatDefCount > 0) {
7218 if (LangOpts.MicrosoftExt)
7219 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
7220 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7221 Result += llvm::utostr(CatDefCount); Result += "]";
7222 Result +=
7223 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7224 "regular,no_dead_strip\")))= {\n";
7225 for (int i = 0; i < CatDefCount; i++) {
7226 Result += "\t&_OBJC_$_CATEGORY_";
7227 Result +=
7228 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7229 Result += "_$_";
7230 Result += CategoryImplementation[i]->getNameAsString();
7231 Result += ",\n";
7232 }
7233 Result += "};\n";
7234 }
7235
7236 if (!DefinedNonLazyCategories.empty()) {
7237 if (LangOpts.MicrosoftExt)
7238 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7239 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7240 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7241 Result += "\t&_OBJC_$_CATEGORY_";
7242 Result +=
7243 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7244 Result += "_$_";
7245 Result += DefinedNonLazyCategories[i]->getNameAsString();
7246 Result += ",\n";
7247 }
7248 Result += "};\n";
7249 }
7250}
7251
7252void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7253 if (LangOpts.MicrosoftExt)
7254 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7255
7256 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7257 // version 0, ObjCABI is 2
7258 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
7259}
7260
7261/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7262/// implementation.
7263void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7264 std::string &Result) {
7265 WriteModernMetadataDeclarations(Context, Result);
7266 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7267 // Find category declaration for this implementation.
7268 ObjCCategoryDecl *CDecl
7269 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
7270
7271 std::string FullCategoryName = ClassDecl->getNameAsString();
7272 FullCategoryName += "_$_";
7273 FullCategoryName += CDecl->getNameAsString();
7274
7275 // Build _objc_method_list for class's instance methods if needed
7276 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7277
7278 // If any of our property implementations have associated getters or
7279 // setters, produce metadata for them as well.
7280 for (const auto *Prop : IDecl->property_impls()) {
7281 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7282 continue;
7283 if (!Prop->getPropertyIvarDecl())
7284 continue;
7285 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7286 if (!PD)
7287 continue;
7288 if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
7289 InstanceMethods.push_back(Getter);
7290 if (PD->isReadOnly())
7291 continue;
7292 if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
7293 InstanceMethods.push_back(Setter);
7294 }
7295
7296 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7297 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7298 FullCategoryName, true);
7299
7300 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7301
7302 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7303 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7304 FullCategoryName, true);
7305
7306 // Protocols referenced in class declaration?
7307 // Protocol's super protocol list
7308 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7309 for (auto *I : CDecl->protocols())
7310 // Must write out all protocol definitions in current qualifier list,
7311 // and in their nested qualifiers before writing out current definition.
7312 RewriteObjCProtocolMetaData(I, Result);
7313
7314 Write_protocol_list_initializer(Context, Result,
7315 RefedProtocols,
7316 "_OBJC_CATEGORY_PROTOCOLS_$_",
7317 FullCategoryName);
7318
7319 // Protocol's property metadata.
7320 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7321 CDecl->instance_properties());
7322 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7323 /* Container */IDecl,
7324 "_OBJC_$_PROP_LIST_",
7325 FullCategoryName);
7326
7327 Write_category_t(*this, Context, Result,
7328 CDecl,
7329 ClassDecl,
7330 InstanceMethods,
7331 ClassMethods,
7332 RefedProtocols,
7333 ClassProperties);
7334
7335 // Determine if this category is also "non-lazy".
7336 if (ImplementationIsNonLazy(IDecl))
7337 DefinedNonLazyCategories.push_back(CDecl);
7338}
7339
7340void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7341 int CatDefCount = CategoryImplementation.size();
7342 if (!CatDefCount)
7343 return;
7344 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7345 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7346 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7347 for (int i = 0; i < CatDefCount; i++) {
7348 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7349 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7350 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7351 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7352 Result += ClassDecl->getName();
7353 Result += "_$_";
7354 Result += CatDecl->getName();
7355 Result += ",\n";
7356 }
7357 Result += "};\n";
7358}
7359
7360// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7361/// class methods.
7362template<typename MethodIterator>
7363void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7364 MethodIterator MethodEnd,
7365 bool IsInstanceMethod,
7366 StringRef prefix,
7367 StringRef ClassName,
7368 std::string &Result) {
7369 if (MethodBegin == MethodEnd) return;
7370
7371 if (!objc_impl_method) {
7372 /* struct _objc_method {
7373 SEL _cmd;
7374 char *method_types;
7375 void *_imp;
7376 }
7377 */
7378 Result += "\nstruct _objc_method {\n";
7379 Result += "\tSEL _cmd;\n";
7380 Result += "\tchar *method_types;\n";
7381 Result += "\tvoid *_imp;\n";
7382 Result += "};\n";
7383
7384 objc_impl_method = true;
7385 }
7386
7387 // Build _objc_method_list for class's methods if needed
7388
7389 /* struct {
7390 struct _objc_method_list *next_method;
7391 int method_count;
7392 struct _objc_method method_list[];
7393 }
7394 */
7395 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
7396 Result += "\n";
7397 if (LangOpts.MicrosoftExt) {
7398 if (IsInstanceMethod)
7399 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7400 else
7401 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7402 }
7403 Result += "static struct {\n";
7404 Result += "\tstruct _objc_method_list *next_method;\n";
7405 Result += "\tint method_count;\n";
7406 Result += "\tstruct _objc_method method_list[";
7407 Result += utostr(NumMethods);
7408 Result += "];\n} _OBJC_";
7409 Result += prefix;
7410 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7411 Result += "_METHODS_";
7412 Result += ClassName;
7413 Result += " __attribute__ ((used, section (\"__OBJC, __";
7414 Result += IsInstanceMethod ? "inst" : "cls";
7415 Result += "_meth\")))= ";
7416 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7417
7418 Result += "\t,{{(SEL)\"";
7419 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7420 std::string MethodTypeString;
7421 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7422 Result += "\", \"";
7423 Result += MethodTypeString;
7424 Result += "\", (void *)";
7425 Result += MethodInternalNames[*MethodBegin];
7426 Result += "}\n";
7427 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7428 Result += "\t ,{(SEL)\"";
7429 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7430 std::string MethodTypeString;
7431 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7432 Result += "\", \"";
7433 Result += MethodTypeString;
7434 Result += "\", (void *)";
7435 Result += MethodInternalNames[*MethodBegin];
7436 Result += "}\n";
7437 }
7438 Result += "\t }\n};\n";
7439}
7440
7441Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7442 SourceRange OldRange = IV->getSourceRange();
7443 Expr *BaseExpr = IV->getBase();
7444
7445 // Rewrite the base, but without actually doing replaces.
7446 {
7447 DisableReplaceStmtScope S(*this);
7448 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
1
The object is a 'Expr'
7449 IV->setBase(BaseExpr);
7450 }
7451
7452 ObjCIvarDecl *D = IV->getDecl();
7453
7454 Expr *Replacement = IV;
7455
7456 if (BaseExpr->getType()->isObjCObjectPointerType()) {
2
Calling 'Type::isObjCObjectPointerType'
5
Returning from 'Type::isObjCObjectPointerType'
6
Taking true branch
7457 const ObjCInterfaceType *iFaceDecl =
7458 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7459 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null")((iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null"
) ? static_cast<void> (0) : __assert_fail ("iFaceDecl && \"RewriteObjCIvarRefExpr - iFaceDecl is null\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 7459, __PRETTY_FUNCTION__))
;
7
Assuming 'iFaceDecl' is non-null
8
'?' condition is true
7460 // lookup which class implements the instance variable.
7461 ObjCInterfaceDecl *clsDeclared = nullptr;
7462 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7463 clsDeclared);
7464 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class")((clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class"
) ? static_cast<void> (0) : __assert_fail ("clsDeclared && \"RewriteObjCIvarRefExpr(): Can't find class\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp"
, 7464, __PRETTY_FUNCTION__))
;
9
Assuming 'clsDeclared' is non-null
10
'?' condition is true
7465
7466 // Build name of symbol holding ivar offset.
7467 std::string IvarOffsetName;
7468 if (D->isBitField())
11
Assuming the condition is true
12
Taking true branch
7469 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7470 else
7471 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7472
7473 ReferencedIvars[clsDeclared].insert(D);
7474
7475 // cast offset to "char *".
7476 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7477 Context->getPointerType(Context->CharTy),
7478 CK_BitCast,
7479 BaseExpr);
7480 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7481 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7482 Context->UnsignedLongTy, nullptr,
7483 SC_Extern);
7484 DeclRefExpr *DRE = new (Context)
7485 DeclRefExpr(*Context, NewVD, false, Context->UnsignedLongTy,
7486 VK_LValue, SourceLocation());
7487 BinaryOperator *addExpr =
7488 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7489 Context->getPointerType(Context->CharTy),
7490 VK_RValue, OK_Ordinary, SourceLocation(), FPOptions());
7491 // Don't forget the parens to enforce the proper binding.
7492 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7493 SourceLocation(),
7494 addExpr);
7495 QualType IvarT = D->getType();
7496 if (D->isBitField())
13
Assuming the condition is false
14
Taking false branch
7497 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
7498
7499 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
15
Assuming 'IvarT' is not a 'TypedefType'
16
Calling 'Type::isRecordType'
19
Returning from 'Type::isRecordType'
20
Taking true branch
7500 RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
21
The object is a 'RecordType'
7501 RD = RD->getDefinition();
7502 if (RD
21.1
'RD' is non-null
21.1
'RD' is non-null
&& !RD->getDeclName().getAsIdentifierInfo()) {
22
Taking true branch
7503 // decltype(((Foo_IMPL*)0)->bar) *
7504 ObjCContainerDecl *CDecl =
24
'CDecl' initialized to a null pointer value
7505 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
23
Assuming the object is not a 'ObjCContainerDecl'
7506 // ivar in class extensions requires special treatment.
7507 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
25
Assuming 'CatDecl' is null
26
Taking false branch
7508 CDecl = CatDecl->getClassInterface();
7509 std::string RecName = std::string(CDecl->getName());
27
Called C++ object pointer is null
7510 RecName += "_IMPL";
7511 RecordDecl *RD = RecordDecl::Create(
7512 *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(),
7513 &Context->Idents.get(RecName));
7514 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7515 unsigned UnsignedIntSize =
7516 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7517 Expr *Zero = IntegerLiteral::Create(*Context,
7518 llvm::APInt(UnsignedIntSize, 0),
7519 Context->UnsignedIntTy, SourceLocation());
7520 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7521 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7522 Zero);
7523 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7524 SourceLocation(),
7525 &Context->Idents.get(D->getNameAsString()),
7526 IvarT, nullptr,
7527 /*BitWidth=*/nullptr,
7528 /*Mutable=*/true, ICIS_NoInit);
7529 MemberExpr *ME = MemberExpr::CreateImplicit(
7530 *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
7531 IvarT = Context->getDecltypeType(ME, ME->getType());
7532 }
7533 }
7534 convertObjCTypeToCStyleType(IvarT);
7535 QualType castT = Context->getPointerType(IvarT);
7536
7537 castExpr = NoTypeInfoCStyleCastExpr(Context,
7538 castT,
7539 CK_BitCast,
7540 PE);
7541
7542
7543 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
7544 VK_LValue, OK_Ordinary,
7545 SourceLocation(), false);
7546 PE = new (Context) ParenExpr(OldRange.getBegin(),
7547 OldRange.getEnd(),
7548 Exp);
7549
7550 if (D->isBitField()) {
7551 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7552 SourceLocation(),
7553 &Context->Idents.get(D->getNameAsString()),
7554 D->getType(), nullptr,
7555 /*BitWidth=*/D->getBitWidth(),
7556 /*Mutable=*/true, ICIS_NoInit);
7557 MemberExpr *ME =
7558 MemberExpr::CreateImplicit(*Context, PE, /*isArrow*/ false, FD,
7559 FD->getType(), VK_LValue, OK_Ordinary);
7560 Replacement = ME;
7561
7562 }
7563 else
7564 Replacement = PE;
7565 }
7566
7567 ReplaceStmtWithRange(IV, Replacement, OldRange);
7568 return Replacement;
7569}
7570
7571#endif // CLANG_ENABLE_OBJC_REWRITER

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- 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/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/DependencyFlags.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/TemplateName.h"
23#include "clang/Basic/AddressSpaces.h"
24#include "clang/Basic/AttrKinds.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/ExceptionSpecificationType.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceLocation.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Basic/Visibility.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/APSInt.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/None.h"
38#include "llvm/ADT/Optional.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/Twine.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/PointerLikeTypeTraits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include "llvm/Support/type_traits.h"
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <cstring>
54#include <string>
55#include <type_traits>
56#include <utility>
57
58namespace clang {
59
60class ExtQuals;
61class QualType;
62class ConceptDecl;
63class TagDecl;
64class Type;
65
66enum {
67 TypeAlignmentInBits = 4,
68 TypeAlignment = 1 << TypeAlignmentInBits
69};
70
71namespace serialization {
72 template <class T> class AbstractTypeReader;
73 template <class T> class AbstractTypeWriter;
74}
75
76} // namespace clang
77
78namespace llvm {
79
80 template <typename T>
81 struct PointerLikeTypeTraits;
82 template<>
83 struct PointerLikeTypeTraits< ::clang::Type*> {
84 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
85
86 static inline ::clang::Type *getFromVoidPointer(void *P) {
87 return static_cast< ::clang::Type*>(P);
88 }
89
90 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
91 };
92
93 template<>
94 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
95 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
96
97 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
98 return static_cast< ::clang::ExtQuals*>(P);
99 }
100
101 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
102 };
103
104} // namespace llvm
105
106namespace clang {
107
108class ASTContext;
109template <typename> class CanQual;
110class CXXRecordDecl;
111class DeclContext;
112class EnumDecl;
113class Expr;
114class ExtQualsTypeCommonBase;
115class FunctionDecl;
116class IdentifierInfo;
117class NamedDecl;
118class ObjCInterfaceDecl;
119class ObjCProtocolDecl;
120class ObjCTypeParamDecl;
121struct PrintingPolicy;
122class RecordDecl;
123class Stmt;
124class TagDecl;
125class TemplateArgument;
126class TemplateArgumentListInfo;
127class TemplateArgumentLoc;
128class TemplateTypeParmDecl;
129class TypedefNameDecl;
130class UnresolvedUsingTypenameDecl;
131
132using CanQualType = CanQual<Type>;
133
134// Provide forward declarations for all of the *Type classes.
135#define TYPE(Class, Base) class Class##Type;
136#include "clang/AST/TypeNodes.inc"
137
138/// The collection of all-type qualifiers we support.
139/// Clang supports five independent qualifiers:
140/// * C99: const, volatile, and restrict
141/// * MS: __unaligned
142/// * Embedded C (TR18037): address spaces
143/// * Objective C: the GC attributes (none, weak, or strong)
144class Qualifiers {
145public:
146 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
147 Const = 0x1,
148 Restrict = 0x2,
149 Volatile = 0x4,
150 CVRMask = Const | Volatile | Restrict
151 };
152
153 enum GC {
154 GCNone = 0,
155 Weak,
156 Strong
157 };
158
159 enum ObjCLifetime {
160 /// There is no lifetime qualification on this type.
161 OCL_None,
162
163 /// This object can be modified without requiring retains or
164 /// releases.
165 OCL_ExplicitNone,
166
167 /// Assigning into this object requires the old value to be
168 /// released and the new value to be retained. The timing of the
169 /// release of the old value is inexact: it may be moved to
170 /// immediately after the last known point where the value is
171 /// live.
172 OCL_Strong,
173
174 /// Reading or writing from this object requires a barrier call.
175 OCL_Weak,
176
177 /// Assigning into this object requires a lifetime extension.
178 OCL_Autoreleasing
179 };
180
181 enum {
182 /// The maximum supported address space number.
183 /// 23 bits should be enough for anyone.
184 MaxAddressSpace = 0x7fffffu,
185
186 /// The width of the "fast" qualifier mask.
187 FastWidth = 3,
188
189 /// The fast qualifier mask.
190 FastMask = (1 << FastWidth) - 1
191 };
192
193 /// Returns the common set of qualifiers while removing them from
194 /// the given sets.
195 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
196 // If both are only CVR-qualified, bit operations are sufficient.
197 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
198 Qualifiers Q;
199 Q.Mask = L.Mask & R.Mask;
200 L.Mask &= ~Q.Mask;
201 R.Mask &= ~Q.Mask;
202 return Q;
203 }
204
205 Qualifiers Q;
206 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
207 Q.addCVRQualifiers(CommonCRV);
208 L.removeCVRQualifiers(CommonCRV);
209 R.removeCVRQualifiers(CommonCRV);
210
211 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
212 Q.setObjCGCAttr(L.getObjCGCAttr());
213 L.removeObjCGCAttr();
214 R.removeObjCGCAttr();
215 }
216
217 if (L.getObjCLifetime() == R.getObjCLifetime()) {
218 Q.setObjCLifetime(L.getObjCLifetime());
219 L.removeObjCLifetime();
220 R.removeObjCLifetime();
221 }
222
223 if (L.getAddressSpace() == R.getAddressSpace()) {
224 Q.setAddressSpace(L.getAddressSpace());
225 L.removeAddressSpace();
226 R.removeAddressSpace();
227 }
228 return Q;
229 }
230
231 static Qualifiers fromFastMask(unsigned Mask) {
232 Qualifiers Qs;
233 Qs.addFastQualifiers(Mask);
234 return Qs;
235 }
236
237 static Qualifiers fromCVRMask(unsigned CVR) {
238 Qualifiers Qs;
239 Qs.addCVRQualifiers(CVR);
240 return Qs;
241 }
242
243 static Qualifiers fromCVRUMask(unsigned CVRU) {
244 Qualifiers Qs;
245 Qs.addCVRUQualifiers(CVRU);
246 return Qs;
247 }
248
249 // Deserialize qualifiers from an opaque representation.
250 static Qualifiers fromOpaqueValue(unsigned opaque) {
251 Qualifiers Qs;
252 Qs.Mask = opaque;
253 return Qs;
254 }
255
256 // Serialize these qualifiers into an opaque representation.
257 unsigned getAsOpaqueValue() const {
258 return Mask;
259 }
260
261 bool hasConst() const { return Mask & Const; }
262 bool hasOnlyConst() const { return Mask == Const; }
263 void removeConst() { Mask &= ~Const; }
264 void addConst() { Mask |= Const; }
265
266 bool hasVolatile() const { return Mask & Volatile; }
267 bool hasOnlyVolatile() const { return Mask == Volatile; }
268 void removeVolatile() { Mask &= ~Volatile; }
269 void addVolatile() { Mask |= Volatile; }
270
271 bool hasRestrict() const { return Mask & Restrict; }
272 bool hasOnlyRestrict() const { return Mask == Restrict; }
273 void removeRestrict() { Mask &= ~Restrict; }
274 void addRestrict() { Mask |= Restrict; }
275
276 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
277 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
278 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
279
280 void setCVRQualifiers(unsigned mask) {
281 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 281, __PRETTY_FUNCTION__))
;
282 Mask = (Mask & ~CVRMask) | mask;
283 }
284 void removeCVRQualifiers(unsigned mask) {
285 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 285, __PRETTY_FUNCTION__))
;
286 Mask &= ~mask;
287 }
288 void removeCVRQualifiers() {
289 removeCVRQualifiers(CVRMask);
290 }
291 void addCVRQualifiers(unsigned mask) {
292 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 292, __PRETTY_FUNCTION__))
;
293 Mask |= mask;
294 }
295 void addCVRUQualifiers(unsigned mask) {
296 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 296, __PRETTY_FUNCTION__))
;
297 Mask |= mask;
298 }
299
300 bool hasUnaligned() const { return Mask & UMask; }
301 void setUnaligned(bool flag) {
302 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
303 }
304 void removeUnaligned() { Mask &= ~UMask; }
305 void addUnaligned() { Mask |= UMask; }
306
307 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
308 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
309 void setObjCGCAttr(GC type) {
310 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
311 }
312 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
313 void addObjCGCAttr(GC type) {
314 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 314, __PRETTY_FUNCTION__))
;
315 setObjCGCAttr(type);
316 }
317 Qualifiers withoutObjCGCAttr() const {
318 Qualifiers qs = *this;
319 qs.removeObjCGCAttr();
320 return qs;
321 }
322 Qualifiers withoutObjCLifetime() const {
323 Qualifiers qs = *this;
324 qs.removeObjCLifetime();
325 return qs;
326 }
327 Qualifiers withoutAddressSpace() const {
328 Qualifiers qs = *this;
329 qs.removeAddressSpace();
330 return qs;
331 }
332
333 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
334 ObjCLifetime getObjCLifetime() const {
335 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
336 }
337 void setObjCLifetime(ObjCLifetime type) {
338 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
339 }
340 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
341 void addObjCLifetime(ObjCLifetime type) {
342 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 342, __PRETTY_FUNCTION__))
;
343 assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 343, __PRETTY_FUNCTION__))
;
344 Mask |= (type << LifetimeShift);
345 }
346
347 /// True if the lifetime is neither None or ExplicitNone.
348 bool hasNonTrivialObjCLifetime() const {
349 ObjCLifetime lifetime = getObjCLifetime();
350 return (lifetime > OCL_ExplicitNone);
351 }
352
353 /// True if the lifetime is either strong or weak.
354 bool hasStrongOrWeakObjCLifetime() const {
355 ObjCLifetime lifetime = getObjCLifetime();
356 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
357 }
358
359 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
360 LangAS getAddressSpace() const {
361 return static_cast<LangAS>(Mask >> AddressSpaceShift);
362 }
363 bool hasTargetSpecificAddressSpace() const {
364 return isTargetAddressSpace(getAddressSpace());
365 }
366 /// Get the address space attribute value to be printed by diagnostics.
367 unsigned getAddressSpaceAttributePrintValue() const {
368 auto Addr = getAddressSpace();
369 // This function is not supposed to be used with language specific
370 // address spaces. If that happens, the diagnostic message should consider
371 // printing the QualType instead of the address space value.
372 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace())
? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 372, __PRETTY_FUNCTION__))
;
373 if (Addr != LangAS::Default)
374 return toTargetAddressSpace(Addr);
375 // TODO: The diagnostic messages where Addr may be 0 should be fixed
376 // since it cannot differentiate the situation where 0 denotes the default
377 // address space or user specified __attribute__((address_space(0))).
378 return 0;
379 }
380 void setAddressSpace(LangAS space) {
381 assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void
> (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 381, __PRETTY_FUNCTION__))
;
382 Mask = (Mask & ~AddressSpaceMask)
383 | (((uint32_t) space) << AddressSpaceShift);
384 }
385 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
386 void addAddressSpace(LangAS space) {
387 assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail
("space != LangAS::Default", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 387, __PRETTY_FUNCTION__))
;
388 setAddressSpace(space);
389 }
390
391 // Fast qualifiers are those that can be allocated directly
392 // on a QualType object.
393 bool hasFastQualifiers() const { return getFastQualifiers(); }
394 unsigned getFastQualifiers() const { return Mask & FastMask; }
395 void setFastQualifiers(unsigned mask) {
396 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 396, __PRETTY_FUNCTION__))
;
397 Mask = (Mask & ~FastMask) | mask;
398 }
399 void removeFastQualifiers(unsigned mask) {
400 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 400, __PRETTY_FUNCTION__))
;
401 Mask &= ~mask;
402 }
403 void removeFastQualifiers() {
404 removeFastQualifiers(FastMask);
405 }
406 void addFastQualifiers(unsigned mask) {
407 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 407, __PRETTY_FUNCTION__))
;
408 Mask |= mask;
409 }
410
411 /// Return true if the set contains any qualifiers which require an ExtQuals
412 /// node to be allocated.
413 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
414 Qualifiers getNonFastQualifiers() const {
415 Qualifiers Quals = *this;
416 Quals.setFastQualifiers(0);
417 return Quals;
418 }
419
420 /// Return true if the set contains any qualifiers.
421 bool hasQualifiers() const { return Mask; }
422 bool empty() const { return !Mask; }
423
424 /// Add the qualifiers from the given set to this set.
425 void addQualifiers(Qualifiers Q) {
426 // If the other set doesn't have any non-boolean qualifiers, just
427 // bit-or it in.
428 if (!(Q.Mask & ~CVRMask))
429 Mask |= Q.Mask;
430 else {
431 Mask |= (Q.Mask & CVRMask);
432 if (Q.hasAddressSpace())
433 addAddressSpace(Q.getAddressSpace());
434 if (Q.hasObjCGCAttr())
435 addObjCGCAttr(Q.getObjCGCAttr());
436 if (Q.hasObjCLifetime())
437 addObjCLifetime(Q.getObjCLifetime());
438 }
439 }
440
441 /// Remove the qualifiers from the given set from this set.
442 void removeQualifiers(Qualifiers Q) {
443 // If the other set doesn't have any non-boolean qualifiers, just
444 // bit-and the inverse in.
445 if (!(Q.Mask & ~CVRMask))
446 Mask &= ~Q.Mask;
447 else {
448 Mask &= ~(Q.Mask & CVRMask);
449 if (getObjCGCAttr() == Q.getObjCGCAttr())
450 removeObjCGCAttr();
451 if (getObjCLifetime() == Q.getObjCLifetime())
452 removeObjCLifetime();
453 if (getAddressSpace() == Q.getAddressSpace())
454 removeAddressSpace();
455 }
456 }
457
458 /// Add the qualifiers from the given set to this set, given that
459 /// they don't conflict.
460 void addConsistentQualifiers(Qualifiers qs) {
461 assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 462, __PRETTY_FUNCTION__))
462 !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 462, __PRETTY_FUNCTION__))
;
463 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 464, __PRETTY_FUNCTION__))
464 !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 464, __PRETTY_FUNCTION__))
;
465 assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 466, __PRETTY_FUNCTION__))
466 !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 466, __PRETTY_FUNCTION__))
;
467 Mask |= qs.Mask;
468 }
469
470 /// Returns true if address space A is equal to or a superset of B.
471 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
472 /// overlapping address spaces.
473 /// CL1.1 or CL1.2:
474 /// every address space is a superset of itself.
475 /// CL2.0 adds:
476 /// __generic is a superset of any address space except for __constant.
477 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
478 // Address spaces must match exactly.
479 return A == B ||
480 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
481 // for __constant can be used as __generic.
482 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
483 // Consider pointer size address spaces to be equivalent to default.
484 ((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
485 (isPtrSizeAddressSpace(B) || B == LangAS::Default));
486 }
487
488 /// Returns true if the address space in these qualifiers is equal to or
489 /// a superset of the address space in the argument qualifiers.
490 bool isAddressSpaceSupersetOf(Qualifiers other) const {
491 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
492 }
493
494 /// Determines if these qualifiers compatibly include another set.
495 /// Generally this answers the question of whether an object with the other
496 /// qualifiers can be safely used as an object with these qualifiers.
497 bool compatiblyIncludes(Qualifiers other) const {
498 return isAddressSpaceSupersetOf(other) &&
499 // ObjC GC qualifiers can match, be added, or be removed, but can't
500 // be changed.
501 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
502 !other.hasObjCGCAttr()) &&
503 // ObjC lifetime qualifiers must match exactly.
504 getObjCLifetime() == other.getObjCLifetime() &&
505 // CVR qualifiers may subset.
506 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
507 // U qualifier may superset.
508 (!other.hasUnaligned() || hasUnaligned());
509 }
510
511 /// Determines if these qualifiers compatibly include another set of
512 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
513 ///
514 /// One set of Objective-C lifetime qualifiers compatibly includes the other
515 /// if the lifetime qualifiers match, or if both are non-__weak and the
516 /// including set also contains the 'const' qualifier, or both are non-__weak
517 /// and one is None (which can only happen in non-ARC modes).
518 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
519 if (getObjCLifetime() == other.getObjCLifetime())
520 return true;
521
522 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
523 return false;
524
525 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
526 return true;
527
528 return hasConst();
529 }
530
531 /// Determine whether this set of qualifiers is a strict superset of
532 /// another set of qualifiers, not considering qualifier compatibility.
533 bool isStrictSupersetOf(Qualifiers Other) const;
534
535 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
536 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
537
538 explicit operator bool() const { return hasQualifiers(); }
539
540 Qualifiers &operator+=(Qualifiers R) {
541 addQualifiers(R);
542 return *this;
543 }
544
545 // Union two qualifier sets. If an enumerated qualifier appears
546 // in both sets, use the one from the right.
547 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
548 L += R;
549 return L;
550 }
551
552 Qualifiers &operator-=(Qualifiers R) {
553 removeQualifiers(R);
554 return *this;
555 }
556
557 /// Compute the difference between two qualifier sets.
558 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
559 L -= R;
560 return L;
561 }
562
563 std::string getAsString() const;
564 std::string getAsString(const PrintingPolicy &Policy) const;
565
566 static std::string getAddrSpaceAsString(LangAS AS);
567
568 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
569 void print(raw_ostream &OS, const PrintingPolicy &Policy,
570 bool appendSpaceIfNonEmpty = false) const;
571
572 void Profile(llvm::FoldingSetNodeID &ID) const {
573 ID.AddInteger(Mask);
574 }
575
576private:
577 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
578 // |C R V|U|GCAttr|Lifetime|AddressSpace|
579 uint32_t Mask = 0;
580
581 static const uint32_t UMask = 0x8;
582 static const uint32_t UShift = 3;
583 static const uint32_t GCAttrMask = 0x30;
584 static const uint32_t GCAttrShift = 4;
585 static const uint32_t LifetimeMask = 0x1C0;
586 static const uint32_t LifetimeShift = 6;
587 static const uint32_t AddressSpaceMask =
588 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
589 static const uint32_t AddressSpaceShift = 9;
590};
591
592/// A std::pair-like structure for storing a qualified type split
593/// into its local qualifiers and its locally-unqualified type.
594struct SplitQualType {
595 /// The locally-unqualified type.
596 const Type *Ty = nullptr;
597
598 /// The local qualifiers.
599 Qualifiers Quals;
600
601 SplitQualType() = default;
602 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
603
604 SplitQualType getSingleStepDesugaredType() const; // end of this file
605
606 // Make std::tie work.
607 std::pair<const Type *,Qualifiers> asPair() const {
608 return std::pair<const Type *, Qualifiers>(Ty, Quals);
609 }
610
611 friend bool operator==(SplitQualType a, SplitQualType b) {
612 return a.Ty == b.Ty && a.Quals == b.Quals;
613 }
614 friend bool operator!=(SplitQualType a, SplitQualType b) {
615 return a.Ty != b.Ty || a.Quals != b.Quals;
616 }
617};
618
619/// The kind of type we are substituting Objective-C type arguments into.
620///
621/// The kind of substitution affects the replacement of type parameters when
622/// no concrete type information is provided, e.g., when dealing with an
623/// unspecialized type.
624enum class ObjCSubstitutionContext {
625 /// An ordinary type.
626 Ordinary,
627
628 /// The result type of a method or function.
629 Result,
630
631 /// The parameter type of a method or function.
632 Parameter,
633
634 /// The type of a property.
635 Property,
636
637 /// The superclass of a type.
638 Superclass,
639};
640
641/// A (possibly-)qualified type.
642///
643/// For efficiency, we don't store CV-qualified types as nodes on their
644/// own: instead each reference to a type stores the qualifiers. This
645/// greatly reduces the number of nodes we need to allocate for types (for
646/// example we only need one for 'int', 'const int', 'volatile int',
647/// 'const volatile int', etc).
648///
649/// As an added efficiency bonus, instead of making this a pair, we
650/// just store the two bits we care about in the low bits of the
651/// pointer. To handle the packing/unpacking, we make QualType be a
652/// simple wrapper class that acts like a smart pointer. A third bit
653/// indicates whether there are extended qualifiers present, in which
654/// case the pointer points to a special structure.
655class QualType {
656 friend class QualifierCollector;
657
658 // Thankfully, these are efficiently composable.
659 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
660 Qualifiers::FastWidth> Value;
661
662 const ExtQuals *getExtQualsUnsafe() const {
663 return Value.getPointer().get<const ExtQuals*>();
664 }
665
666 const Type *getTypePtrUnsafe() const {
667 return Value.getPointer().get<const Type*>();
668 }
669
670 const ExtQualsTypeCommonBase *getCommonPtr() const {
671 assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer")
? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 671, __PRETTY_FUNCTION__))
;
672 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
673 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
674 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
675 }
676
677public:
678 QualType() = default;
679 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
680 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
681
682 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
683 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
684
685 /// Retrieves a pointer to the underlying (unqualified) type.
686 ///
687 /// This function requires that the type not be NULL. If the type might be
688 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
689 const Type *getTypePtr() const;
690
691 const Type *getTypePtrOrNull() const;
692
693 /// Retrieves a pointer to the name of the base type.
694 const IdentifierInfo *getBaseTypeIdentifier() const;
695
696 /// Divides a QualType into its unqualified type and a set of local
697 /// qualifiers.
698 SplitQualType split() const;
699
700 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
701
702 static QualType getFromOpaquePtr(const void *Ptr) {
703 QualType T;
704 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
705 return T;
706 }
707
708 const Type &operator*() const {
709 return *getTypePtr();
710 }
711
712 const Type *operator->() const {
713 return getTypePtr();
714 }
715
716 bool isCanonical() const;
717 bool isCanonicalAsParam() const;
718
719 /// Return true if this QualType doesn't point to a type yet.
720 bool isNull() const {
721 return Value.getPointer().isNull();
722 }
723
724 /// Determine whether this particular QualType instance has the
725 /// "const" qualifier set, without looking through typedefs that may have
726 /// added "const" at a different level.
727 bool isLocalConstQualified() const {
728 return (getLocalFastQualifiers() & Qualifiers::Const);
729 }
730
731 /// Determine whether this type is const-qualified.
732 bool isConstQualified() const;
733
734 /// Determine whether this particular QualType instance has the
735 /// "restrict" qualifier set, without looking through typedefs that may have
736 /// added "restrict" at a different level.
737 bool isLocalRestrictQualified() const {
738 return (getLocalFastQualifiers() & Qualifiers::Restrict);
739 }
740
741 /// Determine whether this type is restrict-qualified.
742 bool isRestrictQualified() const;
743
744 /// Determine whether this particular QualType instance has the
745 /// "volatile" qualifier set, without looking through typedefs that may have
746 /// added "volatile" at a different level.
747 bool isLocalVolatileQualified() const {
748 return (getLocalFastQualifiers() & Qualifiers::Volatile);
749 }
750
751 /// Determine whether this type is volatile-qualified.
752 bool isVolatileQualified() const;
753
754 /// Determine whether this particular QualType instance has any
755 /// qualifiers, without looking through any typedefs that might add
756 /// qualifiers at a different level.
757 bool hasLocalQualifiers() const {
758 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
759 }
760
761 /// Determine whether this type has any qualifiers.
762 bool hasQualifiers() const;
763
764 /// Determine whether this particular QualType instance has any
765 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
766 /// instance.
767 bool hasLocalNonFastQualifiers() const {
768 return Value.getPointer().is<const ExtQuals*>();
769 }
770
771 /// Retrieve the set of qualifiers local to this particular QualType
772 /// instance, not including any qualifiers acquired through typedefs or
773 /// other sugar.
774 Qualifiers getLocalQualifiers() const;
775
776 /// Retrieve the set of qualifiers applied to this type.
777 Qualifiers getQualifiers() const;
778
779 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
780 /// local to this particular QualType instance, not including any qualifiers
781 /// acquired through typedefs or other sugar.
782 unsigned getLocalCVRQualifiers() const {
783 return getLocalFastQualifiers();
784 }
785
786 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
787 /// applied to this type.
788 unsigned getCVRQualifiers() const;
789
790 bool isConstant(const ASTContext& Ctx) const {
791 return QualType::isConstant(*this, Ctx);
792 }
793
794 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
795 bool isPODType(const ASTContext &Context) const;
796
797 /// Return true if this is a POD type according to the rules of the C++98
798 /// standard, regardless of the current compilation's language.
799 bool isCXX98PODType(const ASTContext &Context) const;
800
801 /// Return true if this is a POD type according to the more relaxed rules
802 /// of the C++11 standard, regardless of the current compilation's language.
803 /// (C++0x [basic.types]p9). Note that, unlike
804 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
805 bool isCXX11PODType(const ASTContext &Context) const;
806
807 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
808 bool isTrivialType(const ASTContext &Context) const;
809
810 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
811 bool isTriviallyCopyableType(const ASTContext &Context) const;
812
813
814 /// Returns true if it is a class and it might be dynamic.
815 bool mayBeDynamicClass() const;
816
817 /// Returns true if it is not a class or if the class might not be dynamic.
818 bool mayBeNotDynamicClass() const;
819
820 // Don't promise in the API that anything besides 'const' can be
821 // easily added.
822
823 /// Add the `const` type qualifier to this QualType.
824 void addConst() {
825 addFastQualifiers(Qualifiers::Const);
826 }
827 QualType withConst() const {
828 return withFastQualifiers(Qualifiers::Const);
829 }
830
831 /// Add the `volatile` type qualifier to this QualType.
832 void addVolatile() {
833 addFastQualifiers(Qualifiers::Volatile);
834 }
835 QualType withVolatile() const {
836 return withFastQualifiers(Qualifiers::Volatile);
837 }
838
839 /// Add the `restrict` qualifier to this QualType.
840 void addRestrict() {
841 addFastQualifiers(Qualifiers::Restrict);
842 }
843 QualType withRestrict() const {
844 return withFastQualifiers(Qualifiers::Restrict);
845 }
846
847 QualType withCVRQualifiers(unsigned CVR) const {
848 return withFastQualifiers(CVR);
849 }
850
851 void addFastQualifiers(unsigned TQs) {
852 assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 853, __PRETTY_FUNCTION__))
853 && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 853, __PRETTY_FUNCTION__))
;
854 Value.setInt(Value.getInt() | TQs);
855 }
856
857 void removeLocalConst();
858 void removeLocalVolatile();
859 void removeLocalRestrict();
860 void removeLocalCVRQualifiers(unsigned Mask);
861
862 void removeLocalFastQualifiers() { Value.setInt(0); }
863 void removeLocalFastQualifiers(unsigned Mask) {
864 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 864, __PRETTY_FUNCTION__))
;
865 Value.setInt(Value.getInt() & ~Mask);
866 }
867
868 // Creates a type with the given qualifiers in addition to any
869 // qualifiers already on this type.
870 QualType withFastQualifiers(unsigned TQs) const {
871 QualType T = *this;
872 T.addFastQualifiers(TQs);
873 return T;
874 }
875
876 // Creates a type with exactly the given fast qualifiers, removing
877 // any existing fast qualifiers.
878 QualType withExactLocalFastQualifiers(unsigned TQs) const {
879 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
880 }
881
882 // Removes fast qualifiers, but leaves any extended qualifiers in place.
883 QualType withoutLocalFastQualifiers() const {
884 QualType T = *this;
885 T.removeLocalFastQualifiers();
886 return T;
887 }
888
889 QualType getCanonicalType() const;
890
891 /// Return this type with all of the instance-specific qualifiers
892 /// removed, but without removing any qualifiers that may have been applied
893 /// through typedefs.
894 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
895
896 /// Retrieve the unqualified variant of the given type,
897 /// removing as little sugar as possible.
898 ///
899 /// This routine looks through various kinds of sugar to find the
900 /// least-desugared type that is unqualified. For example, given:
901 ///
902 /// \code
903 /// typedef int Integer;
904 /// typedef const Integer CInteger;
905 /// typedef CInteger DifferenceType;
906 /// \endcode
907 ///
908 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
909 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
910 ///
911 /// The resulting type might still be qualified if it's sugar for an array
912 /// type. To strip qualifiers even from within a sugared array type, use
913 /// ASTContext::getUnqualifiedArrayType.
914 inline QualType getUnqualifiedType() const;
915
916 /// Retrieve the unqualified variant of the given type, removing as little
917 /// sugar as possible.
918 ///
919 /// Like getUnqualifiedType(), but also returns the set of
920 /// qualifiers that were built up.
921 ///
922 /// The resulting type might still be qualified if it's sugar for an array
923 /// type. To strip qualifiers even from within a sugared array type, use
924 /// ASTContext::getUnqualifiedArrayType.
925 inline SplitQualType getSplitUnqualifiedType() const;
926
927 /// Determine whether this type is more qualified than the other
928 /// given type, requiring exact equality for non-CVR qualifiers.
929 bool isMoreQualifiedThan(QualType Other) const;
930
931 /// Determine whether this type is at least as qualified as the other
932 /// given type, requiring exact equality for non-CVR qualifiers.
933 bool isAtLeastAsQualifiedAs(QualType Other) const;
934
935 QualType getNonReferenceType() const;
936
937 /// Determine the type of a (typically non-lvalue) expression with the
938 /// specified result type.
939 ///
940 /// This routine should be used for expressions for which the return type is
941 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
942 /// an lvalue. It removes a top-level reference (since there are no
943 /// expressions of reference type) and deletes top-level cvr-qualifiers
944 /// from non-class types (in C++) or all types (in C).
945 QualType getNonLValueExprType(const ASTContext &Context) const;
946
947 /// Return the specified type with any "sugar" removed from
948 /// the type. This takes off typedefs, typeof's etc. If the outer level of
949 /// the type is already concrete, it returns it unmodified. This is similar
950 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
951 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
952 /// concrete.
953 ///
954 /// Qualifiers are left in place.
955 QualType getDesugaredType(const ASTContext &Context) const {
956 return getDesugaredType(*this, Context);
957 }
958
959 SplitQualType getSplitDesugaredType() const {
960 return getSplitDesugaredType(*this);
961 }
962
963 /// Return the specified type with one level of "sugar" removed from
964 /// the type.
965 ///
966 /// This routine takes off the first typedef, typeof, etc. If the outer level
967 /// of the type is already concrete, it returns it unmodified.
968 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
969 return getSingleStepDesugaredTypeImpl(*this, Context);
970 }
971
972 /// Returns the specified type after dropping any
973 /// outer-level parentheses.
974 QualType IgnoreParens() const {
975 if (isa<ParenType>(*this))
976 return QualType::IgnoreParens(*this);
977 return *this;
978 }
979
980 /// Indicate whether the specified types and qualifiers are identical.
981 friend bool operator==(const QualType &LHS, const QualType &RHS) {
982 return LHS.Value == RHS.Value;
983 }
984 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
985 return LHS.Value != RHS.Value;
986 }
987 friend bool operator<(const QualType &LHS, const QualType &RHS) {
988 return LHS.Value < RHS.Value;
989 }
990
991 static std::string getAsString(SplitQualType split,
992 const PrintingPolicy &Policy) {
993 return getAsString(split.Ty, split.Quals, Policy);
994 }
995 static std::string getAsString(const Type *ty, Qualifiers qs,
996 const PrintingPolicy &Policy);
997
998 std::string getAsString() const;
999 std::string getAsString(const PrintingPolicy &Policy) const;
1000
1001 void print(raw_ostream &OS, const PrintingPolicy &Policy,
1002 const Twine &PlaceHolder = Twine(),
1003 unsigned Indentation = 0) const;
1004
1005 static void print(SplitQualType split, raw_ostream &OS,
1006 const PrintingPolicy &policy, const Twine &PlaceHolder,
1007 unsigned Indentation = 0) {
1008 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1009 }
1010
1011 static void print(const Type *ty, Qualifiers qs,
1012 raw_ostream &OS, const PrintingPolicy &policy,
1013 const Twine &PlaceHolder,
1014 unsigned Indentation = 0);
1015
1016 void getAsStringInternal(std::string &Str,
1017 const PrintingPolicy &Policy) const;
1018
1019 static void getAsStringInternal(SplitQualType split, std::string &out,
1020 const PrintingPolicy &policy) {
1021 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1022 }
1023
1024 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1025 std::string &out,
1026 const PrintingPolicy &policy);
1027
1028 class StreamedQualTypeHelper {
1029 const QualType &T;
1030 const PrintingPolicy &Policy;
1031 const Twine &PlaceHolder;
1032 unsigned Indentation;
1033
1034 public:
1035 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1036 const Twine &PlaceHolder, unsigned Indentation)
1037 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1038 Indentation(Indentation) {}
1039
1040 friend raw_ostream &operator<<(raw_ostream &OS,
1041 const StreamedQualTypeHelper &SQT) {
1042 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1043 return OS;
1044 }
1045 };
1046
1047 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1048 const Twine &PlaceHolder = Twine(),
1049 unsigned Indentation = 0) const {
1050 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1051 }
1052
1053 void dump(const char *s) const;
1054 void dump() const;
1055 void dump(llvm::raw_ostream &OS) const;
1056
1057 void Profile(llvm::FoldingSetNodeID &ID) const {
1058 ID.AddPointer(getAsOpaquePtr());
1059 }
1060
1061 /// Check if this type has any address space qualifier.
1062 inline bool hasAddressSpace() const;
1063
1064 /// Return the address space of this type.
1065 inline LangAS getAddressSpace() const;
1066
1067 /// Returns gc attribute of this type.
1068 inline Qualifiers::GC getObjCGCAttr() const;
1069
1070 /// true when Type is objc's weak.
1071 bool isObjCGCWeak() const {
1072 return getObjCGCAttr() == Qualifiers::Weak;
1073 }
1074
1075 /// true when Type is objc's strong.
1076 bool isObjCGCStrong() const {
1077 return getObjCGCAttr() == Qualifiers::Strong;
1078 }
1079
1080 /// Returns lifetime attribute of this type.
1081 Qualifiers::ObjCLifetime getObjCLifetime() const {
1082 return getQualifiers().getObjCLifetime();
1083 }
1084
1085 bool hasNonTrivialObjCLifetime() const {
1086 return getQualifiers().hasNonTrivialObjCLifetime();
1087 }
1088
1089 bool hasStrongOrWeakObjCLifetime() const {
1090 return getQualifiers().hasStrongOrWeakObjCLifetime();
1091 }
1092
1093 // true when Type is objc's weak and weak is enabled but ARC isn't.
1094 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1095
1096 enum PrimitiveDefaultInitializeKind {
1097 /// The type does not fall into any of the following categories. Note that
1098 /// this case is zero-valued so that values of this enum can be used as a
1099 /// boolean condition for non-triviality.
1100 PDIK_Trivial,
1101
1102 /// The type is an Objective-C retainable pointer type that is qualified
1103 /// with the ARC __strong qualifier.
1104 PDIK_ARCStrong,
1105
1106 /// The type is an Objective-C retainable pointer type that is qualified
1107 /// with the ARC __weak qualifier.
1108 PDIK_ARCWeak,
1109
1110 /// The type is a struct containing a field whose type is not PCK_Trivial.
1111 PDIK_Struct
1112 };
1113
1114 /// Functions to query basic properties of non-trivial C struct types.
1115
1116 /// Check if this is a non-trivial type that would cause a C struct
1117 /// transitively containing this type to be non-trivial to default initialize
1118 /// and return the kind.
1119 PrimitiveDefaultInitializeKind
1120 isNonTrivialToPrimitiveDefaultInitialize() const;
1121
1122 enum PrimitiveCopyKind {
1123 /// The type does not fall into any of the following categories. Note that
1124 /// this case is zero-valued so that values of this enum can be used as a
1125 /// boolean condition for non-triviality.
1126 PCK_Trivial,
1127
1128 /// The type would be trivial except that it is volatile-qualified. Types
1129 /// that fall into one of the other non-trivial cases may additionally be
1130 /// volatile-qualified.
1131 PCK_VolatileTrivial,
1132
1133 /// The type is an Objective-C retainable pointer type that is qualified
1134 /// with the ARC __strong qualifier.
1135 PCK_ARCStrong,
1136
1137 /// The type is an Objective-C retainable pointer type that is qualified
1138 /// with the ARC __weak qualifier.
1139 PCK_ARCWeak,
1140
1141 /// The type is a struct containing a field whose type is neither
1142 /// PCK_Trivial nor PCK_VolatileTrivial.
1143 /// Note that a C++ struct type does not necessarily match this; C++ copying
1144 /// semantics are too complex to express here, in part because they depend
1145 /// on the exact constructor or assignment operator that is chosen by
1146 /// overload resolution to do the copy.
1147 PCK_Struct
1148 };
1149
1150 /// Check if this is a non-trivial type that would cause a C struct
1151 /// transitively containing this type to be non-trivial to copy and return the
1152 /// kind.
1153 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1154
1155 /// Check if this is a non-trivial type that would cause a C struct
1156 /// transitively containing this type to be non-trivial to destructively
1157 /// move and return the kind. Destructive move in this context is a C++-style
1158 /// move in which the source object is placed in a valid but unspecified state
1159 /// after it is moved, as opposed to a truly destructive move in which the
1160 /// source object is placed in an uninitialized state.
1161 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1162
1163 enum DestructionKind {
1164 DK_none,
1165 DK_cxx_destructor,
1166 DK_objc_strong_lifetime,
1167 DK_objc_weak_lifetime,
1168 DK_nontrivial_c_struct
1169 };
1170
1171 /// Returns a nonzero value if objects of this type require
1172 /// non-trivial work to clean up after. Non-zero because it's
1173 /// conceivable that qualifiers (objc_gc(weak)?) could make
1174 /// something require destruction.
1175 DestructionKind isDestructedType() const {
1176 return isDestructedTypeImpl(*this);
1177 }
1178
1179 /// Check if this is or contains a C union that is non-trivial to
1180 /// default-initialize, which is a union that has a member that is non-trivial
1181 /// to default-initialize. If this returns true,
1182 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1183 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1184
1185 /// Check if this is or contains a C union that is non-trivial to destruct,
1186 /// which is a union that has a member that is non-trivial to destruct. If
1187 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1188 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1189
1190 /// Check if this is or contains a C union that is non-trivial to copy, which
1191 /// is a union that has a member that is non-trivial to copy. If this returns
1192 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1193 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1194
1195 /// Determine whether expressions of the given type are forbidden
1196 /// from being lvalues in C.
1197 ///
1198 /// The expression types that are forbidden to be lvalues are:
1199 /// - 'void', but not qualified void
1200 /// - function types
1201 ///
1202 /// The exact rule here is C99 6.3.2.1:
1203 /// An lvalue is an expression with an object type or an incomplete
1204 /// type other than void.
1205 bool isCForbiddenLValueType() const;
1206
1207 /// Substitute type arguments for the Objective-C type parameters used in the
1208 /// subject type.
1209 ///
1210 /// \param ctx ASTContext in which the type exists.
1211 ///
1212 /// \param typeArgs The type arguments that will be substituted for the
1213 /// Objective-C type parameters in the subject type, which are generally
1214 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1215 /// parameters will be replaced with their bounds or id/Class, as appropriate
1216 /// for the context.
1217 ///
1218 /// \param context The context in which the subject type was written.
1219 ///
1220 /// \returns the resulting type.
1221 QualType substObjCTypeArgs(ASTContext &ctx,
1222 ArrayRef<QualType> typeArgs,
1223 ObjCSubstitutionContext context) const;
1224
1225 /// Substitute type arguments from an object type for the Objective-C type
1226 /// parameters used in the subject type.
1227 ///
1228 /// This operation combines the computation of type arguments for
1229 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1230 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1231 /// callers that need to perform a single substitution in isolation.
1232 ///
1233 /// \param objectType The type of the object whose member type we're
1234 /// substituting into. For example, this might be the receiver of a message
1235 /// or the base of a property access.
1236 ///
1237 /// \param dc The declaration context from which the subject type was
1238 /// retrieved, which indicates (for example) which type parameters should
1239 /// be substituted.
1240 ///
1241 /// \param context The context in which the subject type was written.
1242 ///
1243 /// \returns the subject type after replacing all of the Objective-C type
1244 /// parameters with their corresponding arguments.
1245 QualType substObjCMemberType(QualType objectType,
1246 const DeclContext *dc,
1247 ObjCSubstitutionContext context) const;
1248
1249 /// Strip Objective-C "__kindof" types from the given type.
1250 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1251
1252 /// Remove all qualifiers including _Atomic.
1253 QualType getAtomicUnqualifiedType() const;
1254
1255private:
1256 // These methods are implemented in a separate translation unit;
1257 // "static"-ize them to avoid creating temporary QualTypes in the
1258 // caller.
1259 static bool isConstant(QualType T, const ASTContext& Ctx);
1260 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1261 static SplitQualType getSplitDesugaredType(QualType T);
1262 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1263 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1264 const ASTContext &C);
1265 static QualType IgnoreParens(QualType T);
1266 static DestructionKind isDestructedTypeImpl(QualType type);
1267
1268 /// Check if \param RD is or contains a non-trivial C union.
1269 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1270 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1271 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1272};
1273
1274} // namespace clang
1275
1276namespace llvm {
1277
1278/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1279/// to a specific Type class.
1280template<> struct simplify_type< ::clang::QualType> {
1281 using SimpleType = const ::clang::Type *;
1282
1283 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1284 return Val.getTypePtr();
1285 }
1286};
1287
1288// Teach SmallPtrSet that QualType is "basically a pointer".
1289template<>
1290struct PointerLikeTypeTraits<clang::QualType> {
1291 static inline void *getAsVoidPointer(clang::QualType P) {
1292 return P.getAsOpaquePtr();
1293 }
1294
1295 static inline clang::QualType getFromVoidPointer(void *P) {
1296 return clang::QualType::getFromOpaquePtr(P);
1297 }
1298
1299 // Various qualifiers go in low bits.
1300 static constexpr int NumLowBitsAvailable = 0;
1301};
1302
1303} // namespace llvm
1304
1305namespace clang {
1306
1307/// Base class that is common to both the \c ExtQuals and \c Type
1308/// classes, which allows \c QualType to access the common fields between the
1309/// two.
1310class ExtQualsTypeCommonBase {
1311 friend class ExtQuals;
1312 friend class QualType;
1313 friend class Type;
1314
1315 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1316 /// a self-referential pointer (for \c Type).
1317 ///
1318 /// This pointer allows an efficient mapping from a QualType to its
1319 /// underlying type pointer.
1320 const Type *const BaseType;
1321
1322 /// The canonical type of this type. A QualType.
1323 QualType CanonicalType;
1324
1325 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1326 : BaseType(baseType), CanonicalType(canon) {}
1327};
1328
1329/// We can encode up to four bits in the low bits of a
1330/// type pointer, but there are many more type qualifiers that we want
1331/// to be able to apply to an arbitrary type. Therefore we have this
1332/// struct, intended to be heap-allocated and used by QualType to
1333/// store qualifiers.
1334///
1335/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1336/// in three low bits on the QualType pointer; a fourth bit records whether
1337/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1338/// Objective-C GC attributes) are much more rare.
1339class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1340 // NOTE: changing the fast qualifiers should be straightforward as
1341 // long as you don't make 'const' non-fast.
1342 // 1. Qualifiers:
1343 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1344 // Fast qualifiers must occupy the low-order bits.
1345 // b) Update Qualifiers::FastWidth and FastMask.
1346 // 2. QualType:
1347 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1348 // b) Update remove{Volatile,Restrict}, defined near the end of
1349 // this header.
1350 // 3. ASTContext:
1351 // a) Update get{Volatile,Restrict}Type.
1352
1353 /// The immutable set of qualifiers applied by this node. Always contains
1354 /// extended qualifiers.
1355 Qualifiers Quals;
1356
1357 ExtQuals *this_() { return this; }
1358
1359public:
1360 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1361 : ExtQualsTypeCommonBase(baseType,
1362 canon.isNull() ? QualType(this_(), 0) : canon),
1363 Quals(quals) {
1364 assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 1365, __PRETTY_FUNCTION__))
1365 && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 1365, __PRETTY_FUNCTION__))
;
1366 assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 1367, __PRETTY_FUNCTION__))
1367 && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 1367, __PRETTY_FUNCTION__))
;
1368 }
1369
1370 Qualifiers getQualifiers() const { return Quals; }
1371
1372 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1373 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1374
1375 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1376 Qualifiers::ObjCLifetime getObjCLifetime() const {
1377 return Quals.getObjCLifetime();
1378 }
1379
1380 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1381 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1382
1383 const Type *getBaseType() const { return BaseType; }
1384
1385public:
1386 void Profile(llvm::FoldingSetNodeID &ID) const {
1387 Profile(ID, getBaseType(), Quals);
1388 }
1389
1390 static void Profile(llvm::FoldingSetNodeID &ID,
1391 const Type *BaseType,
1392 Qualifiers Quals) {
1393 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 1393, __PRETTY_FUNCTION__))
;
1394 ID.AddPointer(BaseType);
1395 Quals.Profile(ID);
1396 }
1397};
1398
1399/// The kind of C++11 ref-qualifier associated with a function type.
1400/// This determines whether a member function's "this" object can be an
1401/// lvalue, rvalue, or neither.
1402enum RefQualifierKind {
1403 /// No ref-qualifier was provided.
1404 RQ_None = 0,
1405
1406 /// An lvalue ref-qualifier was provided (\c &).
1407 RQ_LValue,
1408
1409 /// An rvalue ref-qualifier was provided (\c &&).
1410 RQ_RValue
1411};
1412
1413/// Which keyword(s) were used to create an AutoType.
1414enum class AutoTypeKeyword {
1415 /// auto
1416 Auto,
1417
1418 /// decltype(auto)
1419 DecltypeAuto,
1420
1421 /// __auto_type (GNU extension)
1422 GNUAutoType
1423};
1424
1425/// The base class of the type hierarchy.
1426///
1427/// A central concept with types is that each type always has a canonical
1428/// type. A canonical type is the type with any typedef names stripped out
1429/// of it or the types it references. For example, consider:
1430///
1431/// typedef int foo;
1432/// typedef foo* bar;
1433/// 'int *' 'foo *' 'bar'
1434///
1435/// There will be a Type object created for 'int'. Since int is canonical, its
1436/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1437/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1438/// there is a PointerType that represents 'int*', which, like 'int', is
1439/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1440/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1441/// is also 'int*'.
1442///
1443/// Non-canonical types are useful for emitting diagnostics, without losing
1444/// information about typedefs being used. Canonical types are useful for type
1445/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1446/// about whether something has a particular form (e.g. is a function type),
1447/// because they implicitly, recursively, strip all typedefs out of a type.
1448///
1449/// Types, once created, are immutable.
1450///
1451class alignas(8) Type : public ExtQualsTypeCommonBase {
1452public:
1453 enum TypeClass {
1454#define TYPE(Class, Base) Class,
1455#define LAST_TYPE(Class) TypeLast = Class
1456#define ABSTRACT_TYPE(Class, Base)
1457#include "clang/AST/TypeNodes.inc"
1458 };
1459
1460private:
1461 /// Bitfields required by the Type class.
1462 class TypeBitfields {
1463 friend class Type;
1464 template <class T> friend class TypePropertyCache;
1465
1466 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1467 unsigned TC : 8;
1468
1469 /// Store information on the type dependency.
1470 /*TypeDependence*/ unsigned Dependence : TypeDependenceBits;
1471
1472 /// True if the cache (i.e. the bitfields here starting with
1473 /// 'Cache') is valid.
1474 mutable unsigned CacheValid : 1;
1475
1476 /// Linkage of this type.
1477 mutable unsigned CachedLinkage : 3;
1478
1479 /// Whether this type involves and local or unnamed types.
1480 mutable unsigned CachedLocalOrUnnamed : 1;
1481
1482 /// Whether this type comes from an AST file.
1483 mutable unsigned FromAST : 1;
1484
1485 bool isCacheValid() const {
1486 return CacheValid;
1487 }
1488
1489 Linkage getLinkage() const {
1490 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 1490, __PRETTY_FUNCTION__))
;
1491 return static_cast<Linkage>(CachedLinkage);
1492 }
1493
1494 bool hasLocalOrUnnamedType() const {
1495 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 1495, __PRETTY_FUNCTION__))
;
1496 return CachedLocalOrUnnamed;
1497 }
1498 };
1499 enum { NumTypeBits = 18 };
1500
1501protected:
1502 // These classes allow subclasses to somewhat cleanly pack bitfields
1503 // into Type.
1504
1505 class ArrayTypeBitfields {
1506 friend class ArrayType;
1507
1508 unsigned : NumTypeBits;
1509
1510 /// CVR qualifiers from declarations like
1511 /// 'int X[static restrict 4]'. For function parameters only.
1512 unsigned IndexTypeQuals : 3;
1513
1514 /// Storage class qualifiers from declarations like
1515 /// 'int X[static restrict 4]'. For function parameters only.
1516 /// Actually an ArrayType::ArraySizeModifier.
1517 unsigned SizeModifier : 3;
1518 };
1519
1520 class ConstantArrayTypeBitfields {
1521 friend class ConstantArrayType;
1522
1523 unsigned : NumTypeBits + 3 + 3;
1524
1525 /// Whether we have a stored size expression.
1526 unsigned HasStoredSizeExpr : 1;
1527 };
1528
1529 class BuiltinTypeBitfields {
1530 friend class BuiltinType;
1531
1532 unsigned : NumTypeBits;
1533
1534 /// The kind (BuiltinType::Kind) of builtin type this is.
1535 unsigned Kind : 8;
1536 };
1537
1538 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1539 /// Only common bits are stored here. Additional uncommon bits are stored
1540 /// in a trailing object after FunctionProtoType.
1541 class FunctionTypeBitfields {
1542 friend class FunctionProtoType;
1543 friend class FunctionType;
1544
1545 unsigned : NumTypeBits;
1546
1547 /// Extra information which affects how the function is called, like
1548 /// regparm and the calling convention.
1549 unsigned ExtInfo : 12;
1550
1551 /// The ref-qualifier associated with a \c FunctionProtoType.
1552 ///
1553 /// This is a value of type \c RefQualifierKind.
1554 unsigned RefQualifier : 2;
1555
1556 /// Used only by FunctionProtoType, put here to pack with the
1557 /// other bitfields.
1558 /// The qualifiers are part of FunctionProtoType because...
1559 ///
1560 /// C++ 8.3.5p4: The return type, the parameter type list and the
1561 /// cv-qualifier-seq, [...], are part of the function type.
1562 unsigned FastTypeQuals : Qualifiers::FastWidth;
1563 /// Whether this function has extended Qualifiers.
1564 unsigned HasExtQuals : 1;
1565
1566 /// The number of parameters this function has, not counting '...'.
1567 /// According to [implimits] 8 bits should be enough here but this is
1568 /// somewhat easy to exceed with metaprogramming and so we would like to
1569 /// keep NumParams as wide as reasonably possible.
1570 unsigned NumParams : 16;
1571
1572 /// The type of exception specification this function has.
1573 unsigned ExceptionSpecType : 4;
1574
1575 /// Whether this function has extended parameter information.
1576 unsigned HasExtParameterInfos : 1;
1577
1578 /// Whether the function is variadic.
1579 unsigned Variadic : 1;
1580
1581 /// Whether this function has a trailing return type.
1582 unsigned HasTrailingReturn : 1;
1583 };
1584
1585 class ObjCObjectTypeBitfields {
1586 friend class ObjCObjectType;
1587
1588 unsigned : NumTypeBits;
1589
1590 /// The number of type arguments stored directly on this object type.
1591 unsigned NumTypeArgs : 7;
1592
1593 /// The number of protocols stored directly on this object type.
1594 unsigned NumProtocols : 6;
1595
1596 /// Whether this is a "kindof" type.
1597 unsigned IsKindOf : 1;
1598 };
1599
1600 class ReferenceTypeBitfields {
1601 friend class ReferenceType;
1602
1603 unsigned : NumTypeBits;
1604
1605 /// True if the type was originally spelled with an lvalue sigil.
1606 /// This is never true of rvalue references but can also be false
1607 /// on lvalue references because of C++0x [dcl.typedef]p9,
1608 /// as follows:
1609 ///
1610 /// typedef int &ref; // lvalue, spelled lvalue
1611 /// typedef int &&rvref; // rvalue
1612 /// ref &a; // lvalue, inner ref, spelled lvalue
1613 /// ref &&a; // lvalue, inner ref
1614 /// rvref &a; // lvalue, inner ref, spelled lvalue
1615 /// rvref &&a; // rvalue, inner ref
1616 unsigned SpelledAsLValue : 1;
1617
1618 /// True if the inner type is a reference type. This only happens
1619 /// in non-canonical forms.
1620 unsigned InnerRef : 1;
1621 };
1622
1623 class TypeWithKeywordBitfields {
1624 friend class TypeWithKeyword;
1625
1626 unsigned : NumTypeBits;
1627
1628 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1629 unsigned Keyword : 8;
1630 };
1631
1632 enum { NumTypeWithKeywordBits = 8 };
1633
1634 class ElaboratedTypeBitfields {
1635 friend class ElaboratedType;
1636
1637 unsigned : NumTypeBits;
1638 unsigned : NumTypeWithKeywordBits;
1639
1640 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1641 unsigned HasOwnedTagDecl : 1;
1642 };
1643
1644 class VectorTypeBitfields {
1645 friend class VectorType;
1646 friend class DependentVectorType;
1647
1648 unsigned : NumTypeBits;
1649
1650 /// The kind of vector, either a generic vector type or some
1651 /// target-specific vector type such as for AltiVec or Neon.
1652 unsigned VecKind : 3;
1653
1654 /// The number of elements in the vector.
1655 unsigned NumElements : 29 - NumTypeBits;
1656
1657 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1658 };
1659
1660 class AttributedTypeBitfields {
1661 friend class AttributedType;
1662
1663 unsigned : NumTypeBits;
1664
1665 /// An AttributedType::Kind
1666 unsigned AttrKind : 32 - NumTypeBits;
1667 };
1668
1669 class AutoTypeBitfields {
1670 friend class AutoType;
1671
1672 unsigned : NumTypeBits;
1673
1674 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1675 /// or '__auto_type'? AutoTypeKeyword value.
1676 unsigned Keyword : 2;
1677
1678 /// The number of template arguments in the type-constraints, which is
1679 /// expected to be able to hold at least 1024 according to [implimits].
1680 /// However as this limit is somewhat easy to hit with template
1681 /// metaprogramming we'd prefer to keep it as large as possible.
1682 /// At the moment it has been left as a non-bitfield since this type
1683 /// safely fits in 64 bits as an unsigned, so there is no reason to
1684 /// introduce the performance impact of a bitfield.
1685 unsigned NumArgs;
1686 };
1687
1688 class SubstTemplateTypeParmPackTypeBitfields {
1689 friend class SubstTemplateTypeParmPackType;
1690
1691 unsigned : NumTypeBits;
1692
1693 /// The number of template arguments in \c Arguments, which is
1694 /// expected to be able to hold at least 1024 according to [implimits].
1695 /// However as this limit is somewhat easy to hit with template
1696 /// metaprogramming we'd prefer to keep it as large as possible.
1697 /// At the moment it has been left as a non-bitfield since this type
1698 /// safely fits in 64 bits as an unsigned, so there is no reason to
1699 /// introduce the performance impact of a bitfield.
1700 unsigned NumArgs;
1701 };
1702
1703 class TemplateSpecializationTypeBitfields {
1704 friend class TemplateSpecializationType;
1705
1706 unsigned : NumTypeBits;
1707
1708 /// Whether this template specialization type is a substituted type alias.
1709 unsigned TypeAlias : 1;
1710
1711 /// The number of template arguments named in this class template
1712 /// specialization, which is expected to be able to hold at least 1024
1713 /// according to [implimits]. However, as this limit is somewhat easy to
1714 /// hit with template metaprogramming we'd prefer to keep it as large
1715 /// as possible. At the moment it has been left as a non-bitfield since
1716 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1717 /// to introduce the performance impact of a bitfield.
1718 unsigned NumArgs;
1719 };
1720
1721 class DependentTemplateSpecializationTypeBitfields {
1722 friend class DependentTemplateSpecializationType;
1723
1724 unsigned : NumTypeBits;
1725 unsigned : NumTypeWithKeywordBits;
1726
1727 /// The number of template arguments named in this class template
1728 /// specialization, which is expected to be able to hold at least 1024
1729 /// according to [implimits]. However, as this limit is somewhat easy to
1730 /// hit with template metaprogramming we'd prefer to keep it as large
1731 /// as possible. At the moment it has been left as a non-bitfield since
1732 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1733 /// to introduce the performance impact of a bitfield.
1734 unsigned NumArgs;
1735 };
1736
1737 class PackExpansionTypeBitfields {
1738 friend class PackExpansionType;
1739
1740 unsigned : NumTypeBits;
1741
1742 /// The number of expansions that this pack expansion will
1743 /// generate when substituted (+1), which is expected to be able to
1744 /// hold at least 1024 according to [implimits]. However, as this limit
1745 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1746 /// keep it as large as possible. At the moment it has been left as a
1747 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1748 /// there is no reason to introduce the performance impact of a bitfield.
1749 ///
1750 /// This field will only have a non-zero value when some of the parameter
1751 /// packs that occur within the pattern have been substituted but others
1752 /// have not.
1753 unsigned NumExpansions;
1754 };
1755
1756 union {
1757 TypeBitfields TypeBits;
1758 ArrayTypeBitfields ArrayTypeBits;
1759 ConstantArrayTypeBitfields ConstantArrayTypeBits;
1760 AttributedTypeBitfields AttributedTypeBits;
1761 AutoTypeBitfields AutoTypeBits;
1762 BuiltinTypeBitfields BuiltinTypeBits;
1763 FunctionTypeBitfields FunctionTypeBits;
1764 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1765 ReferenceTypeBitfields ReferenceTypeBits;
1766 TypeWithKeywordBitfields TypeWithKeywordBits;
1767 ElaboratedTypeBitfields ElaboratedTypeBits;
1768 VectorTypeBitfields VectorTypeBits;
1769 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1770 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1771 DependentTemplateSpecializationTypeBitfields
1772 DependentTemplateSpecializationTypeBits;
1773 PackExpansionTypeBitfields PackExpansionTypeBits;
1774
1775 static_assert(sizeof(TypeBitfields) <= 8,
1776 "TypeBitfields is larger than 8 bytes!");
1777 static_assert(sizeof(ArrayTypeBitfields) <= 8,
1778 "ArrayTypeBitfields is larger than 8 bytes!");
1779 static_assert(sizeof(AttributedTypeBitfields) <= 8,
1780 "AttributedTypeBitfields is larger than 8 bytes!");
1781 static_assert(sizeof(AutoTypeBitfields) <= 8,
1782 "AutoTypeBitfields is larger than 8 bytes!");
1783 static_assert(sizeof(BuiltinTypeBitfields) <= 8,
1784 "BuiltinTypeBitfields is larger than 8 bytes!");
1785 static_assert(sizeof(FunctionTypeBitfields) <= 8,
1786 "FunctionTypeBitfields is larger than 8 bytes!");
1787 static_assert(sizeof(ObjCObjectTypeBitfields) <= 8,
1788 "ObjCObjectTypeBitfields is larger than 8 bytes!");
1789 static_assert(sizeof(ReferenceTypeBitfields) <= 8,
1790 "ReferenceTypeBitfields is larger than 8 bytes!");
1791 static_assert(sizeof(TypeWithKeywordBitfields) <= 8,
1792 "TypeWithKeywordBitfields is larger than 8 bytes!");
1793 static_assert(sizeof(ElaboratedTypeBitfields) <= 8,
1794 "ElaboratedTypeBitfields is larger than 8 bytes!");
1795 static_assert(sizeof(VectorTypeBitfields) <= 8,
1796 "VectorTypeBitfields is larger than 8 bytes!");
1797 static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8,
1798 "SubstTemplateTypeParmPackTypeBitfields is larger"
1799 " than 8 bytes!");
1800 static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8,
1801 "TemplateSpecializationTypeBitfields is larger"
1802 " than 8 bytes!");
1803 static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8,
1804 "DependentTemplateSpecializationTypeBitfields is larger"
1805 " than 8 bytes!");
1806 static_assert(sizeof(PackExpansionTypeBitfields) <= 8,
1807 "PackExpansionTypeBitfields is larger than 8 bytes");
1808 };
1809
1810private:
1811 template <class T> friend class TypePropertyCache;
1812
1813 /// Set whether this type comes from an AST file.
1814 void setFromAST(bool V = true) const {
1815 TypeBits.FromAST = V;
1816 }
1817
1818protected:
1819 friend class ASTContext;
1820
1821 Type(TypeClass tc, QualType canon, bool Dependent,
1822 bool InstantiationDependent, bool VariablyModified,
1823 bool ContainsUnexpandedParameterPack)
1824 : ExtQualsTypeCommonBase(this,
1825 canon.isNull() ? QualType(this_(), 0) : canon) {
1826 auto Deps = TypeDependence::None;
1827 if (Dependent)
1828 Deps |= TypeDependence::Dependent | TypeDependence::Instantiation;
1829 if (InstantiationDependent)
1830 Deps |= TypeDependence::Instantiation;
1831 if (ContainsUnexpandedParameterPack)
1832 Deps |= TypeDependence::UnexpandedPack;
1833 if (VariablyModified)
1834 Deps |= TypeDependence::VariablyModified;
1835
1836 TypeBits.TC = tc;
1837 TypeBits.Dependence = static_cast<unsigned>(Deps);
1838 TypeBits.CacheValid = false;
1839 TypeBits.CachedLocalOrUnnamed = false;
1840 TypeBits.CachedLinkage = NoLinkage;
1841 TypeBits.FromAST = false;
1842 }
1843
1844 // silence VC++ warning C4355: 'this' : used in base member initializer list
1845 Type *this_() { return this; }
1846
1847 void setDependent(bool D = true) {
1848 if (!D) {
1849 TypeBits.Dependence &= ~static_cast<unsigned>(TypeDependence::Dependent);
1850 return;
1851 }
1852 TypeBits.Dependence |= static_cast<unsigned>(TypeDependence::Dependent |
1853 TypeDependence::Instantiation);
1854 }
1855
1856 void setInstantiationDependent(bool D = true) {
1857 if (D)
1858 TypeBits.Dependence |=
1859 static_cast<unsigned>(TypeDependence::Instantiation);
1860 else
1861 TypeBits.Dependence &=
1862 ~static_cast<unsigned>(TypeDependence::Instantiation);
1863 }
1864
1865 void setVariablyModified(bool VM = true) {
1866 if (VM)
1867 TypeBits.Dependence |=
1868 static_cast<unsigned>(TypeDependence::VariablyModified);
1869 else
1870 TypeBits.Dependence &=
1871 ~static_cast<unsigned>(TypeDependence::VariablyModified);
1872 }
1873
1874 void setContainsUnexpandedParameterPack(bool PP = true) {
1875 if (PP)
1876 TypeBits.Dependence |=
1877 static_cast<unsigned>(TypeDependence::UnexpandedPack);
1878 else
1879 TypeBits.Dependence &=
1880 ~static_cast<unsigned>(TypeDependence::UnexpandedPack);
1881 }
1882
1883public:
1884 friend class ASTReader;
1885 friend class ASTWriter;
1886 template <class T> friend class serialization::AbstractTypeReader;
1887 template <class T> friend class serialization::AbstractTypeWriter;
1888
1889 Type(const Type &) = delete;
1890 Type(Type &&) = delete;
1891 Type &operator=(const Type &) = delete;
1892 Type &operator=(Type &&) = delete;
1893
1894 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1895
1896 /// Whether this type comes from an AST file.
1897 bool isFromAST() const { return TypeBits.FromAST; }
1898
1899 /// Whether this type is or contains an unexpanded parameter
1900 /// pack, used to support C++0x variadic templates.
1901 ///
1902 /// A type that contains a parameter pack shall be expanded by the
1903 /// ellipsis operator at some point. For example, the typedef in the
1904 /// following example contains an unexpanded parameter pack 'T':
1905 ///
1906 /// \code
1907 /// template<typename ...T>
1908 /// struct X {
1909 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1910 /// };
1911 /// \endcode
1912 ///
1913 /// Note that this routine does not specify which
1914 bool containsUnexpandedParameterPack() const {
1915 return getDependence() & TypeDependence::UnexpandedPack;
1916 }
1917
1918 /// Determines if this type would be canonical if it had no further
1919 /// qualification.
1920 bool isCanonicalUnqualified() const {
1921 return CanonicalType == QualType(this, 0);
1922 }
1923
1924 /// Pull a single level of sugar off of this locally-unqualified type.
1925 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1926 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1927 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1928
1929 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1930 /// object types, function types, and incomplete types.
1931
1932 /// Return true if this is an incomplete type.
1933 /// A type that can describe objects, but which lacks information needed to
1934 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1935 /// routine will need to determine if the size is actually required.
1936 ///
1937 /// Def If non-null, and the type refers to some kind of declaration
1938 /// that can be completed (such as a C struct, C++ class, or Objective-C
1939 /// class), will be set to the declaration.
1940 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1941
1942 /// Return true if this is an incomplete or object
1943 /// type, in other words, not a function type.
1944 bool isIncompleteOrObjectType() const {
1945 return !isFunctionType();
1946 }
1947
1948 /// Determine whether this type is an object type.
1949 bool isObjectType() const {
1950 // C++ [basic.types]p8:
1951 // An object type is a (possibly cv-qualified) type that is not a
1952 // function type, not a reference type, and not a void type.
1953 return !isReferenceType() && !isFunctionType() && !isVoidType();
1954 }
1955
1956 /// Return true if this is a literal type
1957 /// (C++11 [basic.types]p10)
1958 bool isLiteralType(const ASTContext &Ctx) const;
1959
1960 /// Test if this type is a standard-layout type.
1961 /// (C++0x [basic.type]p9)
1962 bool isStandardLayoutType() const;
1963
1964 /// Helper methods to distinguish type categories. All type predicates
1965 /// operate on the canonical type, ignoring typedefs and qualifiers.
1966
1967 /// Returns true if the type is a builtin type.
1968 bool isBuiltinType() const;
1969
1970 /// Test for a particular builtin type.
1971 bool isSpecificBuiltinType(unsigned K) const;
1972
1973 /// Test for a type which does not represent an actual type-system type but
1974 /// is instead used as a placeholder for various convenient purposes within
1975 /// Clang. All such types are BuiltinTypes.
1976 bool isPlaceholderType() const;
1977 const BuiltinType *getAsPlaceholderType() const;
1978
1979 /// Test for a specific placeholder type.
1980 bool isSpecificPlaceholderType(unsigned K) const;
1981
1982 /// Test for a placeholder type other than Overload; see
1983 /// BuiltinType::isNonOverloadPlaceholderType.
1984 bool isNonOverloadPlaceholderType() const;
1985
1986 /// isIntegerType() does *not* include complex integers (a GCC extension).
1987 /// isComplexIntegerType() can be used to test for complex integers.
1988 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1989 bool isEnumeralType() const;
1990
1991 /// Determine whether this type is a scoped enumeration type.
1992 bool isScopedEnumeralType() const;
1993 bool isBooleanType() const;
1994 bool isCharType() const;
1995 bool isWideCharType() const;
1996 bool isChar8Type() const;
1997 bool isChar16Type() const;
1998 bool isChar32Type() const;
1999 bool isAnyCharacterType() const;
2000 bool isIntegralType(const ASTContext &Ctx) const;
2001
2002 /// Determine whether this type is an integral or enumeration type.
2003 bool isIntegralOrEnumerationType() const;
2004
2005 /// Determine whether this type is an integral or unscoped enumeration type.
2006 bool isIntegralOrUnscopedEnumerationType() const;
2007 bool isUnscopedEnumerationType() const;
2008
2009 /// Floating point categories.
2010 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
2011 /// isComplexType() does *not* include complex integers (a GCC extension).
2012 /// isComplexIntegerType() can be used to test for complex integers.
2013 bool isComplexType() const; // C99 6.2.5p11 (complex)
2014 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
2015 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
2016 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
2017 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
2018 bool isFloat128Type() const;
2019 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
2020 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
2021 bool isVoidType() const; // C99 6.2.5p19
2022 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
2023 bool isAggregateType() const;
2024 bool isFundamentalType() const;
2025 bool isCompoundType() const;
2026
2027 // Type Predicates: Check to see if this type is structurally the specified
2028 // type, ignoring typedefs and qualifiers.
2029 bool isFunctionType() const;
2030 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2031 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2032 bool isPointerType() const;
2033 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2034 bool isBlockPointerType() const;
2035 bool isVoidPointerType() const;
2036 bool isReferenceType() const;
2037 bool isLValueReferenceType() const;
2038 bool isRValueReferenceType() const;
2039 bool isObjectPointerType() const;
2040 bool isFunctionPointerType() const;
2041 bool isFunctionReferenceType() const;
2042 bool isMemberPointerType() const;
2043 bool isMemberFunctionPointerType() const;
2044 bool isMemberDataPointerType() const;
2045 bool isArrayType() const;
2046 bool isConstantArrayType() const;
2047 bool isIncompleteArrayType() const;
2048 bool isVariableArrayType() const;
2049 bool isDependentSizedArrayType() const;
2050 bool isRecordType() const;
2051 bool isClassType() const;
2052 bool isStructureType() const;
2053 bool isObjCBoxableRecordType() const;
2054 bool isInterfaceType() const;
2055 bool isStructureOrClassType() const;
2056 bool isUnionType() const;
2057 bool isComplexIntegerType() const; // GCC _Complex integer type.
2058 bool isVectorType() const; // GCC vector type.
2059 bool isExtVectorType() const; // Extended vector type.
2060 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2061 bool isObjCObjectPointerType() const; // pointer to ObjC object
2062 bool isObjCRetainableType() const; // ObjC object or block pointer
2063 bool isObjCLifetimeType() const; // (array of)* retainable type
2064 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2065 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2066 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2067 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2068 // for the common case.
2069 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2070 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2071 bool isObjCQualifiedIdType() const; // id<foo>
2072 bool isObjCQualifiedClassType() const; // Class<foo>
2073 bool isObjCObjectOrInterfaceType() const;
2074 bool isObjCIdType() const; // id
2075 bool isDecltypeType() const;
2076 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2077 /// qualifier?
2078 ///
2079 /// This approximates the answer to the following question: if this
2080 /// translation unit were compiled in ARC, would this type be qualified
2081 /// with __unsafe_unretained?
2082 bool isObjCInertUnsafeUnretainedType() const {
2083 return hasAttr(attr::ObjCInertUnsafeUnretained);
2084 }
2085
2086 /// Whether the type is Objective-C 'id' or a __kindof type of an
2087 /// object type, e.g., __kindof NSView * or __kindof id
2088 /// <NSCopying>.
2089 ///
2090 /// \param bound Will be set to the bound on non-id subtype types,
2091 /// which will be (possibly specialized) Objective-C class type, or
2092 /// null for 'id.
2093 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2094 const ObjCObjectType *&bound) const;
2095
2096 bool isObjCClassType() const; // Class
2097
2098 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2099 /// Class type, e.g., __kindof Class <NSCopying>.
2100 ///
2101 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2102 /// here because Objective-C's type system cannot express "a class
2103 /// object for a subclass of NSFoo".
2104 bool isObjCClassOrClassKindOfType() const;
2105
2106 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2107 bool isObjCSelType() const; // Class
2108 bool isObjCBuiltinType() const; // 'id' or 'Class'
2109 bool isObjCARCBridgableType() const;
2110 bool isCARCBridgableType() const;
2111 bool isTemplateTypeParmType() const; // C++ template type parameter
2112 bool isNullPtrType() const; // C++11 std::nullptr_t
2113 bool isNothrowT() const; // C++ std::nothrow_t
2114 bool isAlignValT() const; // C++17 std::align_val_t
2115 bool isStdByteType() const; // C++17 std::byte
2116 bool isAtomicType() const; // C11 _Atomic()
2117 bool isUndeducedAutoType() const; // C++11 auto or
2118 // C++14 decltype(auto)
2119
2120#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2121 bool is##Id##Type() const;
2122#include "clang/Basic/OpenCLImageTypes.def"
2123
2124 bool isImageType() const; // Any OpenCL image type
2125
2126 bool isSamplerT() const; // OpenCL sampler_t
2127 bool isEventT() const; // OpenCL event_t
2128 bool isClkEventT() const; // OpenCL clk_event_t
2129 bool isQueueT() const; // OpenCL queue_t
2130 bool isReserveIDT() const; // OpenCL reserve_id_t
2131
2132#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2133 bool is##Id##Type() const;
2134#include "clang/Basic/OpenCLExtensionTypes.def"
2135 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2136 bool isOCLIntelSubgroupAVCType() const;
2137 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2138
2139 bool isPipeType() const; // OpenCL pipe type
2140 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2141
2142 /// Determines if this type, which must satisfy
2143 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2144 /// than implicitly __strong.
2145 bool isObjCARCImplicitlyUnretainedType() const;
2146
2147 /// Return the implicit lifetime for this type, which must not be dependent.
2148 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2149
2150 enum ScalarTypeKind {
2151 STK_CPointer,
2152 STK_BlockPointer,
2153 STK_ObjCObjectPointer,
2154 STK_MemberPointer,
2155 STK_Bool,
2156 STK_Integral,
2157 STK_Floating,
2158 STK_IntegralComplex,
2159 STK_FloatingComplex,
2160 STK_FixedPoint
2161 };
2162
2163 /// Given that this is a scalar type, classify it.
2164 ScalarTypeKind getScalarTypeKind() const;
2165
2166 TypeDependence getDependence() const {
2167 return static_cast<TypeDependence>(TypeBits.Dependence);
2168 }
2169
2170 /// Whether this type is a dependent type, meaning that its definition
2171 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2172 bool isDependentType() const {
2173 return getDependence() & TypeDependence::Dependent;
2174 }
2175
2176 /// Determine whether this type is an instantiation-dependent type,
2177 /// meaning that the type involves a template parameter (even if the
2178 /// definition does not actually depend on the type substituted for that
2179 /// template parameter).
2180 bool isInstantiationDependentType() const {
2181 return getDependence() & TypeDependence::Instantiation;
2182 }
2183
2184 /// Determine whether this type is an undeduced type, meaning that
2185 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2186 /// deduced.
2187 bool isUndeducedType() const;
2188
2189 /// Whether this type is a variably-modified type (C99 6.7.5).
2190 bool isVariablyModifiedType() const {
2191 return getDependence() & TypeDependence::VariablyModified;
2192 }
2193
2194 /// Whether this type involves a variable-length array type
2195 /// with a definite size.
2196 bool hasSizedVLAType() const;
2197
2198 /// Whether this type is or contains a local or unnamed type.
2199 bool hasUnnamedOrLocalType() const;
2200
2201 bool isOverloadableType() const;
2202
2203 /// Determine wither this type is a C++ elaborated-type-specifier.
2204 bool isElaboratedTypeSpecifier() const;
2205
2206 bool canDecayToPointerType() const;
2207
2208 /// Whether this type is represented natively as a pointer. This includes
2209 /// pointers, references, block pointers, and Objective-C interface,
2210 /// qualified id, and qualified interface types, as well as nullptr_t.
2211 bool hasPointerRepresentation() const;
2212
2213 /// Whether this type can represent an objective pointer type for the
2214 /// purpose of GC'ability
2215 bool hasObjCPointerRepresentation() const;
2216
2217 /// Determine whether this type has an integer representation
2218 /// of some sort, e.g., it is an integer type or a vector.
2219 bool hasIntegerRepresentation() const;
2220
2221 /// Determine whether this type has an signed integer representation
2222 /// of some sort, e.g., it is an signed integer type or a vector.
2223 bool hasSignedIntegerRepresentation() const;
2224
2225 /// Determine whether this type has an unsigned integer representation
2226 /// of some sort, e.g., it is an unsigned integer type or a vector.
2227 bool hasUnsignedIntegerRepresentation() const;
2228
2229 /// Determine whether this type has a floating-point representation
2230 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2231 bool hasFloatingRepresentation() const;
2232
2233 // Type Checking Functions: Check to see if this type is structurally the
2234 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2235 // the best type we can.
2236 const RecordType *getAsStructureType() const;
2237 /// NOTE: getAs*ArrayType are methods on ASTContext.
2238 const RecordType *getAsUnionType() const;
2239 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2240 const ObjCObjectType *getAsObjCInterfaceType() const;
2241
2242 // The following is a convenience method that returns an ObjCObjectPointerType
2243 // for object declared using an interface.
2244 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2245 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2246 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2247 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2248
2249 /// Retrieves the CXXRecordDecl that this type refers to, either
2250 /// because the type is a RecordType or because it is the injected-class-name
2251 /// type of a class template or class template partial specialization.
2252 CXXRecordDecl *getAsCXXRecordDecl() const;
2253
2254 /// Retrieves the RecordDecl this type refers to.
2255 RecordDecl *getAsRecordDecl() const;
2256
2257 /// Retrieves the TagDecl that this type refers to, either
2258 /// because the type is a TagType or because it is the injected-class-name
2259 /// type of a class template or class template partial specialization.
2260 TagDecl *getAsTagDecl() const;
2261
2262 /// If this is a pointer or reference to a RecordType, return the
2263 /// CXXRecordDecl that the type refers to.
2264 ///
2265 /// If this is not a pointer or reference, or the type being pointed to does
2266 /// not refer to a CXXRecordDecl, returns NULL.
2267 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2268
2269 /// Get the DeducedType whose type will be deduced for a variable with
2270 /// an initializer of this type. This looks through declarators like pointer
2271 /// types, but not through decltype or typedefs.
2272 DeducedType *getContainedDeducedType() const;
2273
2274 /// Get the AutoType whose type will be deduced for a variable with
2275 /// an initializer of this type. This looks through declarators like pointer
2276 /// types, but not through decltype or typedefs.
2277 AutoType *getContainedAutoType() const {
2278 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2279 }
2280
2281 /// Determine whether this type was written with a leading 'auto'
2282 /// corresponding to a trailing return type (possibly for a nested
2283 /// function type within a pointer to function type or similar).
2284 bool hasAutoForTrailingReturnType() const;
2285
2286 /// Member-template getAs<specific type>'. Look through sugar for
2287 /// an instance of \<specific type>. This scheme will eventually
2288 /// replace the specific getAsXXXX methods above.
2289 ///
2290 /// There are some specializations of this member template listed
2291 /// immediately following this class.
2292 template <typename T> const T *getAs() const;
2293
2294 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2295 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2296 /// This is used when you need to walk over sugar nodes that represent some
2297 /// kind of type adjustment from a type that was written as a \<specific type>
2298 /// to another type that is still canonically a \<specific type>.
2299 template <typename T> const T *getAsAdjusted() const;
2300
2301 /// A variant of getAs<> for array types which silently discards
2302 /// qualifiers from the outermost type.
2303 const ArrayType *getAsArrayTypeUnsafe() const;
2304
2305 /// Member-template castAs<specific type>. Look through sugar for
2306 /// the underlying instance of \<specific type>.
2307 ///
2308 /// This method has the same relationship to getAs<T> as cast<T> has
2309 /// to dyn_cast<T>; which is to say, the underlying type *must*
2310 /// have the intended type, and this method will never return null.
2311 template <typename T> const T *castAs() const;
2312
2313 /// A variant of castAs<> for array type which silently discards
2314 /// qualifiers from the outermost type.
2315 const ArrayType *castAsArrayTypeUnsafe() const;
2316
2317 /// Determine whether this type had the specified attribute applied to it
2318 /// (looking through top-level type sugar).
2319 bool hasAttr(attr::Kind AK) const;
2320
2321 /// Get the base element type of this type, potentially discarding type
2322 /// qualifiers. This should never be used when type qualifiers
2323 /// are meaningful.
2324 const Type *getBaseElementTypeUnsafe() const;
2325
2326 /// If this is an array type, return the element type of the array,
2327 /// potentially with type qualifiers missing.
2328 /// This should never be used when type qualifiers are meaningful.
2329 const Type *getArrayElementTypeNoTypeQual() const;
2330
2331 /// If this is a pointer type, return the pointee type.
2332 /// If this is an array type, return the array element type.
2333 /// This should never be used when type qualifiers are meaningful.
2334 const Type *getPointeeOrArrayElementType() const;
2335
2336 /// If this is a pointer, ObjC object pointer, or block
2337 /// pointer, this returns the respective pointee.
2338 QualType getPointeeType() const;
2339
2340 /// Return the specified type with any "sugar" removed from the type,
2341 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2342 const Type *getUnqualifiedDesugaredType() const;
2343
2344 /// More type predicates useful for type checking/promotion
2345 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2346
2347 /// Return true if this is an integer type that is
2348 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2349 /// or an enum decl which has a signed representation.
2350 bool isSignedIntegerType() const;
2351
2352 /// Return true if this is an integer type that is
2353 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2354 /// or an enum decl which has an unsigned representation.
2355 bool isUnsignedIntegerType() const;
2356
2357 /// Determines whether this is an integer type that is signed or an
2358 /// enumeration types whose underlying type is a signed integer type.
2359 bool isSignedIntegerOrEnumerationType() const;
2360
2361 /// Determines whether this is an integer type that is unsigned or an
2362 /// enumeration types whose underlying type is a unsigned integer type.
2363 bool isUnsignedIntegerOrEnumerationType() const;
2364
2365 /// Return true if this is a fixed point type according to
2366 /// ISO/IEC JTC1 SC22 WG14 N1169.
2367 bool isFixedPointType() const;
2368
2369 /// Return true if this is a fixed point or integer type.
2370 bool isFixedPointOrIntegerType() const;
2371
2372 /// Return true if this is a saturated fixed point type according to
2373 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2374 bool isSaturatedFixedPointType() const;
2375
2376 /// Return true if this is a saturated fixed point type according to
2377 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2378 bool isUnsaturatedFixedPointType() const;
2379
2380 /// Return true if this is a fixed point type that is signed according
2381 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2382 bool isSignedFixedPointType() const;
2383
2384 /// Return true if this is a fixed point type that is unsigned according
2385 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2386 bool isUnsignedFixedPointType() const;
2387
2388 /// Return true if this is not a variable sized type,
2389 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2390 /// incomplete types.
2391 bool isConstantSizeType() const;
2392
2393 /// Returns true if this type can be represented by some
2394 /// set of type specifiers.
2395 bool isSpecifierType() const;
2396
2397 /// Determine the linkage of this type.
2398 Linkage getLinkage() const;
2399
2400 /// Determine the visibility of this type.
2401 Visibility getVisibility() const {
2402 return getLinkageAndVisibility().getVisibility();
2403 }
2404
2405 /// Return true if the visibility was explicitly set is the code.
2406 bool isVisibilityExplicit() const {
2407 return getLinkageAndVisibility().isVisibilityExplicit();
2408 }
2409
2410 /// Determine the linkage and visibility of this type.
2411 LinkageInfo getLinkageAndVisibility() const;
2412
2413 /// True if the computed linkage is valid. Used for consistency
2414 /// checking. Should always return true.
2415 bool isLinkageValid() const;
2416
2417 /// Determine the nullability of the given type.
2418 ///
2419 /// Note that nullability is only captured as sugar within the type
2420 /// system, not as part of the canonical type, so nullability will
2421 /// be lost by canonicalization and desugaring.
2422 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2423
2424 /// Determine whether the given type can have a nullability
2425 /// specifier applied to it, i.e., if it is any kind of pointer type.
2426 ///
2427 /// \param ResultIfUnknown The value to return if we don't yet know whether
2428 /// this type can have nullability because it is dependent.
2429 bool canHaveNullability(bool ResultIfUnknown = true) const;
2430
2431 /// Retrieve the set of substitutions required when accessing a member
2432 /// of the Objective-C receiver type that is declared in the given context.
2433 ///
2434 /// \c *this is the type of the object we're operating on, e.g., the
2435 /// receiver for a message send or the base of a property access, and is
2436 /// expected to be of some object or object pointer type.
2437 ///
2438 /// \param dc The declaration context for which we are building up a
2439 /// substitution mapping, which should be an Objective-C class, extension,
2440 /// category, or method within.
2441 ///
2442 /// \returns an array of type arguments that can be substituted for
2443 /// the type parameters of the given declaration context in any type described
2444 /// within that context, or an empty optional to indicate that no
2445 /// substitution is required.
2446 Optional<ArrayRef<QualType>>
2447 getObjCSubstitutions(const DeclContext *dc) const;
2448
2449 /// Determines if this is an ObjC interface type that may accept type
2450 /// parameters.
2451 bool acceptsObjCTypeParams() const;
2452
2453 const char *getTypeClassName() const;
2454
2455 QualType getCanonicalTypeInternal() const {
2456 return CanonicalType;
2457 }
2458
2459 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2460 void dump() const;
2461 void dump(llvm::raw_ostream &OS) const;
2462};
2463
2464/// This will check for a TypedefType by removing any existing sugar
2465/// until it reaches a TypedefType or a non-sugared type.
2466template <> const TypedefType *Type::getAs() const;
2467
2468/// This will check for a TemplateSpecializationType by removing any
2469/// existing sugar until it reaches a TemplateSpecializationType or a
2470/// non-sugared type.
2471template <> const TemplateSpecializationType *Type::getAs() const;
2472
2473/// This will check for an AttributedType by removing any existing sugar
2474/// until it reaches an AttributedType or a non-sugared type.
2475template <> const AttributedType *Type::getAs() const;
2476
2477// We can do canonical leaf types faster, because we don't have to
2478// worry about preserving child type decoration.
2479#define TYPE(Class, Base)
2480#define LEAF_TYPE(Class) \
2481template <> inline const Class##Type *Type::getAs() const { \
2482 return dyn_cast<Class##Type>(CanonicalType); \
2483} \
2484template <> inline const Class##Type *Type::castAs() const { \
2485 return cast<Class##Type>(CanonicalType); \
2486}
2487#include "clang/AST/TypeNodes.inc"
2488
2489/// This class is used for builtin types like 'int'. Builtin
2490/// types are always canonical and have a literal name field.
2491class BuiltinType : public Type {
2492public:
2493 enum Kind {
2494// OpenCL image types
2495#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2496#include "clang/Basic/OpenCLImageTypes.def"
2497// OpenCL extension types
2498#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2499#include "clang/Basic/OpenCLExtensionTypes.def"
2500// SVE Types
2501#define SVE_TYPE(Name, Id, SingletonId) Id,
2502#include "clang/Basic/AArch64SVEACLETypes.def"
2503// All other builtin types
2504#define BUILTIN_TYPE(Id, SingletonId) Id,
2505#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2506#include "clang/AST/BuiltinTypes.def"
2507 };
2508
2509private:
2510 friend class ASTContext; // ASTContext creates these.
2511
2512 BuiltinType(Kind K)
2513 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2514 /*InstantiationDependent=*/(K == Dependent),
2515 /*VariablyModified=*/false,
2516 /*Unexpanded parameter pack=*/false) {
2517 BuiltinTypeBits.Kind = K;
2518 }
2519
2520public:
2521 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2522 StringRef getName(const PrintingPolicy &Policy) const;
2523
2524 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2525 // The StringRef is null-terminated.
2526 StringRef str = getName(Policy);
2527 assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast
<void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 2527, __PRETTY_FUNCTION__))
;
2528 return str.data();
2529 }
2530
2531 bool isSugared() const { return false; }
2532 QualType desugar() const { return QualType(this, 0); }
2533
2534 bool isInteger() const {
2535 return getKind() >= Bool && getKind() <= Int128;
2536 }
2537
2538 bool isSignedInteger() const {
2539 return getKind() >= Char_S && getKind() <= Int128;
2540 }
2541
2542 bool isUnsignedInteger() const {
2543 return getKind() >= Bool && getKind() <= UInt128;
2544 }
2545
2546 bool isFloatingPoint() const {
2547 return getKind() >= Half && getKind() <= Float128;
2548 }
2549
2550 /// Determines whether the given kind corresponds to a placeholder type.
2551 static bool isPlaceholderTypeKind(Kind K) {
2552 return K >= Overload;
2553 }
2554
2555 /// Determines whether this type is a placeholder type, i.e. a type
2556 /// which cannot appear in arbitrary positions in a fully-formed
2557 /// expression.
2558 bool isPlaceholderType() const {
2559 return isPlaceholderTypeKind(getKind());
2560 }
2561
2562 /// Determines whether this type is a placeholder type other than
2563 /// Overload. Most placeholder types require only syntactic
2564 /// information about their context in order to be resolved (e.g.
2565 /// whether it is a call expression), which means they can (and
2566 /// should) be resolved in an earlier "phase" of analysis.
2567 /// Overload expressions sometimes pick up further information
2568 /// from their context, like whether the context expects a
2569 /// specific function-pointer type, and so frequently need
2570 /// special treatment.
2571 bool isNonOverloadPlaceholderType() const {
2572 return getKind() > Overload;
2573 }
2574
2575 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2576};
2577
2578/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2579/// types (_Complex float etc) as well as the GCC integer complex extensions.
2580class ComplexType : public Type, public llvm::FoldingSetNode {
2581 friend class ASTContext; // ASTContext creates these.
2582
2583 QualType ElementType;
2584
2585 ComplexType(QualType Element, QualType CanonicalPtr)
2586 : Type(Complex, CanonicalPtr, Element->isDependentType(),
2587 Element->isInstantiationDependentType(),
2588 Element->isVariablyModifiedType(),
2589 Element->containsUnexpandedParameterPack()),
2590 ElementType(Element) {}
2591
2592public:
2593 QualType getElementType() const { return ElementType; }
2594
2595 bool isSugared() const { return false; }
2596 QualType desugar() const { return QualType(this, 0); }
2597
2598 void Profile(llvm::FoldingSetNodeID &ID) {
2599 Profile(ID, getElementType());
2600 }
2601
2602 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2603 ID.AddPointer(Element.getAsOpaquePtr());
2604 }
2605
2606 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2607};
2608
2609/// Sugar for parentheses used when specifying types.
2610class ParenType : public Type, public llvm::FoldingSetNode {
2611 friend class ASTContext; // ASTContext creates these.
2612
2613 QualType Inner;
2614
2615 ParenType(QualType InnerType, QualType CanonType)
2616 : Type(Paren, CanonType, InnerType->isDependentType(),
2617 InnerType->isInstantiationDependentType(),
2618 InnerType->isVariablyModifiedType(),
2619 InnerType->containsUnexpandedParameterPack()),
2620 Inner(InnerType) {}
2621
2622public:
2623 QualType getInnerType() const { return Inner; }
2624
2625 bool isSugared() const { return true; }
2626 QualType desugar() const { return getInnerType(); }
2627
2628 void Profile(llvm::FoldingSetNodeID &ID) {
2629 Profile(ID, getInnerType());
2630 }
2631
2632 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2633 Inner.Profile(ID);
2634 }
2635
2636 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2637};
2638
2639/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2640class PointerType : public Type, public llvm::FoldingSetNode {
2641 friend class ASTContext; // ASTContext creates these.
2642
2643 QualType PointeeType;
2644
2645 PointerType(QualType Pointee, QualType CanonicalPtr)
2646 : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2647 Pointee->isInstantiationDependentType(),
2648 Pointee->isVariablyModifiedType(),
2649 Pointee->containsUnexpandedParameterPack()),
2650 PointeeType(Pointee) {}
2651
2652public:
2653 QualType getPointeeType() const { return PointeeType; }
2654
2655 /// Returns true if address spaces of pointers overlap.
2656 /// OpenCL v2.0 defines conversion rules for pointers to different
2657 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2658 /// address spaces.
2659 /// CL1.1 or CL1.2:
2660 /// address spaces overlap iff they are they same.
2661 /// CL2.0 adds:
2662 /// __generic overlaps with any address space except for __constant.
2663 bool isAddressSpaceOverlapping(const PointerType &other) const {
2664 Qualifiers thisQuals = PointeeType.getQualifiers();
2665 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2666 // Address spaces overlap if at least one of them is a superset of another
2667 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2668 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2669 }
2670
2671 bool isSugared() const { return false; }
2672 QualType desugar() const { return QualType(this, 0); }
2673
2674 void Profile(llvm::FoldingSetNodeID &ID) {
2675 Profile(ID, getPointeeType());
2676 }
2677
2678 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2679 ID.AddPointer(Pointee.getAsOpaquePtr());
2680 }
2681
2682 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2683};
2684
2685/// Represents a type which was implicitly adjusted by the semantic
2686/// engine for arbitrary reasons. For example, array and function types can
2687/// decay, and function types can have their calling conventions adjusted.
2688class AdjustedType : public Type, public llvm::FoldingSetNode {
2689 QualType OriginalTy;
2690 QualType AdjustedTy;
2691
2692protected:
2693 friend class ASTContext; // ASTContext creates these.
2694
2695 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2696 QualType CanonicalPtr)
2697 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2698 OriginalTy->isInstantiationDependentType(),
2699 OriginalTy->isVariablyModifiedType(),
2700 OriginalTy->containsUnexpandedParameterPack()),
2701 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2702
2703public:
2704 QualType getOriginalType() const { return OriginalTy; }
2705 QualType getAdjustedType() const { return AdjustedTy; }
2706
2707 bool isSugared() const { return true; }
2708 QualType desugar() const { return AdjustedTy; }
2709
2710 void Profile(llvm::FoldingSetNodeID &ID) {
2711 Profile(ID, OriginalTy, AdjustedTy);
2712 }
2713
2714 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2715 ID.AddPointer(Orig.getAsOpaquePtr());
2716 ID.AddPointer(New.getAsOpaquePtr());
2717 }
2718
2719 static bool classof(const Type *T) {
2720 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2721 }
2722};
2723
2724/// Represents a pointer type decayed from an array or function type.
2725class DecayedType : public AdjustedType {
2726 friend class ASTContext; // ASTContext creates these.
2727
2728 inline
2729 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2730
2731public:
2732 QualType getDecayedType() const { return getAdjustedType(); }
2733
2734 inline QualType getPointeeType() const;
2735
2736 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2737};
2738
2739/// Pointer to a block type.
2740/// This type is to represent types syntactically represented as
2741/// "void (^)(int)", etc. Pointee is required to always be a function type.
2742class BlockPointerType : public Type, public llvm::FoldingSetNode {
2743 friend class ASTContext; // ASTContext creates these.
2744
2745 // Block is some kind of pointer type
2746 QualType PointeeType;
2747
2748 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2749 : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2750 Pointee->isInstantiationDependentType(),
2751 Pointee->isVariablyModifiedType(),
2752 Pointee->containsUnexpandedParameterPack()),
2753 PointeeType(Pointee) {}
2754
2755public:
2756 // Get the pointee type. Pointee is required to always be a function type.
2757 QualType getPointeeType() const { return PointeeType; }
2758
2759 bool isSugared() const { return false; }
2760 QualType desugar() const { return QualType(this, 0); }
2761
2762 void Profile(llvm::FoldingSetNodeID &ID) {
2763 Profile(ID, getPointeeType());
2764 }
2765
2766 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2767 ID.AddPointer(Pointee.getAsOpaquePtr());
2768 }
2769
2770 static bool classof(const Type *T) {
2771 return T->getTypeClass() == BlockPointer;
2772 }
2773};
2774
2775/// Base for LValueReferenceType and RValueReferenceType
2776class ReferenceType : public Type, public llvm::FoldingSetNode {
2777 QualType PointeeType;
2778
2779protected:
2780 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2781 bool SpelledAsLValue)
2782 : Type(tc, CanonicalRef, Referencee->isDependentType(),
2783 Referencee->isInstantiationDependentType(),
2784 Referencee->isVariablyModifiedType(),
2785 Referencee->containsUnexpandedParameterPack()),
2786 PointeeType(Referencee) {
2787 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2788 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2789 }
2790
2791public:
2792 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2793 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2794
2795 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2796
2797 QualType getPointeeType() const {
2798 // FIXME: this might strip inner qualifiers; okay?
2799 const ReferenceType *T = this;
2800 while (T->isInnerRef())
2801 T = T->PointeeType->castAs<ReferenceType>();
2802 return T->PointeeType;
2803 }
2804
2805 void Profile(llvm::FoldingSetNodeID &ID) {
2806 Profile(ID, PointeeType, isSpelledAsLValue());
2807 }
2808
2809 static void Profile(llvm::FoldingSetNodeID &ID,
2810 QualType Referencee,
2811 bool SpelledAsLValue) {
2812 ID.AddPointer(Referencee.getAsOpaquePtr());
2813 ID.AddBoolean(SpelledAsLValue);
2814 }
2815
2816 static bool classof(const Type *T) {
2817 return T->getTypeClass() == LValueReference ||
2818 T->getTypeClass() == RValueReference;
2819 }
2820};
2821
2822/// An lvalue reference type, per C++11 [dcl.ref].
2823class LValueReferenceType : public ReferenceType {
2824 friend class ASTContext; // ASTContext creates these
2825
2826 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2827 bool SpelledAsLValue)
2828 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2829 SpelledAsLValue) {}
2830
2831public:
2832 bool isSugared() const { return false; }
2833 QualType desugar() const { return QualType(this, 0); }
2834
2835 static bool classof(const Type *T) {
2836 return T->getTypeClass() == LValueReference;
2837 }
2838};
2839
2840/// An rvalue reference type, per C++11 [dcl.ref].
2841class RValueReferenceType : public ReferenceType {
2842 friend class ASTContext; // ASTContext creates these
2843
2844 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2845 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2846
2847public:
2848 bool isSugared() const { return false; }
2849 QualType desugar() const { return QualType(this, 0); }
2850
2851 static bool classof(const Type *T) {
2852 return T->getTypeClass() == RValueReference;
2853 }
2854};
2855
2856/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2857///
2858/// This includes both pointers to data members and pointer to member functions.
2859class MemberPointerType : public Type, public llvm::FoldingSetNode {
2860 friend class ASTContext; // ASTContext creates these.
2861
2862 QualType PointeeType;
2863
2864 /// The class of which the pointee is a member. Must ultimately be a
2865 /// RecordType, but could be a typedef or a template parameter too.
2866 const Type *Class;
2867
2868 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2869 : Type(MemberPointer, CanonicalPtr,
2870 Cls->isDependentType() || Pointee->isDependentType(),
2871 (Cls->isInstantiationDependentType() ||
2872 Pointee->isInstantiationDependentType()),
2873 Pointee->isVariablyModifiedType(),
2874 (Cls->containsUnexpandedParameterPack() ||
2875 Pointee->containsUnexpandedParameterPack())),
2876 PointeeType(Pointee), Class(Cls) {}
2877
2878public:
2879 QualType getPointeeType() const { return PointeeType; }
2880
2881 /// Returns true if the member type (i.e. the pointee type) is a
2882 /// function type rather than a data-member type.
2883 bool isMemberFunctionPointer() const {
2884 return PointeeType->isFunctionProtoType();
2885 }
2886
2887 /// Returns true if the member type (i.e. the pointee type) is a
2888 /// data type rather than a function type.
2889 bool isMemberDataPointer() const {
2890 return !PointeeType->isFunctionProtoType();
2891 }
2892
2893 const Type *getClass() const { return Class; }
2894 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2895
2896 bool isSugared() const { return false; }
2897 QualType desugar() const { return QualType(this, 0); }
2898
2899 void Profile(llvm::FoldingSetNodeID &ID) {
2900 Profile(ID, getPointeeType(), getClass());
2901 }
2902
2903 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2904 const Type *Class) {
2905 ID.AddPointer(Pointee.getAsOpaquePtr());
2906 ID.AddPointer(Class);
2907 }
2908
2909 static bool classof(const Type *T) {
2910 return T->getTypeClass() == MemberPointer;
2911 }
2912};
2913
2914/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2915class ArrayType : public Type, public llvm::FoldingSetNode {
2916public:
2917 /// Capture whether this is a normal array (e.g. int X[4])
2918 /// an array with a static size (e.g. int X[static 4]), or an array
2919 /// with a star size (e.g. int X[*]).
2920 /// 'static' is only allowed on function parameters.
2921 enum ArraySizeModifier {
2922 Normal, Static, Star
2923 };
2924
2925private:
2926 /// The element type of the array.
2927 QualType ElementType;
2928
2929protected:
2930 friend class ASTContext; // ASTContext creates these.
2931
2932 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm,
2933 unsigned tq, const Expr *sz = nullptr);
2934
2935public:
2936 QualType getElementType() const { return ElementType; }
2937
2938 ArraySizeModifier getSizeModifier() const {
2939 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2940 }
2941
2942 Qualifiers getIndexTypeQualifiers() const {
2943 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2944 }
2945
2946 unsigned getIndexTypeCVRQualifiers() const {
2947 return ArrayTypeBits.IndexTypeQuals;
2948 }
2949
2950 static bool classof(const Type *T) {
2951 return T->getTypeClass() == ConstantArray ||
2952 T->getTypeClass() == VariableArray ||
2953 T->getTypeClass() == IncompleteArray ||
2954 T->getTypeClass() == DependentSizedArray;
2955 }
2956};
2957
2958/// Represents the canonical version of C arrays with a specified constant size.
2959/// For example, the canonical type for 'int A[4 + 4*100]' is a
2960/// ConstantArrayType where the element type is 'int' and the size is 404.
2961class ConstantArrayType final
2962 : public ArrayType,
2963 private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
2964 friend class ASTContext; // ASTContext creates these.
2965 friend TrailingObjects;
2966
2967 llvm::APInt Size; // Allows us to unique the type.
2968
2969 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2970 const Expr *sz, ArraySizeModifier sm, unsigned tq)
2971 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
2972 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
2973 if (ConstantArrayTypeBits.HasStoredSizeExpr) {
2974 assert(!can.isNull() && "canonical constant array should not have size")((!can.isNull() && "canonical constant array should not have size"
) ? static_cast<void> (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 2974, __PRETTY_FUNCTION__))
;
2975 *getTrailingObjects<const Expr*>() = sz;
2976 }
2977 }
2978
2979 unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
2980 return ConstantArrayTypeBits.HasStoredSizeExpr;
2981 }
2982
2983public:
2984 const llvm::APInt &getSize() const { return Size; }
2985 const Expr *getSizeExpr() const {
2986 return ConstantArrayTypeBits.HasStoredSizeExpr
2987 ? *getTrailingObjects<const Expr *>()
2988 : nullptr;
2989 }
2990 bool isSugared() const { return false; }
2991 QualType desugar() const { return QualType(this, 0); }
2992
2993 /// Determine the number of bits required to address a member of
2994 // an array with the given element type and number of elements.
2995 static unsigned getNumAddressingBits(const ASTContext &Context,
2996 QualType ElementType,
2997 const llvm::APInt &NumElements);
2998
2999 /// Determine the maximum number of active bits that an array's size
3000 /// can require, which limits the maximum size of the array.
3001 static unsigned getMaxSizeBits(const ASTContext &Context);
3002
3003 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
3004 Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(),
3005 getSizeModifier(), getIndexTypeCVRQualifiers());
3006 }
3007
3008 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
3009 QualType ET, const llvm::APInt &ArraySize,
3010 const Expr *SizeExpr, ArraySizeModifier SizeMod,
3011 unsigned TypeQuals);
3012
3013 static bool classof(const Type *T) {
3014 return T->getTypeClass() == ConstantArray;
3015 }
3016};
3017
3018/// Represents a C array with an unspecified size. For example 'int A[]' has
3019/// an IncompleteArrayType where the element type is 'int' and the size is
3020/// unspecified.
3021class IncompleteArrayType : public ArrayType {
3022 friend class ASTContext; // ASTContext creates these.
3023
3024 IncompleteArrayType(QualType et, QualType can,
3025 ArraySizeModifier sm, unsigned tq)
3026 : ArrayType(IncompleteArray, et, can, sm, tq) {}
3027
3028public:
3029 friend class StmtIteratorBase;
3030
3031 bool isSugared() const { return false; }
3032 QualType desugar() const { return QualType(this, 0); }
3033
3034 static bool classof(const Type *T) {
3035 return T->getTypeClass() == IncompleteArray;
3036 }
3037
3038 void Profile(llvm::FoldingSetNodeID &ID) {
3039 Profile(ID, getElementType(), getSizeModifier(),
3040 getIndexTypeCVRQualifiers());
3041 }
3042
3043 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
3044 ArraySizeModifier SizeMod, unsigned TypeQuals) {
3045 ID.AddPointer(ET.getAsOpaquePtr());
3046 ID.AddInteger(SizeMod);
3047 ID.AddInteger(TypeQuals);
3048 }
3049};
3050
3051/// Represents a C array with a specified size that is not an
3052/// integer-constant-expression. For example, 'int s[x+foo()]'.
3053/// Since the size expression is an arbitrary expression, we store it as such.
3054///
3055/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3056/// should not be: two lexically equivalent variable array types could mean
3057/// different things, for example, these variables do not have the same type
3058/// dynamically:
3059///
3060/// void foo(int x) {
3061/// int Y[x];
3062/// ++x;
3063/// int Z[x];
3064/// }
3065class VariableArrayType : public ArrayType {
3066 friend class ASTContext; // ASTContext creates these.
3067
3068 /// An assignment-expression. VLA's are only permitted within
3069 /// a function block.
3070 Stmt *SizeExpr;
3071
3072 /// The range spanned by the left and right array brackets.
3073 SourceRange Brackets;
3074
3075 VariableArrayType(QualType et, QualType can, Expr *e,
3076 ArraySizeModifier sm, unsigned tq,
3077 SourceRange brackets)
3078 : ArrayType(VariableArray, et, can, sm, tq, e),
3079 SizeExpr((Stmt*) e), Brackets(brackets) {}
3080
3081public:
3082 friend class StmtIteratorBase;
3083
3084 Expr *getSizeExpr() const {
3085 // We use C-style casts instead of cast<> here because we do not wish
3086 // to have a dependency of Type.h on Stmt.h/Expr.h.
3087 return (Expr*) SizeExpr;
3088 }
3089
3090 SourceRange getBracketsRange() const { return Brackets; }
3091 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3092 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3093
3094 bool isSugared() const { return false; }
3095 QualType desugar() const { return QualType(this, 0); }
3096
3097 static bool classof(const Type *T) {
3098 return T->getTypeClass() == VariableArray;
3099 }
3100
3101 void Profile(llvm::FoldingSetNodeID &ID) {
3102 llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes."
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 3102)
;
3103 }
3104};
3105
3106/// Represents an array type in C++ whose size is a value-dependent expression.
3107///
3108/// For example:
3109/// \code
3110/// template<typename T, int Size>
3111/// class array {
3112/// T data[Size];
3113/// };
3114/// \endcode
3115///
3116/// For these types, we won't actually know what the array bound is
3117/// until template instantiation occurs, at which point this will
3118/// become either a ConstantArrayType or a VariableArrayType.
3119class DependentSizedArrayType : public ArrayType {
3120 friend class ASTContext; // ASTContext creates these.
3121
3122 const ASTContext &Context;
3123
3124 /// An assignment expression that will instantiate to the
3125 /// size of the array.
3126 ///
3127 /// The expression itself might be null, in which case the array
3128 /// type will have its size deduced from an initializer.
3129 Stmt *SizeExpr;
3130
3131 /// The range spanned by the left and right array brackets.
3132 SourceRange Brackets;
3133
3134 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3135 Expr *e, ArraySizeModifier sm, unsigned tq,
3136 SourceRange brackets);
3137
3138public:
3139 friend class StmtIteratorBase;
3140
3141 Expr *getSizeExpr() const {
3142 // We use C-style casts instead of cast<> here because we do not wish
3143 // to have a dependency of Type.h on Stmt.h/Expr.h.
3144 return (Expr*) SizeExpr;
3145 }
3146
3147 SourceRange getBracketsRange() const { return Brackets; }
3148 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3149 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3150
3151 bool isSugared() const { return false; }
3152 QualType desugar() const { return QualType(this, 0); }
3153
3154 static bool classof(const Type *T) {
3155 return T->getTypeClass() == DependentSizedArray;
3156 }
3157
3158 void Profile(llvm::FoldingSetNodeID &ID) {
3159 Profile(ID, Context, getElementType(),
3160 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3161 }
3162
3163 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3164 QualType ET, ArraySizeModifier SizeMod,
3165 unsigned TypeQuals, Expr *E);
3166};
3167
3168/// Represents an extended address space qualifier where the input address space
3169/// value is dependent. Non-dependent address spaces are not represented with a
3170/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3171///
3172/// For example:
3173/// \code
3174/// template<typename T, int AddrSpace>
3175/// class AddressSpace {
3176/// typedef T __attribute__((address_space(AddrSpace))) type;
3177/// }
3178/// \endcode
3179class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3180 friend class ASTContext;
3181
3182 const ASTContext &Context;
3183 Expr *AddrSpaceExpr;
3184 QualType PointeeType;
3185 SourceLocation loc;
3186
3187 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3188 QualType can, Expr *AddrSpaceExpr,
3189 SourceLocation loc);
3190
3191public:
3192 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3193 QualType getPointeeType() const { return PointeeType; }
3194 SourceLocation getAttributeLoc() const { return loc; }
3195
3196 bool isSugared() const { return false; }
3197 QualType desugar() const { return QualType(this, 0); }
3198
3199 static bool classof(const Type *T) {
3200 return T->getTypeClass() == DependentAddressSpace;
3201 }
3202
3203 void Profile(llvm::FoldingSetNodeID &ID) {
3204 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3205 }
3206
3207 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3208 QualType PointeeType, Expr *AddrSpaceExpr);
3209};
3210
3211/// Represents an extended vector type where either the type or size is
3212/// dependent.
3213///
3214/// For example:
3215/// \code
3216/// template<typename T, int Size>
3217/// class vector {
3218/// typedef T __attribute__((ext_vector_type(Size))) type;
3219/// }
3220/// \endcode
3221class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3222 friend class ASTContext;
3223
3224 const ASTContext &Context;
3225 Expr *SizeExpr;
3226
3227 /// The element type of the array.
3228 QualType ElementType;
3229
3230 SourceLocation loc;
3231
3232 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3233 QualType can, Expr *SizeExpr, SourceLocation loc);
3234
3235public:
3236 Expr *getSizeExpr() const { return SizeExpr; }
3237 QualType getElementType() const { return ElementType; }
3238 SourceLocation getAttributeLoc() const { return loc; }
3239
3240 bool isSugared() const { return false; }
3241 QualType desugar() const { return QualType(this, 0); }
3242
3243 static bool classof(const Type *T) {
3244 return T->getTypeClass() == DependentSizedExtVector;
3245 }
3246
3247 void Profile(llvm::FoldingSetNodeID &ID) {
3248 Profile(ID, Context, getElementType(), getSizeExpr());
3249 }
3250
3251 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3252 QualType ElementType, Expr *SizeExpr);
3253};
3254
3255
3256/// Represents a GCC generic vector type. This type is created using
3257/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3258/// bytes; or from an Altivec __vector or vector declaration.
3259/// Since the constructor takes the number of vector elements, the
3260/// client is responsible for converting the size into the number of elements.
3261class VectorType : public Type, public llvm::FoldingSetNode {
3262public:
3263 enum VectorKind {
3264 /// not a target-specific vector type
3265 GenericVector,
3266
3267 /// is AltiVec vector
3268 AltiVecVector,
3269
3270 /// is AltiVec 'vector Pixel'
3271 AltiVecPixel,
3272
3273 /// is AltiVec 'vector bool ...'
3274 AltiVecBool,
3275
3276 /// is ARM Neon vector
3277 NeonVector,
3278
3279 /// is ARM Neon polynomial vector
3280 NeonPolyVector
3281 };
3282
3283protected:
3284 friend class ASTContext; // ASTContext creates these.
3285
3286 /// The element type of the vector.
3287 QualType ElementType;
3288
3289 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3290 VectorKind vecKind);
3291
3292 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3293 QualType canonType, VectorKind vecKind);
3294
3295public:
3296 QualType getElementType() const { return ElementType; }
3297 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3298
3299 static bool isVectorSizeTooLarge(unsigned NumElements) {
3300 return NumElements > VectorTypeBitfields::MaxNumElements;
3301 }
3302
3303 bool isSugared() const { return false; }
3304 QualType desugar() const { return QualType(this, 0); }
3305
3306 VectorKind getVectorKind() const {
3307 return VectorKind(VectorTypeBits.VecKind);
3308 }
3309
3310 void Profile(llvm::FoldingSetNodeID &ID) {
3311 Profile(ID, getElementType(), getNumElements(),
3312 getTypeClass(), getVectorKind());
3313 }
3314
3315 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3316 unsigned NumElements, TypeClass TypeClass,
3317 VectorKind VecKind) {
3318 ID.AddPointer(ElementType.getAsOpaquePtr());
3319 ID.AddInteger(NumElements);
3320 ID.AddInteger(TypeClass);
3321 ID.AddInteger(VecKind);
3322 }
3323
3324 static bool classof(const Type *T) {
3325 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3326 }
3327};
3328
3329/// Represents a vector type where either the type or size is dependent.
3330////
3331/// For example:
3332/// \code
3333/// template<typename T, int Size>
3334/// class vector {
3335/// typedef T __attribute__((vector_size(Size))) type;
3336/// }
3337/// \endcode
3338class DependentVectorType : public Type, public llvm::FoldingSetNode {
3339 friend class ASTContext;
3340
3341 const ASTContext &Context;
3342 QualType ElementType;
3343 Expr *SizeExpr;
3344 SourceLocation Loc;
3345
3346 DependentVectorType(const ASTContext &Context, QualType ElementType,
3347 QualType CanonType, Expr *SizeExpr,
3348 SourceLocation Loc, VectorType::VectorKind vecKind);
3349
3350public:
3351 Expr *getSizeExpr() const { return SizeExpr; }
3352 QualType getElementType() const { return ElementType; }
3353 SourceLocation getAttributeLoc() const { return Loc; }
3354 VectorType::VectorKind getVectorKind() const {
3355 return VectorType::VectorKind(VectorTypeBits.VecKind);
3356 }
3357
3358 bool isSugared() const { return false; }
3359 QualType desugar() const { return QualType(this, 0); }
3360
3361 static bool classof(const Type *T) {
3362 return T->getTypeClass() == DependentVector;
3363 }
3364
3365 void Profile(llvm::FoldingSetNodeID &ID) {
3366 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3367 }
3368
3369 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3370 QualType ElementType, const Expr *SizeExpr,
3371 VectorType::VectorKind VecKind);
3372};
3373
3374/// ExtVectorType - Extended vector type. This type is created using
3375/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3376/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3377/// class enables syntactic extensions, like Vector Components for accessing
3378/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3379/// Shading Language).
3380class ExtVectorType : public VectorType {
3381 friend class ASTContext; // ASTContext creates these.
3382
3383 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3384 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3385
3386public:
3387 static int getPointAccessorIdx(char c) {
3388 switch (c) {
3389 default: return -1;
3390 case 'x': case 'r': return 0;
3391 case 'y': case 'g': return 1;
3392 case 'z': case 'b': return 2;
3393 case 'w': case 'a': return 3;
3394 }
3395 }
3396
3397 static int getNumericAccessorIdx(char c) {
3398 switch (c) {
3399 default: return -1;
3400 case '0': return 0;
3401 case '1': return 1;
3402 case '2': return 2;
3403 case '3': return 3;
3404 case '4': return 4;
3405 case '5': return 5;
3406 case '6': return 6;
3407 case '7': return 7;
3408 case '8': return 8;
3409 case '9': return 9;
3410 case 'A':
3411 case 'a': return 10;
3412 case 'B':
3413 case 'b': return 11;
3414 case 'C':
3415 case 'c': return 12;
3416 case 'D':
3417 case 'd': return 13;
3418 case 'E':
3419 case 'e': return 14;
3420 case 'F':
3421 case 'f': return 15;
3422 }
3423 }
3424
3425 static int getAccessorIdx(char c, bool isNumericAccessor) {
3426 if (isNumericAccessor)
3427 return getNumericAccessorIdx(c);
3428 else
3429 return getPointAccessorIdx(c);
3430 }
3431
3432 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3433 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3434 return unsigned(idx-1) < getNumElements();
3435 return false;
3436 }
3437
3438 bool isSugared() const { return false; }
3439 QualType desugar() const { return QualType(this, 0); }
3440
3441 static bool classof(const Type *T) {
3442 return T->getTypeClass() == ExtVector;
3443 }
3444};
3445
3446/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3447/// class of FunctionNoProtoType and FunctionProtoType.
3448class FunctionType : public Type {
3449 // The type returned by the function.
3450 QualType ResultType;
3451
3452public:
3453 /// Interesting information about a specific parameter that can't simply
3454 /// be reflected in parameter's type. This is only used by FunctionProtoType
3455 /// but is in FunctionType to make this class available during the
3456 /// specification of the bases of FunctionProtoType.
3457 ///
3458 /// It makes sense to model language features this way when there's some
3459 /// sort of parameter-specific override (such as an attribute) that
3460 /// affects how the function is called. For example, the ARC ns_consumed
3461 /// attribute changes whether a parameter is passed at +0 (the default)
3462 /// or +1 (ns_consumed). This must be reflected in the function type,
3463 /// but isn't really a change to the parameter type.
3464 ///
3465 /// One serious disadvantage of modelling language features this way is
3466 /// that they generally do not work with language features that attempt
3467 /// to destructure types. For example, template argument deduction will
3468 /// not be able to match a parameter declared as
3469 /// T (*)(U)
3470 /// against an argument of type
3471 /// void (*)(__attribute__((ns_consumed)) id)
3472 /// because the substitution of T=void, U=id into the former will
3473 /// not produce the latter.
3474 class ExtParameterInfo {
3475 enum {
3476 ABIMask = 0x0F,
3477 IsConsumed = 0x10,
3478 HasPassObjSize = 0x20,
3479 IsNoEscape = 0x40,
3480 };
3481 unsigned char Data = 0;
3482
3483 public:
3484 ExtParameterInfo() = default;
3485
3486 /// Return the ABI treatment of this parameter.
3487 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3488 ExtParameterInfo withABI(ParameterABI kind) const {
3489 ExtParameterInfo copy = *this;
3490 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3491 return copy;
3492 }
3493
3494 /// Is this parameter considered "consumed" by Objective-C ARC?
3495 /// Consumed parameters must have retainable object type.
3496 bool isConsumed() const { return (Data & IsConsumed); }
3497 ExtParameterInfo withIsConsumed(bool consumed) const {
3498 ExtParameterInfo copy = *this;
3499 if (consumed)
3500 copy.Data |= IsConsumed;
3501 else
3502 copy.Data &= ~IsConsumed;
3503 return copy;
3504 }
3505
3506 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3507 ExtParameterInfo withHasPassObjectSize() const {
3508 ExtParameterInfo Copy = *this;
3509 Copy.Data |= HasPassObjSize;
3510 return Copy;
3511 }
3512
3513 bool isNoEscape() const { return Data & IsNoEscape; }
3514 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3515 ExtParameterInfo Copy = *this;
3516 if (NoEscape)
3517 Copy.Data |= IsNoEscape;
3518 else
3519 Copy.Data &= ~IsNoEscape;
3520 return Copy;
3521 }
3522
3523 unsigned char getOpaqueValue() const { return Data; }
3524 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3525 ExtParameterInfo result;
3526 result.Data = data;
3527 return result;
3528 }
3529
3530 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3531 return lhs.Data == rhs.Data;
3532 }
3533
3534 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3535 return lhs.Data != rhs.Data;
3536 }
3537 };
3538
3539 /// A class which abstracts out some details necessary for
3540 /// making a call.
3541 ///
3542 /// It is not actually used directly for storing this information in
3543 /// a FunctionType, although FunctionType does currently use the
3544 /// same bit-pattern.
3545 ///
3546 // If you add a field (say Foo), other than the obvious places (both,
3547 // constructors, compile failures), what you need to update is
3548 // * Operator==
3549 // * getFoo
3550 // * withFoo
3551 // * functionType. Add Foo, getFoo.
3552 // * ASTContext::getFooType
3553 // * ASTContext::mergeFunctionTypes
3554 // * FunctionNoProtoType::Profile
3555 // * FunctionProtoType::Profile
3556 // * TypePrinter::PrintFunctionProto
3557 // * AST read and write
3558 // * Codegen
3559 class ExtInfo {
3560 friend class FunctionType;
3561
3562 // Feel free to rearrange or add bits, but if you go over 12,
3563 // you'll need to adjust both the Bits field below and
3564 // Type::FunctionTypeBitfields.
3565
3566 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3567 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
3568 //
3569 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3570 enum { CallConvMask = 0x1F };
3571 enum { NoReturnMask = 0x20 };
3572 enum { ProducesResultMask = 0x40 };
3573 enum { NoCallerSavedRegsMask = 0x80 };
3574 enum { NoCfCheckMask = 0x800 };
3575 enum {
3576 RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3577 NoCallerSavedRegsMask | NoCfCheckMask),
3578 RegParmOffset = 8
3579 }; // Assumed to be the last field
3580 uint16_t Bits = CC_C;
3581
3582 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3583
3584 public:
3585 // Constructor with no defaults. Use this when you know that you
3586 // have all the elements (when reading an AST file for example).
3587 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3588 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3589 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value"
) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 3589, __PRETTY_FUNCTION__))
;
3590 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3591 (producesResult ? ProducesResultMask : 0) |
3592 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3593 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3594 (NoCfCheck ? NoCfCheckMask : 0);
3595 }
3596
3597 // Constructor with all defaults. Use when for example creating a
3598 // function known to use defaults.
3599 ExtInfo() = default;
3600
3601 // Constructor with just the calling convention, which is an important part
3602 // of the canonical type.
3603 ExtInfo(CallingConv CC) : Bits(CC) {}
3604
3605 bool getNoReturn() const { return Bits & NoReturnMask; }
3606 bool getProducesResult() const { return Bits & ProducesResultMask; }
3607 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3608 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3609 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3610
3611 unsigned getRegParm() const {
3612 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3613 if (RegParm > 0)
3614 --RegParm;
3615 return RegParm;
3616 }
3617
3618 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3619
3620 bool operator==(ExtInfo Other) const {
3621 return Bits == Other.Bits;
3622 }
3623 bool operator!=(ExtInfo Other) const {
3624 return Bits != Other.Bits;
3625 }
3626
3627 // Note that we don't have setters. That is by design, use
3628 // the following with methods instead of mutating these objects.
3629
3630 ExtInfo withNoReturn(bool noReturn) const {
3631 if (noReturn)
3632 return ExtInfo(Bits | NoReturnMask);
3633 else
3634 return ExtInfo(Bits & ~NoReturnMask);
3635 }
3636
3637 ExtInfo withProducesResult(bool producesResult) const {
3638 if (producesResult)
3639 return ExtInfo(Bits | ProducesResultMask);
3640 else
3641 return ExtInfo(Bits & ~ProducesResultMask);
3642 }
3643
3644 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3645 if (noCallerSavedRegs)
3646 return ExtInfo(Bits | NoCallerSavedRegsMask);
3647 else
3648 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3649 }
3650
3651 ExtInfo withNoCfCheck(bool noCfCheck) const {
3652 if (noCfCheck)
3653 return ExtInfo(Bits | NoCfCheckMask);
3654 else
3655 return ExtInfo(Bits & ~NoCfCheckMask);
3656 }
3657
3658 ExtInfo withRegParm(unsigned RegParm) const {
3659 assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast
<void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 3659, __PRETTY_FUNCTION__))
;
3660 return ExtInfo((Bits & ~RegParmMask) |
3661 ((RegParm + 1) << RegParmOffset));
3662 }
3663
3664 ExtInfo withCallingConv(CallingConv cc) const {
3665 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3666 }
3667
3668 void Profile(llvm::FoldingSetNodeID &ID) const {
3669 ID.AddInteger(Bits);
3670 }
3671 };
3672
3673 /// A simple holder for a QualType representing a type in an
3674 /// exception specification. Unfortunately needed by FunctionProtoType
3675 /// because TrailingObjects cannot handle repeated types.
3676 struct ExceptionType { QualType Type; };
3677
3678 /// A simple holder for various uncommon bits which do not fit in
3679 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3680 /// alignment of subsequent objects in TrailingObjects. You must update
3681 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3682 struct alignas(void *) FunctionTypeExtraBitfields {
3683 /// The number of types in the exception specification.
3684 /// A whole unsigned is not needed here and according to
3685 /// [implimits] 8 bits would be enough here.
3686 unsigned NumExceptionType;
3687 };
3688
3689protected:
3690 FunctionType(TypeClass tc, QualType res,
3691 QualType Canonical, bool Dependent,
3692 bool InstantiationDependent,
3693 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3694 ExtInfo Info)
3695 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3696 ContainsUnexpandedParameterPack),
3697 ResultType(res) {
3698 FunctionTypeBits.ExtInfo = Info.Bits;
3699 }
3700
3701 Qualifiers getFastTypeQuals() const {
3702 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3703 }
3704
3705public:
3706 QualType getReturnType() const { return ResultType; }
3707
3708 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3709 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3710
3711 /// Determine whether this function type includes the GNU noreturn
3712 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3713 /// type.
3714 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3715
3716 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3717 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3718
3719 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3720 "Const, volatile and restrict are assumed to be a subset of "
3721 "the fast qualifiers.");
3722
3723 bool isConst() const { return getFastTypeQuals().hasConst(); }
3724 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3725 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3726
3727 /// Determine the type of an expression that calls a function of
3728 /// this type.
3729 QualType getCallResultType(const ASTContext &Context) const {
3730 return getReturnType().getNonLValueExprType(Context);
3731 }
3732
3733 static StringRef getNameForCallConv(CallingConv CC);
3734
3735 static bool classof(const Type *T) {
3736 return T->getTypeClass() == FunctionNoProto ||
3737 T->getTypeClass() == FunctionProto;
3738 }
3739};
3740
3741/// Represents a K&R-style 'int foo()' function, which has
3742/// no information available about its arguments.
3743class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3744 friend class ASTContext; // ASTContext creates these.
3745
3746 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3747 : FunctionType(FunctionNoProto, Result, Canonical,
3748 /*Dependent=*/false, /*InstantiationDependent=*/false,
3749 Result->isVariablyModifiedType(),
3750 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3751
3752public:
3753 // No additional state past what FunctionType provides.
3754
3755 bool isSugared() const { return false; }
3756 QualType desugar() const { return QualType(this, 0); }
3757
3758 void Profile(llvm::FoldingSetNodeID &ID) {
3759 Profile(ID, getReturnType(), getExtInfo());
3760 }
3761
3762 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3763 ExtInfo Info) {
3764 Info.Profile(ID);
3765 ID.AddPointer(ResultType.getAsOpaquePtr());
3766 }
3767
3768 static bool classof(const Type *T) {
3769 return T->getTypeClass() == FunctionNoProto;
3770 }
3771};
3772
3773/// Represents a prototype with parameter type info, e.g.
3774/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3775/// parameters, not as having a single void parameter. Such a type can have
3776/// an exception specification, but this specification is not part of the
3777/// canonical type. FunctionProtoType has several trailing objects, some of
3778/// which optional. For more information about the trailing objects see
3779/// the first comment inside FunctionProtoType.
3780class FunctionProtoType final
3781 : public FunctionType,
3782 public llvm::FoldingSetNode,
3783 private llvm::TrailingObjects<
3784 FunctionProtoType, QualType, SourceLocation,
3785 FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType,
3786 Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> {
3787 friend class ASTContext; // ASTContext creates these.
3788 friend TrailingObjects;
3789
3790 // FunctionProtoType is followed by several trailing objects, some of
3791 // which optional. They are in order:
3792 //
3793 // * An array of getNumParams() QualType holding the parameter types.
3794 // Always present. Note that for the vast majority of FunctionProtoType,
3795 // these will be the only trailing objects.
3796 //
3797 // * Optionally if the function is variadic, the SourceLocation of the
3798 // ellipsis.
3799 //
3800 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3801 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3802 // a single FunctionTypeExtraBitfields. Present if and only if
3803 // hasExtraBitfields() is true.
3804 //
3805 // * Optionally exactly one of:
3806 // * an array of getNumExceptions() ExceptionType,
3807 // * a single Expr *,
3808 // * a pair of FunctionDecl *,
3809 // * a single FunctionDecl *
3810 // used to store information about the various types of exception
3811 // specification. See getExceptionSpecSize for the details.
3812 //
3813 // * Optionally an array of getNumParams() ExtParameterInfo holding
3814 // an ExtParameterInfo for each of the parameters. Present if and
3815 // only if hasExtParameterInfos() is true.
3816 //
3817 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3818 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3819 // if hasExtQualifiers() is true.
3820 //
3821 // The optional FunctionTypeExtraBitfields has to be before the data
3822 // related to the exception specification since it contains the number
3823 // of exception types.
3824 //
3825 // We put the ExtParameterInfos last. If all were equal, it would make
3826 // more sense to put these before the exception specification, because
3827 // it's much easier to skip past them compared to the elaborate switch
3828 // required to skip the exception specification. However, all is not
3829 // equal; ExtParameterInfos are used to model very uncommon features,
3830 // and it's better not to burden the more common paths.
3831
3832public:
3833 /// Holds information about the various types of exception specification.
3834 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3835 /// used to group together the various bits of information about the
3836 /// exception specification.
3837 struct ExceptionSpecInfo {
3838 /// The kind of exception specification this is.
3839 ExceptionSpecificationType Type = EST_None;
3840
3841 /// Explicitly-specified list of exception types.
3842 ArrayRef<QualType> Exceptions;
3843
3844 /// Noexcept expression, if this is a computed noexcept specification.
3845 Expr *NoexceptExpr = nullptr;
3846
3847 /// The function whose exception specification this is, for
3848 /// EST_Unevaluated and EST_Uninstantiated.
3849 FunctionDecl *SourceDecl = nullptr;
3850
3851 /// The function template whose exception specification this is instantiated
3852 /// from, for EST_Uninstantiated.
3853 FunctionDecl *SourceTemplate = nullptr;
3854
3855 ExceptionSpecInfo() = default;
3856
3857 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3858 };
3859
3860 /// Extra information about a function prototype. ExtProtoInfo is not
3861 /// stored as such in FunctionProtoType but is used to group together
3862 /// the various bits of extra information about a function prototype.
3863 struct ExtProtoInfo {
3864 FunctionType::ExtInfo ExtInfo;
3865 bool Variadic : 1;
3866 bool HasTrailingReturn : 1;
3867 Qualifiers TypeQuals;
3868 RefQualifierKind RefQualifier = RQ_None;
3869 ExceptionSpecInfo ExceptionSpec;
3870 const ExtParameterInfo *ExtParameterInfos = nullptr;
3871 SourceLocation EllipsisLoc;
3872
3873 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3874
3875 ExtProtoInfo(CallingConv CC)
3876 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3877
3878 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3879 ExtProtoInfo Result(*this);
3880 Result.ExceptionSpec = ESI;
3881 return Result;
3882 }
3883 };
3884
3885private:
3886 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3887 return getNumParams();
3888 }
3889
3890 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
3891 return isVariadic();
3892 }
3893
3894 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3895 return hasExtraBitfields();
3896 }
3897
3898 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3899 return getExceptionSpecSize().NumExceptionType;
3900 }
3901
3902 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
3903 return getExceptionSpecSize().NumExprPtr;
3904 }
3905
3906 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
3907 return getExceptionSpecSize().NumFunctionDeclPtr;
3908 }
3909
3910 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
3911 return hasExtParameterInfos() ? getNumParams() : 0;
3912 }
3913
3914 /// Determine whether there are any argument types that
3915 /// contain an unexpanded parameter pack.
3916 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3917 unsigned numArgs) {
3918 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3919 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3920 return true;
3921
3922 return false;
3923 }
3924
3925 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3926 QualType canonical, const ExtProtoInfo &epi);
3927
3928 /// This struct is returned by getExceptionSpecSize and is used to
3929 /// translate an ExceptionSpecificationType to the number and kind
3930 /// of trailing objects related to the exception specification.
3931 struct ExceptionSpecSizeHolder {
3932 unsigned NumExceptionType;
3933 unsigned NumExprPtr;
3934 unsigned NumFunctionDeclPtr;
3935 };
3936
3937 /// Return the number and kind of trailing objects
3938 /// related to the exception specification.
3939 static ExceptionSpecSizeHolder
3940 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
3941 switch (EST) {
3942 case EST_None:
3943 case EST_DynamicNone:
3944 case EST_MSAny:
3945 case EST_BasicNoexcept:
3946 case EST_Unparsed:
3947 case EST_NoThrow:
3948 return {0, 0, 0};
3949
3950 case EST_Dynamic:
3951 return {NumExceptions, 0, 0};
3952
3953 case EST_DependentNoexcept:
3954 case EST_NoexceptFalse:
3955 case EST_NoexceptTrue:
3956 return {0, 1, 0};
3957
3958 case EST_Uninstantiated:
3959 return {0, 0, 2};
3960
3961 case EST_Unevaluated:
3962 return {0, 0, 1};
3963 }
3964 llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 3964)
;
3965 }
3966
3967 /// Return the number and kind of trailing objects
3968 /// related to the exception specification.
3969 ExceptionSpecSizeHolder getExceptionSpecSize() const {
3970 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
3971 }
3972
3973 /// Whether the trailing FunctionTypeExtraBitfields is present.
3974 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
3975 // If the exception spec type is EST_Dynamic then we have > 0 exception
3976 // types and the exact number is stored in FunctionTypeExtraBitfields.
3977 return EST == EST_Dynamic;
3978 }
3979
3980 /// Whether the trailing FunctionTypeExtraBitfields is present.
3981 bool hasExtraBitfields() const {
3982 return hasExtraBitfields(getExceptionSpecType());
3983 }
3984
3985 bool hasExtQualifiers() const {
3986 return FunctionTypeBits.HasExtQuals;
3987 }
3988
3989public:
3990 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
3991
3992 QualType getParamType(unsigned i) const {
3993 assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index")
? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 3993, __PRETTY_FUNCTION__))
;
3994 return param_type_begin()[i];
3995 }
3996
3997 ArrayRef<QualType> getParamTypes() const {
3998 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3999 }
4000
4001 ExtProtoInfo getExtProtoInfo() const {
4002 ExtProtoInfo EPI;
4003 EPI.ExtInfo = getExtInfo();
4004 EPI.Variadic = isVariadic();
4005 EPI.EllipsisLoc = getEllipsisLoc();
4006 EPI.HasTrailingReturn = hasTrailingReturn();
4007 EPI.ExceptionSpec = getExceptionSpecInfo();
4008 EPI.TypeQuals = getMethodQuals();
4009 EPI.RefQualifier = getRefQualifier();
4010 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
4011 return EPI;
4012 }
4013
4014 /// Get the kind of exception specification on this function.
4015 ExceptionSpecificationType getExceptionSpecType() const {
4016 return static_cast<ExceptionSpecificationType>(
4017 FunctionTypeBits.ExceptionSpecType);
4018 }
4019
4020 /// Return whether this function has any kind of exception spec.
4021 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
4022
4023 /// Return whether this function has a dynamic (throw) exception spec.
4024 bool hasDynamicExceptionSpec() const {
4025 return isDynamicExceptionSpec(getExceptionSpecType());
4026 }
4027
4028 /// Return whether this function has a noexcept exception spec.
4029 bool hasNoexceptExceptionSpec() const {
4030 return isNoexceptExceptionSpec(getExceptionSpecType());
4031 }
4032
4033 /// Return whether this function has a dependent exception spec.
4034 bool hasDependentExceptionSpec() const;
4035
4036 /// Return whether this function has an instantiation-dependent exception
4037 /// spec.
4038 bool hasInstantiationDependentExceptionSpec() const;
4039
4040 /// Return all the available information about this type's exception spec.
4041 ExceptionSpecInfo getExceptionSpecInfo() const {
4042 ExceptionSpecInfo Result;
4043 Result.Type = getExceptionSpecType();
4044 if (Result.Type == EST_Dynamic) {
4045 Result.Exceptions = exceptions();
4046 } else if (isComputedNoexcept(Result.Type)) {
4047 Result.NoexceptExpr = getNoexceptExpr();
4048 } else if (Result.Type == EST_Uninstantiated) {
4049 Result.SourceDecl = getExceptionSpecDecl();
4050 Result.SourceTemplate = getExceptionSpecTemplate();
4051 } else if (Result.Type == EST_Unevaluated) {
4052 Result.SourceDecl = getExceptionSpecDecl();
4053 }
4054 return Result;
4055 }
4056
4057 /// Return the number of types in the exception specification.
4058 unsigned getNumExceptions() const {
4059 return getExceptionSpecType() == EST_Dynamic
4060 ? getTrailingObjects<FunctionTypeExtraBitfields>()
4061 ->NumExceptionType
4062 : 0;
4063 }
4064
4065 /// Return the ith exception type, where 0 <= i < getNumExceptions().
4066 QualType getExceptionType(unsigned i) const {
4067 assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4067, __PRETTY_FUNCTION__))
;
4068 return exception_begin()[i];
4069 }
4070
4071 /// Return the expression inside noexcept(expression), or a null pointer
4072 /// if there is none (because the exception spec is not of this form).
4073 Expr *getNoexceptExpr() const {
4074 if (!isComputedNoexcept(getExceptionSpecType()))
4075 return nullptr;
4076 return *getTrailingObjects<Expr *>();
4077 }
4078
4079 /// If this function type has an exception specification which hasn't
4080 /// been determined yet (either because it has not been evaluated or because
4081 /// it has not been instantiated), this is the function whose exception
4082 /// specification is represented by this type.
4083 FunctionDecl *getExceptionSpecDecl() const {
4084 if (getExceptionSpecType() != EST_Uninstantiated &&
4085 getExceptionSpecType() != EST_Unevaluated)
4086 return nullptr;
4087 return getTrailingObjects<FunctionDecl *>()[0];
4088 }
4089
4090 /// If this function type has an uninstantiated exception
4091 /// specification, this is the function whose exception specification
4092 /// should be instantiated to find the exception specification for
4093 /// this type.
4094 FunctionDecl *getExceptionSpecTemplate() const {
4095 if (getExceptionSpecType() != EST_Uninstantiated)
4096 return nullptr;
4097 return getTrailingObjects<FunctionDecl *>()[1];
4098 }
4099
4100 /// Determine whether this function type has a non-throwing exception
4101 /// specification.
4102 CanThrowResult canThrow() const;
4103
4104 /// Determine whether this function type has a non-throwing exception
4105 /// specification. If this depends on template arguments, returns
4106 /// \c ResultIfDependent.
4107 bool isNothrow(bool ResultIfDependent = false) const {
4108 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4109 }
4110
4111 /// Whether this function prototype is variadic.
4112 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4113
4114 SourceLocation getEllipsisLoc() const {
4115 return isVariadic() ? *getTrailingObjects<SourceLocation>()
4116 : SourceLocation();
4117 }
4118
4119 /// Determines whether this function prototype contains a
4120 /// parameter pack at the end.
4121 ///
4122 /// A function template whose last parameter is a parameter pack can be
4123 /// called with an arbitrary number of arguments, much like a variadic
4124 /// function.
4125 bool isTemplateVariadic() const;
4126
4127 /// Whether this function prototype has a trailing return type.
4128 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4129
4130 Qualifiers getMethodQuals() const {
4131 if (hasExtQualifiers())
4132 return *getTrailingObjects<Qualifiers>();
4133 else
4134 return getFastTypeQuals();
4135 }
4136
4137 /// Retrieve the ref-qualifier associated with this function type.
4138 RefQualifierKind getRefQualifier() const {
4139 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4140 }
4141
4142 using param_type_iterator = const QualType *;
4143 using param_type_range = llvm::iterator_range<param_type_iterator>;
4144
4145 param_type_range param_types() const {
4146 return param_type_range(param_type_begin(), param_type_end());
4147 }
4148
4149 param_type_iterator param_type_begin() const {
4150 return getTrailingObjects<QualType>();
4151 }
4152
4153 param_type_iterator param_type_end() const {
4154 return param_type_begin() + getNumParams();
4155 }
4156
4157 using exception_iterator = const QualType *;
4158
4159 ArrayRef<QualType> exceptions() const {
4160 return llvm::makeArrayRef(exception_begin(), exception_end());
4161 }
4162
4163 exception_iterator exception_begin() const {
4164 return reinterpret_cast<exception_iterator>(
4165 getTrailingObjects<ExceptionType>());
4166 }
4167
4168 exception_iterator exception_end() const {
4169 return exception_begin() + getNumExceptions();
4170 }
4171
4172 /// Is there any interesting extra information for any of the parameters
4173 /// of this function type?
4174 bool hasExtParameterInfos() const {
4175 return FunctionTypeBits.HasExtParameterInfos;
4176 }
4177
4178 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4179 assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail
("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4179, __PRETTY_FUNCTION__))
;
4180 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4181 getNumParams());
4182 }
4183
4184 /// Return a pointer to the beginning of the array of extra parameter
4185 /// information, if present, or else null if none of the parameters
4186 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4187 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4188 if (!hasExtParameterInfos())
4189 return nullptr;
4190 return getTrailingObjects<ExtParameterInfo>();
4191 }
4192
4193 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4194 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4194, __PRETTY_FUNCTION__))
;
4195 if (hasExtParameterInfos())
4196 return getTrailingObjects<ExtParameterInfo>()[I];
4197 return ExtParameterInfo();
4198 }
4199
4200 ParameterABI getParameterABI(unsigned I) const {
4201 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4201, __PRETTY_FUNCTION__))
;
4202 if (hasExtParameterInfos())
4203 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4204 return ParameterABI::Ordinary;
4205 }
4206
4207 bool isParamConsumed(unsigned I) const {
4208 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4208, __PRETTY_FUNCTION__))
;
4209 if (hasExtParameterInfos())
4210 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4211 return false;
4212 }
4213
4214 bool isSugared() const { return false; }
4215 QualType desugar() const { return QualType(this, 0); }
4216
4217 void printExceptionSpecification(raw_ostream &OS,
4218 const PrintingPolicy &Policy) const;
4219
4220 static bool classof(const Type *T) {
4221 return T->getTypeClass() == FunctionProto;
4222 }
4223
4224 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4225 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4226 param_type_iterator ArgTys, unsigned NumArgs,
4227 const ExtProtoInfo &EPI, const ASTContext &Context,
4228 bool Canonical);
4229};
4230
4231/// Represents the dependent type named by a dependently-scoped
4232/// typename using declaration, e.g.
4233/// using typename Base<T>::foo;
4234///
4235/// Template instantiation turns these into the underlying type.
4236class UnresolvedUsingType : public Type {
4237 friend class ASTContext; // ASTContext creates these.
4238
4239 UnresolvedUsingTypenameDecl *Decl;
4240
4241 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4242 : Type(UnresolvedUsing, QualType(), true, true, false,
4243 /*ContainsUnexpandedParameterPack=*/false),
4244 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
4245
4246public:
4247 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4248
4249 bool isSugared() const { return false; }
4250 QualType desugar() const { return QualType(this, 0); }
4251
4252 static bool classof(const Type *T) {
4253 return T->getTypeClass() == UnresolvedUsing;
4254 }
4255
4256 void Profile(llvm::FoldingSetNodeID &ID) {
4257 return Profile(ID, Decl);
4258 }
4259
4260 static void Profile(llvm::FoldingSetNodeID &ID,
4261 UnresolvedUsingTypenameDecl *D) {
4262 ID.AddPointer(D);
4263 }
4264};
4265
4266class TypedefType : public Type {
4267 TypedefNameDecl *Decl;
4268
4269protected:
4270 friend class ASTContext; // ASTContext creates these.
4271
4272 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
4273 : Type(tc, can, can->isDependentType(),
4274 can->isInstantiationDependentType(),
4275 can->isVariablyModifiedType(),
4276 /*ContainsUnexpandedParameterPack=*/false),
4277 Decl(const_cast<TypedefNameDecl*>(D)) {
4278 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4278, __PRETTY_FUNCTION__))
;
4279 }
4280
4281public:
4282 TypedefNameDecl *getDecl() const { return Decl; }
4283
4284 bool isSugared() const { return true; }
4285 QualType desugar() const;
4286
4287 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4288};
4289
4290/// Sugar type that represents a type that was qualified by a qualifier written
4291/// as a macro invocation.
4292class MacroQualifiedType : public Type {
4293 friend class ASTContext; // ASTContext creates these.
4294
4295 QualType UnderlyingTy;
4296 const IdentifierInfo *MacroII;
4297
4298 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4299 const IdentifierInfo *MacroII)
4300 : Type(MacroQualified, CanonTy, UnderlyingTy->isDependentType(),
4301 UnderlyingTy->isInstantiationDependentType(),
4302 UnderlyingTy->isVariablyModifiedType(),
4303 UnderlyingTy->containsUnexpandedParameterPack()),
4304 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4305 assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4306, __PRETTY_FUNCTION__))
4306 "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4306, __PRETTY_FUNCTION__))
;
4307 }
4308
4309public:
4310 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4311 QualType getUnderlyingType() const { return UnderlyingTy; }
4312
4313 /// Return this attributed type's modified type with no qualifiers attached to
4314 /// it.
4315 QualType getModifiedType() const;
4316
4317 bool isSugared() const { return true; }
4318 QualType desugar() const;
4319
4320 static bool classof(const Type *T) {
4321 return T->getTypeClass() == MacroQualified;
4322 }
4323};
4324
4325/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4326class TypeOfExprType : public Type {
4327 Expr *TOExpr;
4328
4329protected:
4330 friend class ASTContext; // ASTContext creates these.
4331
4332 TypeOfExprType(Expr *E, QualType can = QualType());
4333
4334public:
4335 Expr *getUnderlyingExpr() const { return TOExpr; }
4336
4337 /// Remove a single level of sugar.
4338 QualType desugar() const;
4339
4340 /// Returns whether this type directly provides sugar.
4341 bool isSugared() const;
4342
4343 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4344};
4345
4346/// Internal representation of canonical, dependent
4347/// `typeof(expr)` types.
4348///
4349/// This class is used internally by the ASTContext to manage
4350/// canonical, dependent types, only. Clients will only see instances
4351/// of this class via TypeOfExprType nodes.
4352class DependentTypeOfExprType
4353 : public TypeOfExprType, public llvm::FoldingSetNode {
4354 const ASTContext &Context;
4355
4356public:
4357 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4358 : TypeOfExprType(E), Context(Context) {}
4359
4360 void Profile(llvm::FoldingSetNodeID &ID) {
4361 Profile(ID, Context, getUnderlyingExpr());
4362 }
4363
4364 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4365 Expr *E);
4366};
4367
4368/// Represents `typeof(type)`, a GCC extension.
4369class TypeOfType : public Type {
4370 friend class ASTContext; // ASTContext creates these.
4371
4372 QualType TOType;
4373
4374 TypeOfType(QualType T, QualType can)
4375 : Type(TypeOf, can, T->isDependentType(),
4376 T->isInstantiationDependentType(),
4377 T->isVariablyModifiedType(),
4378 T->containsUnexpandedParameterPack()),
4379 TOType(T) {
4380 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4380, __PRETTY_FUNCTION__))
;
4381 }
4382
4383public:
4384 QualType getUnderlyingType() const { return TOType; }
4385
4386 /// Remove a single level of sugar.
4387 QualType desugar() const { return getUnderlyingType(); }
4388
4389 /// Returns whether this type directly provides sugar.
4390 bool isSugared() const { return true; }
4391
4392 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4393};
4394
4395/// Represents the type `decltype(expr)` (C++11).
4396class DecltypeType : public Type {
4397 Expr *E;
4398 QualType UnderlyingType;
4399
4400protected:
4401 friend class ASTContext; // ASTContext creates these.
4402
4403 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4404
4405public:
4406 Expr *getUnderlyingExpr() const { return E; }
4407 QualType getUnderlyingType() const { return UnderlyingType; }
4408
4409 /// Remove a single level of sugar.
4410 QualType desugar() const;
4411
4412 /// Returns whether this type directly provides sugar.
4413 bool isSugared() const;
4414
4415 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4416};
4417
4418/// Internal representation of canonical, dependent
4419/// decltype(expr) types.
4420///
4421/// This class is used internally by the ASTContext to manage
4422/// canonical, dependent types, only. Clients will only see instances
4423/// of this class via DecltypeType nodes.
4424class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4425 const ASTContext &Context;
4426
4427public:
4428 DependentDecltypeType(const ASTContext &Context, Expr *E);
4429
4430 void Profile(llvm::FoldingSetNodeID &ID) {
4431 Profile(ID, Context, getUnderlyingExpr());
4432 }
4433
4434 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4435 Expr *E);
4436};
4437
4438/// A unary type transform, which is a type constructed from another.
4439class UnaryTransformType : public Type {
4440public:
4441 enum UTTKind {
4442 EnumUnderlyingType
4443 };
4444
4445private:
4446 /// The untransformed type.
4447 QualType BaseType;
4448
4449 /// The transformed type if not dependent, otherwise the same as BaseType.
4450 QualType UnderlyingType;
4451
4452 UTTKind UKind;
4453
4454protected:
4455 friend class ASTContext;
4456
4457 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4458 QualType CanonicalTy);
4459
4460public:
4461 bool isSugared() const { return !isDependentType(); }
4462 QualType desugar() const { return UnderlyingType; }
4463
4464 QualType getUnderlyingType() const { return UnderlyingType; }
4465 QualType getBaseType() const { return BaseType; }
4466
4467 UTTKind getUTTKind() const { return UKind; }
4468
4469 static bool classof(const Type *T) {
4470 return T->getTypeClass() == UnaryTransform;
4471 }
4472};
4473
4474/// Internal representation of canonical, dependent
4475/// __underlying_type(type) types.
4476///
4477/// This class is used internally by the ASTContext to manage
4478/// canonical, dependent types, only. Clients will only see instances
4479/// of this class via UnaryTransformType nodes.
4480class DependentUnaryTransformType : public UnaryTransformType,
4481 public llvm::FoldingSetNode {
4482public:
4483 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4484 UTTKind UKind);
4485
4486 void Profile(llvm::FoldingSetNodeID &ID) {
4487 Profile(ID, getBaseType(), getUTTKind());
4488 }
4489
4490 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4491 UTTKind UKind) {
4492 ID.AddPointer(BaseType.getAsOpaquePtr());
4493 ID.AddInteger((unsigned)UKind);
4494 }
4495};
4496
4497class TagType : public Type {
4498 friend class ASTReader;
4499 template <class T> friend class serialization::AbstractTypeReader;
4500
4501 /// Stores the TagDecl associated with this type. The decl may point to any
4502 /// TagDecl that declares the entity.
4503 TagDecl *decl;
4504
4505protected:
4506 TagType(TypeClass TC, const TagDecl *D, QualType can);
4507
4508public:
4509 TagDecl *getDecl() const;
4510
4511 /// Determines whether this type is in the process of being defined.
4512 bool isBeingDefined() const;
4513
4514 static bool classof(const Type *T) {
4515 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4516 }
4517};
4518
4519/// A helper class that allows the use of isa/cast/dyncast
4520/// to detect TagType objects of structs/unions/classes.
4521class RecordType : public TagType {
4522protected:
4523 friend class ASTContext; // ASTContext creates these.
4524
4525 explicit RecordType(const RecordDecl *D)
4526 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4527 explicit RecordType(TypeClass TC, RecordDecl *D)
4528 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4529
4530public:
4531 RecordDecl *getDecl() const {
4532 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4533 }
4534
4535 /// Recursively check all fields in the record for const-ness. If any field
4536 /// is declared const, return true. Otherwise, return false.
4537 bool hasConstFields() const;
4538
4539 bool isSugared() const { return false; }
4540 QualType desugar() const { return QualType(this, 0); }
4541
4542 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4543};
4544
4545/// A helper class that allows the use of isa/cast/dyncast
4546/// to detect TagType objects of enums.
4547class EnumType : public TagType {
4548 friend class ASTContext; // ASTContext creates these.
4549
4550 explicit EnumType(const EnumDecl *D)
4551 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4552
4553public:
4554 EnumDecl *getDecl() const {
4555 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4556 }
4557
4558 bool isSugared() const { return false; }
4559 QualType desugar() const { return QualType(this, 0); }
4560
4561 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4562};
4563
4564/// An attributed type is a type to which a type attribute has been applied.
4565///
4566/// The "modified type" is the fully-sugared type to which the attributed
4567/// type was applied; generally it is not canonically equivalent to the
4568/// attributed type. The "equivalent type" is the minimally-desugared type
4569/// which the type is canonically equivalent to.
4570///
4571/// For example, in the following attributed type:
4572/// int32_t __attribute__((vector_size(16)))
4573/// - the modified type is the TypedefType for int32_t
4574/// - the equivalent type is VectorType(16, int32_t)
4575/// - the canonical type is VectorType(16, int)
4576class AttributedType : public Type, public llvm::FoldingSetNode {
4577public:
4578 using Kind = attr::Kind;
4579
4580private:
4581 friend class ASTContext; // ASTContext creates these
4582
4583 QualType ModifiedType;
4584 QualType EquivalentType;
4585
4586 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4587 QualType equivalent)
4588 : Type(Attributed, canon, equivalent->isDependentType(),
4589 equivalent->isInstantiationDependentType(),
4590 equivalent->isVariablyModifiedType(),
4591 equivalent->containsUnexpandedParameterPack()),
4592 ModifiedType(modified), EquivalentType(equivalent) {
4593 AttributedTypeBits.AttrKind = attrKind;
4594 }
4595
4596public:
4597 Kind getAttrKind() const {
4598 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4599 }
4600
4601 QualType getModifiedType() const { return ModifiedType; }
4602 QualType getEquivalentType() const { return EquivalentType; }
4603
4604 bool isSugared() const { return true; }
4605 QualType desugar() const { return getEquivalentType(); }
4606
4607 /// Does this attribute behave like a type qualifier?
4608 ///
4609 /// A type qualifier adjusts a type to provide specialized rules for
4610 /// a specific object, like the standard const and volatile qualifiers.
4611 /// This includes attributes controlling things like nullability,
4612 /// address spaces, and ARC ownership. The value of the object is still
4613 /// largely described by the modified type.
4614 ///
4615 /// In contrast, many type attributes "rewrite" their modified type to
4616 /// produce a fundamentally different type, not necessarily related in any
4617 /// formalizable way to the original type. For example, calling convention
4618 /// and vector attributes are not simple type qualifiers.
4619 ///
4620 /// Type qualifiers are often, but not always, reflected in the canonical
4621 /// type.
4622 bool isQualifier() const;
4623
4624 bool isMSTypeSpec() const;
4625
4626 bool isCallingConv() const;
4627
4628 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4629
4630 /// Retrieve the attribute kind corresponding to the given
4631 /// nullability kind.
4632 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4633 switch (kind) {
4634 case NullabilityKind::NonNull:
4635 return attr::TypeNonNull;
4636
4637 case NullabilityKind::Nullable:
4638 return attr::TypeNullable;
4639
4640 case NullabilityKind::Unspecified:
4641 return attr::TypeNullUnspecified;
4642 }
4643 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4643)
;
4644 }
4645
4646 /// Strip off the top-level nullability annotation on the given
4647 /// type, if it's there.
4648 ///
4649 /// \param T The type to strip. If the type is exactly an
4650 /// AttributedType specifying nullability (without looking through
4651 /// type sugar), the nullability is returned and this type changed
4652 /// to the underlying modified type.
4653 ///
4654 /// \returns the top-level nullability, if present.
4655 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4656
4657 void Profile(llvm::FoldingSetNodeID &ID) {
4658 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4659 }
4660
4661 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4662 QualType modified, QualType equivalent) {
4663 ID.AddInteger(attrKind);
4664 ID.AddPointer(modified.getAsOpaquePtr());
4665 ID.AddPointer(equivalent.getAsOpaquePtr());
4666 }
4667
4668 static bool classof(const Type *T) {
4669 return T->getTypeClass() == Attributed;
4670 }
4671};
4672
4673class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4674 friend class ASTContext; // ASTContext creates these
4675
4676 // Helper data collector for canonical types.
4677 struct CanonicalTTPTInfo {
4678 unsigned Depth : 15;
4679 unsigned ParameterPack : 1;
4680 unsigned Index : 16;
4681 };
4682
4683 union {
4684 // Info for the canonical type.
4685 CanonicalTTPTInfo CanTTPTInfo;
4686
4687 // Info for the non-canonical type.
4688 TemplateTypeParmDecl *TTPDecl;
4689 };
4690
4691 /// Build a non-canonical type.
4692 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4693 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4694 /*InstantiationDependent=*/true,
4695 /*VariablyModified=*/false,
4696 Canon->containsUnexpandedParameterPack()),
4697 TTPDecl(TTPDecl) {}
4698
4699 /// Build the canonical type.
4700 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4701 : Type(TemplateTypeParm, QualType(this, 0),
4702 /*Dependent=*/true,
4703 /*InstantiationDependent=*/true,
4704 /*VariablyModified=*/false, PP) {
4705 CanTTPTInfo.Depth = D;
4706 CanTTPTInfo.Index = I;
4707 CanTTPTInfo.ParameterPack = PP;
4708 }
4709
4710 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4711 QualType Can = getCanonicalTypeInternal();
4712 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4713 }
4714
4715public:
4716 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4717 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4718 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4719
4720 TemplateTypeParmDecl *getDecl() const {
4721 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4722 }
4723
4724 IdentifierInfo *getIdentifier() const;
4725
4726 bool isSugared() const { return false; }
4727 QualType desugar() const { return QualType(this, 0); }
4728
4729 void Profile(llvm::FoldingSetNodeID &ID) {
4730 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4731 }
4732
4733 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4734 unsigned Index, bool ParameterPack,
4735 TemplateTypeParmDecl *TTPDecl) {
4736 ID.AddInteger(Depth);
4737 ID.AddInteger(Index);
4738 ID.AddBoolean(ParameterPack);
4739 ID.AddPointer(TTPDecl);
4740 }
4741
4742 static bool classof(const Type *T) {
4743 return T->getTypeClass() == TemplateTypeParm;
4744 }
4745};
4746
4747/// Represents the result of substituting a type for a template
4748/// type parameter.
4749///
4750/// Within an instantiated template, all template type parameters have
4751/// been replaced with these. They are used solely to record that a
4752/// type was originally written as a template type parameter;
4753/// therefore they are never canonical.
4754class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4755 friend class ASTContext;
4756
4757 // The original type parameter.
4758 const TemplateTypeParmType *Replaced;
4759
4760 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4761 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4762 Canon->isInstantiationDependentType(),
4763 Canon->isVariablyModifiedType(),
4764 Canon->containsUnexpandedParameterPack()),
4765 Replaced(Param) {}
4766
4767public:
4768 /// Gets the template parameter that was substituted for.
4769 const TemplateTypeParmType *getReplacedParameter() const {
4770 return Replaced;
4771 }
4772
4773 /// Gets the type that was substituted for the template
4774 /// parameter.
4775 QualType getReplacementType() const {
4776 return getCanonicalTypeInternal();
4777 }
4778
4779 bool isSugared() const { return true; }
4780 QualType desugar() const { return getReplacementType(); }
4781
4782 void Profile(llvm::FoldingSetNodeID &ID) {
4783 Profile(ID, getReplacedParameter(), getReplacementType());
4784 }
4785
4786 static void Profile(llvm::FoldingSetNodeID &ID,
4787 const TemplateTypeParmType *Replaced,
4788 QualType Replacement) {
4789 ID.AddPointer(Replaced);
4790 ID.AddPointer(Replacement.getAsOpaquePtr());
4791 }
4792
4793 static bool classof(const Type *T) {
4794 return T->getTypeClass() == SubstTemplateTypeParm;
4795 }
4796};
4797
4798/// Represents the result of substituting a set of types for a template
4799/// type parameter pack.
4800///
4801/// When a pack expansion in the source code contains multiple parameter packs
4802/// and those parameter packs correspond to different levels of template
4803/// parameter lists, this type node is used to represent a template type
4804/// parameter pack from an outer level, which has already had its argument pack
4805/// substituted but that still lives within a pack expansion that itself
4806/// could not be instantiated. When actually performing a substitution into
4807/// that pack expansion (e.g., when all template parameters have corresponding
4808/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4809/// at the current pack substitution index.
4810class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4811 friend class ASTContext;
4812
4813 /// The original type parameter.
4814 const TemplateTypeParmType *Replaced;
4815
4816 /// A pointer to the set of template arguments that this
4817 /// parameter pack is instantiated with.
4818 const TemplateArgument *Arguments;
4819
4820 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4821 QualType Canon,
4822 const TemplateArgument &ArgPack);
4823
4824public:
4825 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4826
4827 /// Gets the template parameter that was substituted for.
4828 const TemplateTypeParmType *getReplacedParameter() const {
4829 return Replaced;
4830 }
4831
4832 unsigned getNumArgs() const {
4833 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4834 }
4835
4836 bool isSugared() const { return false; }
4837 QualType desugar() const { return QualType(this, 0); }
4838
4839 TemplateArgument getArgumentPack() const;
4840
4841 void Profile(llvm::FoldingSetNodeID &ID);
4842 static void Profile(llvm::FoldingSetNodeID &ID,
4843 const TemplateTypeParmType *Replaced,
4844 const TemplateArgument &ArgPack);
4845
4846 static bool classof(const Type *T) {
4847 return T->getTypeClass() == SubstTemplateTypeParmPack;
4848 }
4849};
4850
4851/// Common base class for placeholders for types that get replaced by
4852/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4853/// class template types, and constrained type names.
4854///
4855/// These types are usually a placeholder for a deduced type. However, before
4856/// the initializer is attached, or (usually) if the initializer is
4857/// type-dependent, there is no deduced type and the type is canonical. In
4858/// the latter case, it is also a dependent type.
4859class DeducedType : public Type {
4860protected:
4861 DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4862 bool IsInstantiationDependent, bool ContainsParameterPack)
4863 : Type(TC,
4864 // FIXME: Retain the sugared deduced type?
4865 DeducedAsType.isNull() ? QualType(this, 0)
4866 : DeducedAsType.getCanonicalType(),
4867 IsDependent, IsInstantiationDependent,
4868 /*VariablyModified=*/false, ContainsParameterPack) {
4869 if (!DeducedAsType.isNull()) {
4870 if (DeducedAsType->isDependentType())
4871 setDependent();
4872 if (DeducedAsType->isInstantiationDependentType())
4873 setInstantiationDependent();
4874 if (DeducedAsType->containsUnexpandedParameterPack())
4875 setContainsUnexpandedParameterPack();
4876 }
4877 }
4878
4879public:
4880 bool isSugared() const { return !isCanonicalUnqualified(); }
4881 QualType desugar() const { return getCanonicalTypeInternal(); }
4882
4883 /// Get the type deduced for this placeholder type, or null if it's
4884 /// either not been deduced or was deduced to a dependent type.
4885 QualType getDeducedType() const {
4886 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4887 }
4888 bool isDeduced() const {
4889 return !isCanonicalUnqualified() || isDependentType();
4890 }
4891
4892 static bool classof(const Type *T) {
4893 return T->getTypeClass() == Auto ||
4894 T->getTypeClass() == DeducedTemplateSpecialization;
4895 }
4896};
4897
4898/// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained
4899/// by a type-constraint.
4900class alignas(8) AutoType : public DeducedType, public llvm::FoldingSetNode {
4901 friend class ASTContext; // ASTContext creates these
4902
4903 ConceptDecl *TypeConstraintConcept;
4904
4905 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4906 bool IsDeducedAsDependent, bool IsDeducedAsPack, ConceptDecl *CD,
4907 ArrayRef<TemplateArgument> TypeConstraintArgs);
4908
4909 const TemplateArgument *getArgBuffer() const {
4910 return reinterpret_cast<const TemplateArgument*>(this+1);
4911 }
4912
4913 TemplateArgument *getArgBuffer() {
4914 return reinterpret_cast<TemplateArgument*>(this+1);
4915 }
4916
4917public:
4918 /// Retrieve the template arguments.
4919 const TemplateArgument *getArgs() const {
4920 return getArgBuffer();
4921 }
4922
4923 /// Retrieve the number of template arguments.
4924 unsigned getNumArgs() const {
4925 return AutoTypeBits.NumArgs;
4926 }
4927
4928 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4929
4930 ArrayRef<TemplateArgument> getTypeConstraintArguments() const {
4931 return {getArgs(), getNumArgs()};
4932 }
4933
4934 ConceptDecl *getTypeConstraintConcept() const {
4935 return TypeConstraintConcept;
4936 }
4937
4938 bool isConstrained() const {
4939 return TypeConstraintConcept != nullptr;
4940 }
4941
4942 bool isDecltypeAuto() const {
4943 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4944 }
4945
4946 AutoTypeKeyword getKeyword() const {
4947 return (AutoTypeKeyword)AutoTypeBits.Keyword;
4948 }
4949
4950 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4951 Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
4952 getTypeConstraintConcept(), getTypeConstraintArguments());
4953 }
4954
4955 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4956 QualType Deduced, AutoTypeKeyword Keyword,
4957 bool IsDependent, ConceptDecl *CD,
4958 ArrayRef<TemplateArgument> Arguments);
4959
4960 static bool classof(const Type *T) {
4961 return T->getTypeClass() == Auto;
4962 }
4963};
4964
4965/// Represents a C++17 deduced template specialization type.
4966class DeducedTemplateSpecializationType : public DeducedType,
4967 public llvm::FoldingSetNode {
4968 friend class ASTContext; // ASTContext creates these
4969
4970 /// The name of the template whose arguments will be deduced.
4971 TemplateName Template;
4972
4973 DeducedTemplateSpecializationType(TemplateName Template,
4974 QualType DeducedAsType,
4975 bool IsDeducedAsDependent)
4976 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4977 IsDeducedAsDependent || Template.isDependent(),
4978 IsDeducedAsDependent || Template.isInstantiationDependent(),
4979 Template.containsUnexpandedParameterPack()),
4980 Template(Template) {}
4981
4982public:
4983 /// Retrieve the name of the template that we are deducing.
4984 TemplateName getTemplateName() const { return Template;}
4985
4986 void Profile(llvm::FoldingSetNodeID &ID) {
4987 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4988 }
4989
4990 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4991 QualType Deduced, bool IsDependent) {
4992 Template.Profile(ID);
4993 ID.AddPointer(Deduced.getAsOpaquePtr());
4994 ID.AddBoolean(IsDependent);
4995 }
4996
4997 static bool classof(const Type *T) {
4998 return T->getTypeClass() == DeducedTemplateSpecialization;
4999 }
5000};
5001
5002/// Represents a type template specialization; the template
5003/// must be a class template, a type alias template, or a template
5004/// template parameter. A template which cannot be resolved to one of
5005/// these, e.g. because it is written with a dependent scope
5006/// specifier, is instead represented as a
5007/// @c DependentTemplateSpecializationType.
5008///
5009/// A non-dependent template specialization type is always "sugar",
5010/// typically for a \c RecordType. For example, a class template
5011/// specialization type of \c vector<int> will refer to a tag type for
5012/// the instantiation \c std::vector<int, std::allocator<int>>
5013///
5014/// Template specializations are dependent if either the template or
5015/// any of the template arguments are dependent, in which case the
5016/// type may also be canonical.
5017///
5018/// Instances of this type are allocated with a trailing array of
5019/// TemplateArguments, followed by a QualType representing the
5020/// non-canonical aliased type when the template is a type alias
5021/// template.
5022class alignas(8) TemplateSpecializationType
5023 : public Type,
5024 public llvm::FoldingSetNode {
5025 friend class ASTContext; // ASTContext creates these
5026
5027 /// The name of the template being specialized. This is
5028 /// either a TemplateName::Template (in which case it is a
5029 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
5030 /// TypeAliasTemplateDecl*), a
5031 /// TemplateName::SubstTemplateTemplateParmPack, or a
5032 /// TemplateName::SubstTemplateTemplateParm (in which case the
5033 /// replacement must, recursively, be one of these).
5034 TemplateName Template;
5035
5036 TemplateSpecializationType(TemplateName T,
5037 ArrayRef<TemplateArgument> Args,
5038 QualType Canon,
5039 QualType Aliased);
5040
5041public:
5042 /// Determine whether any of the given template arguments are dependent.
5043 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
5044 bool &InstantiationDependent);
5045
5046 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
5047 bool &InstantiationDependent);
5048
5049 /// True if this template specialization type matches a current
5050 /// instantiation in the context in which it is found.
5051 bool isCurrentInstantiation() const {
5052 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
5053 }
5054
5055 /// Determine if this template specialization type is for a type alias
5056 /// template that has been substituted.
5057 ///
5058 /// Nearly every template specialization type whose template is an alias
5059 /// template will be substituted. However, this is not the case when
5060 /// the specialization contains a pack expansion but the template alias
5061 /// does not have a corresponding parameter pack, e.g.,
5062 ///
5063 /// \code
5064 /// template<typename T, typename U, typename V> struct S;
5065 /// template<typename T, typename U> using A = S<T, int, U>;
5066 /// template<typename... Ts> struct X {
5067 /// typedef A<Ts...> type; // not a type alias
5068 /// };
5069 /// \endcode
5070 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
5071
5072 /// Get the aliased type, if this is a specialization of a type alias
5073 /// template.
5074 QualType getAliasedType() const {
5075 assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization"
) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5075, __PRETTY_FUNCTION__))
;
5076 return *reinterpret_cast<const QualType*>(end());
5077 }
5078
5079 using iterator = const TemplateArgument *;
5080
5081 iterator begin() const { return getArgs(); }
5082 iterator end() const; // defined inline in TemplateBase.h
5083
5084 /// Retrieve the name of the template that we are specializing.
5085 TemplateName getTemplateName() const { return Template; }
5086
5087 /// Retrieve the template arguments.
5088 const TemplateArgument *getArgs() const {
5089 return reinterpret_cast<const TemplateArgument *>(this + 1);
5090 }
5091
5092 /// Retrieve the number of template arguments.
5093 unsigned getNumArgs() const {
5094 return TemplateSpecializationTypeBits.NumArgs;
5095 }
5096
5097 /// Retrieve a specific template argument as a type.
5098 /// \pre \c isArgType(Arg)
5099 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5100
5101 ArrayRef<TemplateArgument> template_arguments() const {
5102 return {getArgs(), getNumArgs()};
5103 }
5104
5105 bool isSugared() const {
5106 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5107 }
5108
5109 QualType desugar() const {
5110 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5111 }
5112
5113 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5114 Profile(ID, Template, template_arguments(), Ctx);
5115 if (isTypeAlias())
5116 getAliasedType().Profile(ID);
5117 }
5118
5119 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5120 ArrayRef<TemplateArgument> Args,
5121 const ASTContext &Context);
5122
5123 static bool classof(const Type *T) {
5124 return T->getTypeClass() == TemplateSpecialization;
5125 }
5126};
5127
5128/// Print a template argument list, including the '<' and '>'
5129/// enclosing the template arguments.
5130void printTemplateArgumentList(raw_ostream &OS,
5131 ArrayRef<TemplateArgument> Args,
5132 const PrintingPolicy &Policy);
5133
5134void printTemplateArgumentList(raw_ostream &OS,
5135 ArrayRef<TemplateArgumentLoc> Args,
5136 const PrintingPolicy &Policy);
5137
5138void printTemplateArgumentList(raw_ostream &OS,
5139 const TemplateArgumentListInfo &Args,
5140 const PrintingPolicy &Policy);
5141
5142/// The injected class name of a C++ class template or class
5143/// template partial specialization. Used to record that a type was
5144/// spelled with a bare identifier rather than as a template-id; the
5145/// equivalent for non-templated classes is just RecordType.
5146///
5147/// Injected class name types are always dependent. Template
5148/// instantiation turns these into RecordTypes.
5149///
5150/// Injected class name types are always canonical. This works
5151/// because it is impossible to compare an injected class name type
5152/// with the corresponding non-injected template type, for the same
5153/// reason that it is impossible to directly compare template
5154/// parameters from different dependent contexts: injected class name
5155/// types can only occur within the scope of a particular templated
5156/// declaration, and within that scope every template specialization
5157/// will canonicalize to the injected class name (when appropriate
5158/// according to the rules of the language).
5159class InjectedClassNameType : public Type {
5160 friend class ASTContext; // ASTContext creates these.
5161 friend class ASTNodeImporter;
5162 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5163 // currently suitable for AST reading, too much
5164 // interdependencies.
5165 template <class T> friend class serialization::AbstractTypeReader;
5166
5167 CXXRecordDecl *Decl;
5168
5169 /// The template specialization which this type represents.
5170 /// For example, in
5171 /// template <class T> class A { ... };
5172 /// this is A<T>, whereas in
5173 /// template <class X, class Y> class A<B<X,Y> > { ... };
5174 /// this is A<B<X,Y> >.
5175 ///
5176 /// It is always unqualified, always a template specialization type,
5177 /// and always dependent.
5178 QualType InjectedType;
5179
5180 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5181 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
5182 /*InstantiationDependent=*/true,
5183 /*VariablyModified=*/false,
5184 /*ContainsUnexpandedParameterPack=*/false),
5185 Decl(D), InjectedType(TST) {
5186 assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast<
void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5186, __PRETTY_FUNCTION__))
;
5187 assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail
("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5187, __PRETTY_FUNCTION__))
;
5188 assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail
("TST->isDependentType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5188, __PRETTY_FUNCTION__))
;
5189 }
5190
5191public:
5192 QualType getInjectedSpecializationType() const { return InjectedType; }
5193
5194 const TemplateSpecializationType *getInjectedTST() const {
5195 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5196 }
5197
5198 TemplateName getTemplateName() const {
5199 return getInjectedTST()->getTemplateName();
5200 }
5201
5202 CXXRecordDecl *getDecl() const;
5203
5204 bool isSugared() const { return false; }
5205 QualType desugar() const { return QualType(this, 0); }
5206
5207 static bool classof(const Type *T) {
5208 return T->getTypeClass() == InjectedClassName;
5209 }
5210};
5211
5212/// The kind of a tag type.
5213enum TagTypeKind {
5214 /// The "struct" keyword.
5215 TTK_Struct,
5216
5217 /// The "__interface" keyword.
5218 TTK_Interface,
5219
5220 /// The "union" keyword.
5221 TTK_Union,
5222
5223 /// The "class" keyword.
5224 TTK_Class,
5225
5226 /// The "enum" keyword.
5227 TTK_Enum
5228};
5229
5230/// The elaboration keyword that precedes a qualified type name or
5231/// introduces an elaborated-type-specifier.
5232enum ElaboratedTypeKeyword {
5233 /// The "struct" keyword introduces the elaborated-type-specifier.
5234 ETK_Struct,
5235
5236 /// The "__interface" keyword introduces the elaborated-type-specifier.
5237 ETK_Interface,
5238
5239 /// The "union" keyword introduces the elaborated-type-specifier.
5240 ETK_Union,
5241
5242 /// The "class" keyword introduces the elaborated-type-specifier.
5243 ETK_Class,
5244
5245 /// The "enum" keyword introduces the elaborated-type-specifier.
5246 ETK_Enum,
5247
5248 /// The "typename" keyword precedes the qualified type name, e.g.,
5249 /// \c typename T::type.
5250 ETK_Typename,
5251
5252 /// No keyword precedes the qualified type name.
5253 ETK_None
5254};
5255
5256/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5257/// The keyword in stored in the free bits of the base class.
5258/// Also provides a few static helpers for converting and printing
5259/// elaborated type keyword and tag type kind enumerations.
5260class TypeWithKeyword : public Type {
5261protected:
5262 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5263 QualType Canonical, bool Dependent,
5264 bool InstantiationDependent, bool VariablyModified,
5265 bool ContainsUnexpandedParameterPack)
5266 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
5267 ContainsUnexpandedParameterPack) {
5268 TypeWithKeywordBits.Keyword = Keyword;
5269 }
5270
5271public:
5272 ElaboratedTypeKeyword getKeyword() const {
5273 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5274 }
5275
5276 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5277 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5278
5279 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5280 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5281 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5282
5283 /// Converts a TagTypeKind into an elaborated type keyword.
5284 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5285
5286 /// Converts an elaborated type keyword into a TagTypeKind.
5287 /// It is an error to provide an elaborated type keyword
5288 /// which *isn't* a tag kind here.
5289 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5290
5291 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5292
5293 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5294
5295 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5296 return getKeywordName(getKeywordForTagTypeKind(Kind));
5297 }
5298
5299 class CannotCastToThisType {};
5300 static CannotCastToThisType classof(const Type *);
5301};
5302
5303/// Represents a type that was referred to using an elaborated type
5304/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5305/// or both.
5306///
5307/// This type is used to keep track of a type name as written in the
5308/// source code, including tag keywords and any nested-name-specifiers.
5309/// The type itself is always "sugar", used to express what was written
5310/// in the source code but containing no additional semantic information.
5311class ElaboratedType final
5312 : public TypeWithKeyword,
5313 public llvm::FoldingSetNode,
5314 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5315 friend class ASTContext; // ASTContext creates these
5316 friend TrailingObjects;
5317
5318 /// The nested name specifier containing the qualifier.
5319 NestedNameSpecifier *NNS;
5320
5321 /// The type that this qualified name refers to.
5322 QualType NamedType;
5323
5324 /// The (re)declaration of this tag type owned by this occurrence is stored
5325 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5326 /// it, or obtain a null pointer if there is none.
5327
5328 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5329 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5330 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5331 NamedType->isDependentType(),
5332 NamedType->isInstantiationDependentType(),
5333 NamedType->isVariablyModifiedType(),
5334 NamedType->containsUnexpandedParameterPack()),
5335 NNS(NNS), NamedType(NamedType) {
5336 ElaboratedTypeBits.HasOwnedTagDecl = false;
5337 if (OwnedTagDecl) {
5338 ElaboratedTypeBits.HasOwnedTagDecl = true;
5339 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5340 }
5341 assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5343, __PRETTY_FUNCTION__))
5342 "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5343, __PRETTY_FUNCTION__))
5343 "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5343, __PRETTY_FUNCTION__))
;
5344 }
5345
5346public:
5347 /// Retrieve the qualification on this type.
5348 NestedNameSpecifier *getQualifier() const { return NNS; }
5349
5350 /// Retrieve the type named by the qualified-id.
5351 QualType getNamedType() const { return NamedType; }
5352
5353 /// Remove a single level of sugar.
5354 QualType desugar() const { return getNamedType(); }
5355
5356 /// Returns whether this type directly provides sugar.
5357 bool isSugared() const { return true; }
5358
5359 /// Return the (re)declaration of this type owned by this occurrence of this
5360 /// type, or nullptr if there is none.
5361 TagDecl *getOwnedTagDecl() const {
5362 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5363 : nullptr;
5364 }
5365
5366 void Profile(llvm::FoldingSetNodeID &ID) {
5367 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5368 }
5369
5370 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5371 NestedNameSpecifier *NNS, QualType NamedType,
5372 TagDecl *OwnedTagDecl) {
5373 ID.AddInteger(Keyword);
5374 ID.AddPointer(NNS);
5375 NamedType.Profile(ID);
5376 ID.AddPointer(OwnedTagDecl);
5377 }
5378
5379 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5380};
5381
5382/// Represents a qualified type name for which the type name is
5383/// dependent.
5384///
5385/// DependentNameType represents a class of dependent types that involve a
5386/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5387/// name of a type. The DependentNameType may start with a "typename" (for a
5388/// typename-specifier), "class", "struct", "union", or "enum" (for a
5389/// dependent elaborated-type-specifier), or nothing (in contexts where we
5390/// know that we must be referring to a type, e.g., in a base class specifier).
5391/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5392/// mode, this type is used with non-dependent names to delay name lookup until
5393/// instantiation.
5394class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5395 friend class ASTContext; // ASTContext creates these
5396
5397 /// The nested name specifier containing the qualifier.
5398 NestedNameSpecifier *NNS;
5399
5400 /// The type that this typename specifier refers to.
5401 const IdentifierInfo *Name;
5402
5403 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5404 const IdentifierInfo *Name, QualType CanonType)
5405 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
5406 /*InstantiationDependent=*/true,
5407 /*VariablyModified=*/false,
5408 NNS->containsUnexpandedParameterPack()),
5409 NNS(NNS), Name(Name) {}
5410
5411public:
5412 /// Retrieve the qualification on this type.
5413 NestedNameSpecifier *getQualifier() const { return NNS; }
5414
5415 /// Retrieve the type named by the typename specifier as an identifier.
5416 ///
5417 /// This routine will return a non-NULL identifier pointer when the
5418 /// form of the original typename was terminated by an identifier,
5419 /// e.g., "typename T::type".
5420 const IdentifierInfo *getIdentifier() const {
5421 return Name;
5422 }
5423
5424 bool isSugared() const { return false; }
5425 QualType desugar() const { return QualType(this, 0); }
5426
5427 void Profile(llvm::FoldingSetNodeID &ID) {
5428 Profile(ID, getKeyword(), NNS, Name);
5429 }
5430
5431 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5432 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5433 ID.AddInteger(Keyword);
5434 ID.AddPointer(NNS);
5435 ID.AddPointer(Name);
5436 }
5437
5438 static bool classof(const Type *T) {
5439 return T->getTypeClass() == DependentName;
5440 }
5441};
5442
5443/// Represents a template specialization type whose template cannot be
5444/// resolved, e.g.
5445/// A<T>::template B<T>
5446class alignas(8) DependentTemplateSpecializationType
5447 : public TypeWithKeyword,
5448 public llvm::FoldingSetNode {
5449 friend class ASTContext; // ASTContext creates these
5450
5451 /// The nested name specifier containing the qualifier.
5452 NestedNameSpecifier *NNS;
5453
5454 /// The identifier of the template.
5455 const IdentifierInfo *Name;
5456
5457 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5458 NestedNameSpecifier *NNS,
5459 const IdentifierInfo *Name,
5460 ArrayRef<TemplateArgument> Args,
5461 QualType Canon);
5462
5463 const TemplateArgument *getArgBuffer() const {
5464 return reinterpret_cast<const TemplateArgument*>(this+1);
5465 }
5466
5467 TemplateArgument *getArgBuffer() {
5468 return reinterpret_cast<TemplateArgument*>(this+1);
5469 }
5470
5471public:
5472 NestedNameSpecifier *getQualifier() const { return NNS; }
5473 const IdentifierInfo *getIdentifier() const { return Name; }
5474
5475 /// Retrieve the template arguments.
5476 const TemplateArgument *getArgs() const {
5477 return getArgBuffer();
5478 }
5479
5480 /// Retrieve the number of template arguments.
5481 unsigned getNumArgs() const {
5482 return DependentTemplateSpecializationTypeBits.NumArgs;
5483 }
5484
5485 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5486
5487 ArrayRef<TemplateArgument> template_arguments() const {
5488 return {getArgs(), getNumArgs()};
5489 }
5490
5491 using iterator = const TemplateArgument *;
5492
5493 iterator begin() const { return getArgs(); }
5494 iterator end() const; // inline in TemplateBase.h
5495
5496 bool isSugared() const { return false; }
5497 QualType desugar() const { return QualType(this, 0); }
5498
5499 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5500 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5501 }
5502
5503 static void Profile(llvm::FoldingSetNodeID &ID,
5504 const ASTContext &Context,
5505 ElaboratedTypeKeyword Keyword,
5506 NestedNameSpecifier *Qualifier,
5507 const IdentifierInfo *Name,
5508 ArrayRef<TemplateArgument> Args);
5509
5510 static bool classof(const Type *T) {
5511 return T->getTypeClass() == DependentTemplateSpecialization;
5512 }
5513};
5514
5515/// Represents a pack expansion of types.
5516///
5517/// Pack expansions are part of C++11 variadic templates. A pack
5518/// expansion contains a pattern, which itself contains one or more
5519/// "unexpanded" parameter packs. When instantiated, a pack expansion
5520/// produces a series of types, each instantiated from the pattern of
5521/// the expansion, where the Ith instantiation of the pattern uses the
5522/// Ith arguments bound to each of the unexpanded parameter packs. The
5523/// pack expansion is considered to "expand" these unexpanded
5524/// parameter packs.
5525///
5526/// \code
5527/// template<typename ...Types> struct tuple;
5528///
5529/// template<typename ...Types>
5530/// struct tuple_of_references {
5531/// typedef tuple<Types&...> type;
5532/// };
5533/// \endcode
5534///
5535/// Here, the pack expansion \c Types&... is represented via a
5536/// PackExpansionType whose pattern is Types&.
5537class PackExpansionType : public Type, public llvm::FoldingSetNode {
5538 friend class ASTContext; // ASTContext creates these
5539
5540 /// The pattern of the pack expansion.
5541 QualType Pattern;
5542
5543 PackExpansionType(QualType Pattern, QualType Canon,
5544 Optional<unsigned> NumExpansions)
5545 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
5546 /*InstantiationDependent=*/true,
5547 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
5548 /*ContainsUnexpandedParameterPack=*/false),
5549 Pattern(Pattern) {
5550 PackExpansionTypeBits.NumExpansions =
5551 NumExpansions ? *NumExpansions + 1 : 0;
5552 }
5553
5554public:
5555 /// Retrieve the pattern of this pack expansion, which is the
5556 /// type that will be repeatedly instantiated when instantiating the
5557 /// pack expansion itself.
5558 QualType getPattern() const { return Pattern; }
5559
5560 /// Retrieve the number of expansions that this pack expansion will
5561 /// generate, if known.
5562 Optional<unsigned> getNumExpansions() const {
5563 if (PackExpansionTypeBits.NumExpansions)
5564 return PackExpansionTypeBits.NumExpansions - 1;
5565 return None;
5566 }
5567
5568 bool isSugared() const { return !Pattern->isDependentType(); }
5569 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
5570
5571 void Profile(llvm::FoldingSetNodeID &ID) {
5572 Profile(ID, getPattern(), getNumExpansions());
5573 }
5574
5575 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5576 Optional<unsigned> NumExpansions) {
5577 ID.AddPointer(Pattern.getAsOpaquePtr());
5578 ID.AddBoolean(NumExpansions.hasValue());
5579 if (NumExpansions)
5580 ID.AddInteger(*NumExpansions);
5581 }
5582
5583 static bool classof(const Type *T) {
5584 return T->getTypeClass() == PackExpansion;
5585 }
5586};
5587
5588/// This class wraps the list of protocol qualifiers. For types that can
5589/// take ObjC protocol qualifers, they can subclass this class.
5590template <class T>
5591class ObjCProtocolQualifiers {
5592protected:
5593 ObjCProtocolQualifiers() = default;
5594
5595 ObjCProtocolDecl * const *getProtocolStorage() const {
5596 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5597 }
5598
5599 ObjCProtocolDecl **getProtocolStorage() {
5600 return static_cast<T*>(this)->getProtocolStorageImpl();
5601 }
5602
5603 void setNumProtocols(unsigned N) {
5604 static_cast<T*>(this)->setNumProtocolsImpl(N);
5605 }
5606
5607 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5608 setNumProtocols(protocols.size());
5609 assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5610, __PRETTY_FUNCTION__))
5610 "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5610, __PRETTY_FUNCTION__))
;
5611 if (!protocols.empty())
5612 memcpy(getProtocolStorage(), protocols.data(),
5613 protocols.size() * sizeof(ObjCProtocolDecl*));
5614 }
5615
5616public:
5617 using qual_iterator = ObjCProtocolDecl * const *;
5618 using qual_range = llvm::iterator_range<qual_iterator>;
5619
5620 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5621 qual_iterator qual_begin() const { return getProtocolStorage(); }
5622 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5623
5624 bool qual_empty() const { return getNumProtocols() == 0; }
5625
5626 /// Return the number of qualifying protocols in this type, or 0 if
5627 /// there are none.
5628 unsigned getNumProtocols() const {
5629 return static_cast<const T*>(this)->getNumProtocolsImpl();
5630 }
5631
5632 /// Fetch a protocol by index.
5633 ObjCProtocolDecl *getProtocol(unsigned I) const {
5634 assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access"
) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5634, __PRETTY_FUNCTION__))
;
5635 return qual_begin()[I];
5636 }
5637
5638 /// Retrieve all of the protocol qualifiers.
5639 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5640 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5641 }
5642};
5643
5644/// Represents a type parameter type in Objective C. It can take
5645/// a list of protocols.
5646class ObjCTypeParamType : public Type,
5647 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5648 public llvm::FoldingSetNode {
5649 friend class ASTContext;
5650 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5651
5652 /// The number of protocols stored on this type.
5653 unsigned NumProtocols : 6;
5654
5655 ObjCTypeParamDecl *OTPDecl;
5656
5657 /// The protocols are stored after the ObjCTypeParamType node. In the
5658 /// canonical type, the list of protocols are sorted alphabetically
5659 /// and uniqued.
5660 ObjCProtocolDecl **getProtocolStorageImpl();
5661
5662 /// Return the number of qualifying protocols in this interface type,
5663 /// or 0 if there are none.
5664 unsigned getNumProtocolsImpl() const {
5665 return NumProtocols;
5666 }
5667
5668 void setNumProtocolsImpl(unsigned N) {
5669 NumProtocols = N;
5670 }
5671
5672 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5673 QualType can,
5674 ArrayRef<ObjCProtocolDecl *> protocols);
5675
5676public:
5677 bool isSugared() const { return true; }
5678 QualType desugar() const { return getCanonicalTypeInternal(); }
5679
5680 static bool classof(const Type *T) {
5681 return T->getTypeClass() == ObjCTypeParam;
5682 }
5683
5684 void Profile(llvm::FoldingSetNodeID &ID);
5685 static void Profile(llvm::FoldingSetNodeID &ID,
5686 const ObjCTypeParamDecl *OTPDecl,
5687 ArrayRef<ObjCProtocolDecl *> protocols);
5688
5689 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5690};
5691
5692/// Represents a class type in Objective C.
5693///
5694/// Every Objective C type is a combination of a base type, a set of
5695/// type arguments (optional, for parameterized classes) and a list of
5696/// protocols.
5697///
5698/// Given the following declarations:
5699/// \code
5700/// \@class C<T>;
5701/// \@protocol P;
5702/// \endcode
5703///
5704/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5705/// with base C and no protocols.
5706///
5707/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5708/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5709/// protocol list.
5710/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5711/// and protocol list [P].
5712///
5713/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5714/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5715/// and no protocols.
5716///
5717/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5718/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5719/// this should get its own sugar class to better represent the source.
5720class ObjCObjectType : public Type,
5721 public ObjCProtocolQualifiers<ObjCObjectType> {
5722 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5723
5724 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5725 // after the ObjCObjectPointerType node.
5726 // ObjCObjectType.NumProtocols - the number of protocols stored
5727 // after the type arguments of ObjCObjectPointerType node.
5728 //
5729 // These protocols are those written directly on the type. If
5730 // protocol qualifiers ever become additive, the iterators will need
5731 // to get kindof complicated.
5732 //
5733 // In the canonical object type, these are sorted alphabetically
5734 // and uniqued.
5735
5736 /// Either a BuiltinType or an InterfaceType or sugar for either.
5737 QualType BaseType;
5738
5739 /// Cached superclass type.
5740 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5741 CachedSuperClassType;
5742
5743 QualType *getTypeArgStorage();
5744 const QualType *getTypeArgStorage() const {
5745 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5746 }
5747
5748 ObjCProtocolDecl **getProtocolStorageImpl();
5749 /// Return the number of qualifying protocols in this interface type,
5750 /// or 0 if there are none.
5751 unsigned getNumProtocolsImpl() const {
5752 return ObjCObjectTypeBits.NumProtocols;
5753 }
5754 void setNumProtocolsImpl(unsigned N) {
5755 ObjCObjectTypeBits.NumProtocols = N;
5756 }
5757
5758protected:
5759 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5760
5761 ObjCObjectType(QualType Canonical, QualType Base,
5762 ArrayRef<QualType> typeArgs,
5763 ArrayRef<ObjCProtocolDecl *> protocols,
5764 bool isKindOf);
5765
5766 ObjCObjectType(enum Nonce_ObjCInterface)
5767 : Type(ObjCInterface, QualType(), false, false, false, false),
5768 BaseType(QualType(this_(), 0)) {
5769 ObjCObjectTypeBits.NumProtocols = 0;
5770 ObjCObjectTypeBits.NumTypeArgs = 0;
5771 ObjCObjectTypeBits.IsKindOf = 0;
5772 }
5773
5774 void computeSuperClassTypeSlow() const;
5775
5776public:
5777 /// Gets the base type of this object type. This is always (possibly
5778 /// sugar for) one of:
5779 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5780 /// user, which is a typedef for an ObjCObjectPointerType)
5781 /// - the 'Class' builtin type (same caveat)
5782 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5783 QualType getBaseType() const { return BaseType; }
5784
5785 bool isObjCId() const {
5786 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5787 }
5788
5789 bool isObjCClass() const {
5790 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5791 }
5792
5793 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5794 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5795 bool isObjCUnqualifiedIdOrClass() const {
5796 if (!qual_empty()) return false;
5797 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5798 return T->getKind() == BuiltinType::ObjCId ||
5799 T->getKind() == BuiltinType::ObjCClass;
5800 return false;
5801 }
5802 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5803 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5804
5805 /// Gets the interface declaration for this object type, if the base type
5806 /// really is an interface.
5807 ObjCInterfaceDecl *getInterface() const;
5808
5809 /// Determine whether this object type is "specialized", meaning
5810 /// that it has type arguments.
5811 bool isSpecialized() const;
5812
5813 /// Determine whether this object type was written with type arguments.
5814 bool isSpecializedAsWritten() const {
5815 return ObjCObjectTypeBits.NumTypeArgs > 0;
5816 }
5817
5818 /// Determine whether this object type is "unspecialized", meaning
5819 /// that it has no type arguments.
5820 bool isUnspecialized() const { return !isSpecialized(); }
5821
5822 /// Determine whether this object type is "unspecialized" as
5823 /// written, meaning that it has no type arguments.
5824 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5825
5826 /// Retrieve the type arguments of this object type (semantically).
5827 ArrayRef<QualType> getTypeArgs() const;
5828
5829 /// Retrieve the type arguments of this object type as they were
5830 /// written.
5831 ArrayRef<QualType> getTypeArgsAsWritten() const {
5832 return llvm::makeArrayRef(getTypeArgStorage(),
5833 ObjCObjectTypeBits.NumTypeArgs);
5834 }
5835
5836 /// Whether this is a "__kindof" type as written.
5837 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5838
5839 /// Whether this ia a "__kindof" type (semantically).
5840 bool isKindOfType() const;
5841
5842 /// Retrieve the type of the superclass of this object type.
5843 ///
5844 /// This operation substitutes any type arguments into the
5845 /// superclass of the current class type, potentially producing a
5846 /// specialization of the superclass type. Produces a null type if
5847 /// there is no superclass.
5848 QualType getSuperClassType() const {
5849 if (!CachedSuperClassType.getInt())
5850 computeSuperClassTypeSlow();
5851
5852 assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?"
) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5852, __PRETTY_FUNCTION__))
;
5853 return QualType(CachedSuperClassType.getPointer(), 0);
5854 }
5855
5856 /// Strip off the Objective-C "kindof" type and (with it) any
5857 /// protocol qualifiers.
5858 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5859
5860 bool isSugared() const { return false; }
5861 QualType desugar() const { return QualType(this, 0); }
5862
5863 static bool classof(const Type *T) {
5864 return T->getTypeClass() == ObjCObject ||
5865 T->getTypeClass() == ObjCInterface;
5866 }
5867};
5868
5869/// A class providing a concrete implementation
5870/// of ObjCObjectType, so as to not increase the footprint of
5871/// ObjCInterfaceType. Code outside of ASTContext and the core type
5872/// system should not reference this type.
5873class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5874 friend class ASTContext;
5875
5876 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5877 // will need to be modified.
5878
5879 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5880 ArrayRef<QualType> typeArgs,
5881 ArrayRef<ObjCProtocolDecl *> protocols,
5882 bool isKindOf)
5883 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5884
5885public:
5886 void Profile(llvm::FoldingSetNodeID &ID);
5887 static void Profile(llvm::FoldingSetNodeID &ID,
5888 QualType Base,
5889 ArrayRef<QualType> typeArgs,
5890 ArrayRef<ObjCProtocolDecl *> protocols,
5891 bool isKindOf);
5892};
5893
5894inline QualType *ObjCObjectType::getTypeArgStorage() {
5895 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5896}
5897
5898inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5899 return reinterpret_cast<ObjCProtocolDecl**>(
5900 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5901}
5902
5903inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5904 return reinterpret_cast<ObjCProtocolDecl**>(
5905 static_cast<ObjCTypeParamType*>(this)+1);
5906}
5907
5908/// Interfaces are the core concept in Objective-C for object oriented design.
5909/// They basically correspond to C++ classes. There are two kinds of interface
5910/// types: normal interfaces like `NSString`, and qualified interfaces, which
5911/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5912///
5913/// ObjCInterfaceType guarantees the following properties when considered
5914/// as a subtype of its superclass, ObjCObjectType:
5915/// - There are no protocol qualifiers. To reinforce this, code which
5916/// tries to invoke the protocol methods via an ObjCInterfaceType will
5917/// fail to compile.
5918/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5919/// T->getBaseType() == QualType(T, 0).
5920class ObjCInterfaceType : public ObjCObjectType {
5921 friend class ASTContext; // ASTContext creates these.
5922 friend class ASTReader;
5923 friend class ObjCInterfaceDecl;
5924 template <class T> friend class serialization::AbstractTypeReader;
5925
5926 mutable ObjCInterfaceDecl *Decl;
5927
5928 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5929 : ObjCObjectType(Nonce_ObjCInterface),
5930 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5931
5932public:
5933 /// Get the declaration of this interface.
5934 ObjCInterfaceDecl *getDecl() const { return Decl; }
5935
5936 bool isSugared() const { return false; }
5937 QualType desugar() const { return QualType(this, 0); }
5938
5939 static bool classof(const Type *T) {
5940 return T->getTypeClass() == ObjCInterface;
5941 }
5942
5943 // Nonsense to "hide" certain members of ObjCObjectType within this
5944 // class. People asking for protocols on an ObjCInterfaceType are
5945 // not going to get what they want: ObjCInterfaceTypes are
5946 // guaranteed to have no protocols.
5947 enum {
5948 qual_iterator,
5949 qual_begin,
5950 qual_end,
5951 getNumProtocols,
5952 getProtocol
5953 };
5954};
5955
5956inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5957 QualType baseType = getBaseType();
5958 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
5959 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
5960 return T->getDecl();
5961
5962 baseType = ObjT->getBaseType();
5963 }
5964
5965 return nullptr;
5966}
5967
5968/// Represents a pointer to an Objective C object.
5969///
5970/// These are constructed from pointer declarators when the pointee type is
5971/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
5972/// types are typedefs for these, and the protocol-qualified types 'id<P>'
5973/// and 'Class<P>' are translated into these.
5974///
5975/// Pointers to pointers to Objective C objects are still PointerTypes;
5976/// only the first level of pointer gets it own type implementation.
5977class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5978 friend class ASTContext; // ASTContext creates these.
5979
5980 QualType PointeeType;
5981
5982 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5983 : Type(ObjCObjectPointer, Canonical,
5984 Pointee->isDependentType(),
5985 Pointee->isInstantiationDependentType(),
5986 Pointee->isVariablyModifiedType(),
5987 Pointee->containsUnexpandedParameterPack()),
5988 PointeeType(Pointee) {}
5989
5990public:
5991 /// Gets the type pointed to by this ObjC pointer.
5992 /// The result will always be an ObjCObjectType or sugar thereof.
5993 QualType getPointeeType() const { return PointeeType; }
5994
5995 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
5996 ///
5997 /// This method is equivalent to getPointeeType() except that
5998 /// it discards any typedefs (or other sugar) between this
5999 /// type and the "outermost" object type. So for:
6000 /// \code
6001 /// \@class A; \@protocol P; \@protocol Q;
6002 /// typedef A<P> AP;
6003 /// typedef A A1;
6004 /// typedef A1<P> A1P;
6005 /// typedef A1P<Q> A1PQ;
6006 /// \endcode
6007 /// For 'A*', getObjectType() will return 'A'.
6008 /// For 'A<P>*', getObjectType() will return 'A<P>'.
6009 /// For 'AP*', getObjectType() will return 'A<P>'.
6010 /// For 'A1*', getObjectType() will return 'A'.
6011 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
6012 /// For 'A1P*', getObjectType() will return 'A1<P>'.
6013 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
6014 /// adding protocols to a protocol-qualified base discards the
6015 /// old qualifiers (for now). But if it didn't, getObjectType()
6016 /// would return 'A1P<Q>' (and we'd have to make iterating over
6017 /// qualifiers more complicated).
6018 const ObjCObjectType *getObjectType() const {
6019 return PointeeType->castAs<ObjCObjectType>();
6020 }
6021
6022 /// If this pointer points to an Objective C
6023 /// \@interface type, gets the type for that interface. Any protocol
6024 /// qualifiers on the interface are ignored.
6025 ///
6026 /// \return null if the base type for this pointer is 'id' or 'Class'
6027 const ObjCInterfaceType *getInterfaceType() const;
6028
6029 /// If this pointer points to an Objective \@interface
6030 /// type, gets the declaration for that interface.
6031 ///
6032 /// \return null if the base type for this pointer is 'id' or 'Class'
6033 ObjCInterfaceDecl *getInterfaceDecl() const {
6034 return getObjectType()->getInterface();
6035 }
6036
6037 /// True if this is equivalent to the 'id' type, i.e. if
6038 /// its object type is the primitive 'id' type with no protocols.
6039 bool isObjCIdType() const {
6040 return getObjectType()->isObjCUnqualifiedId();
6041 }
6042
6043 /// True if this is equivalent to the 'Class' type,
6044 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
6045 bool isObjCClassType() const {
6046 return getObjectType()->isObjCUnqualifiedClass();
6047 }
6048
6049 /// True if this is equivalent to the 'id' or 'Class' type,
6050 bool isObjCIdOrClassType() const {
6051 return getObjectType()->isObjCUnqualifiedIdOrClass();
6052 }
6053
6054 /// True if this is equivalent to 'id<P>' for some non-empty set of
6055 /// protocols.
6056 bool isObjCQualifiedIdType() const {
6057 return getObjectType()->isObjCQualifiedId();
6058 }
6059
6060 /// True if this is equivalent to 'Class<P>' for some non-empty set of
6061 /// protocols.
6062 bool isObjCQualifiedClassType() const {
6063 return getObjectType()->isObjCQualifiedClass();
6064 }
6065
6066 /// Whether this is a "__kindof" type.
6067 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
6068
6069 /// Whether this type is specialized, meaning that it has type arguments.
6070 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
6071
6072 /// Whether this type is specialized, meaning that it has type arguments.
6073 bool isSpecializedAsWritten() const {
6074 return getObjectType()->isSpecializedAsWritten();
6075 }
6076
6077 /// Whether this type is unspecialized, meaning that is has no type arguments.
6078 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
6079
6080 /// Determine whether this object type is "unspecialized" as
6081 /// written, meaning that it has no type arguments.
6082 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
6083
6084 /// Retrieve the type arguments for this type.
6085 ArrayRef<QualType> getTypeArgs() const {
6086 return getObjectType()->getTypeArgs();
6087 }
6088
6089 /// Retrieve the type arguments for this type.
6090 ArrayRef<QualType> getTypeArgsAsWritten() const {
6091 return getObjectType()->getTypeArgsAsWritten();
6092 }
6093
6094 /// An iterator over the qualifiers on the object type. Provided
6095 /// for convenience. This will always iterate over the full set of
6096 /// protocols on a type, not just those provided directly.
6097 using qual_iterator = ObjCObjectType::qual_iterator;
6098 using qual_range = llvm::iterator_range<qual_iterator>;
6099
6100 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
6101
6102 qual_iterator qual_begin() const {
6103 return getObjectType()->qual_begin();
6104 }
6105
6106 qual_iterator qual_end() const {
6107 return getObjectType()->qual_end();
6108 }
6109
6110 bool qual_empty() const { return getObjectType()->qual_empty(); }
6111
6112 /// Return the number of qualifying protocols on the object type.
6113 unsigned getNumProtocols() const {
6114 return getObjectType()->getNumProtocols();
6115 }
6116
6117 /// Retrieve a qualifying protocol by index on the object type.
6118 ObjCProtocolDecl *getProtocol(unsigned I) const {
6119 return getObjectType()->getProtocol(I);
6120 }
6121
6122 bool isSugared() const { return false; }
6123 QualType desugar() const { return QualType(this, 0); }
6124
6125 /// Retrieve the type of the superclass of this object pointer type.
6126 ///
6127 /// This operation substitutes any type arguments into the
6128 /// superclass of the current class type, potentially producing a
6129 /// pointer to a specialization of the superclass type. Produces a
6130 /// null type if there is no superclass.
6131 QualType getSuperClassType() const;
6132
6133 /// Strip off the Objective-C "kindof" type and (with it) any
6134 /// protocol qualifiers.
6135 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6136 const ASTContext &ctx) const;
6137
6138 void Profile(llvm::FoldingSetNodeID &ID) {
6139 Profile(ID, getPointeeType());
6140 }
6141
6142 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6143 ID.AddPointer(T.getAsOpaquePtr());
6144 }
6145
6146 static bool classof(const Type *T) {
6147 return T->getTypeClass() == ObjCObjectPointer;
6148 }
6149};
6150
6151class AtomicType : public Type, public llvm::FoldingSetNode {
6152 friend class ASTContext; // ASTContext creates these.
6153
6154 QualType ValueType;
6155
6156 AtomicType(QualType ValTy, QualType Canonical)
6157 : Type(Atomic, Canonical, ValTy->isDependentType(),
6158 ValTy->isInstantiationDependentType(),
6159 ValTy->isVariablyModifiedType(),
6160 ValTy->containsUnexpandedParameterPack()),
6161 ValueType(ValTy) {}
6162
6163public:
6164 /// Gets the type contained by this atomic type, i.e.
6165 /// the type returned by performing an atomic load of this atomic type.
6166 QualType getValueType() const { return ValueType; }
6167
6168 bool isSugared() const { return false; }
6169 QualType desugar() const { return QualType(this, 0); }
6170
6171 void Profile(llvm::FoldingSetNodeID &ID) {
6172 Profile(ID, getValueType());
6173 }
6174
6175 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6176 ID.AddPointer(T.getAsOpaquePtr());
6177 }
6178
6179 static bool classof(const Type *T) {
6180 return T->getTypeClass() == Atomic;
6181 }
6182};
6183
6184/// PipeType - OpenCL20.
6185class PipeType : public Type, public llvm::FoldingSetNode {
6186 friend class ASTContext; // ASTContext creates these.
6187
6188 QualType ElementType;
6189 bool isRead;
6190
6191 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6192 : Type(Pipe, CanonicalPtr, elemType->isDependentType(),
6193 elemType->isInstantiationDependentType(),
6194 elemType->isVariablyModifiedType(),
6195 elemType->containsUnexpandedParameterPack()),
6196 ElementType(elemType), isRead(isRead) {}
6197
6198public:
6199 QualType getElementType() const { return ElementType; }
6200
6201 bool isSugared() const { return false; }
6202
6203 QualType desugar() const { return QualType(this, 0); }
6204
6205 void Profile(llvm::FoldingSetNodeID &ID) {
6206 Profile(ID, getElementType(), isReadOnly());
6207 }
6208
6209 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6210 ID.AddPointer(T.getAsOpaquePtr());
6211 ID.AddBoolean(isRead);
6212 }
6213
6214 static bool classof(const Type *T) {
6215 return T->getTypeClass() == Pipe;
6216 }
6217
6218 bool isReadOnly() const { return isRead; }
6219};
6220
6221/// A qualifier set is used to build a set of qualifiers.
6222class QualifierCollector : public Qualifiers {
6223public:
6224 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6225
6226 /// Collect any qualifiers on the given type and return an
6227 /// unqualified type. The qualifiers are assumed to be consistent
6228 /// with those already in the type.
6229 const Type *strip(QualType type) {
6230 addFastQualifiers(type.getLocalFastQualifiers());
6231 if (!type.hasLocalNonFastQualifiers())
6232 return type.getTypePtrUnsafe();
6233
6234 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6235 addConsistentQualifiers(extQuals->getQualifiers());
6236 return extQuals->getBaseType();
6237 }
6238
6239 /// Apply the collected qualifiers to the given type.
6240 QualType apply(const ASTContext &Context, QualType QT) const;
6241
6242 /// Apply the collected qualifiers to the given type.
6243 QualType apply(const ASTContext &Context, const Type* T) const;
6244};
6245
6246/// A container of type source information.
6247///
6248/// A client can read the relevant info using TypeLoc wrappers, e.g:
6249/// @code
6250/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
6251/// TL.getBeginLoc().print(OS, SrcMgr);
6252/// @endcode
6253class alignas(8) TypeSourceInfo {
6254 // Contains a memory block after the class, used for type source information,
6255 // allocated by ASTContext.
6256 friend class ASTContext;
6257
6258 QualType Ty;
6259
6260 TypeSourceInfo(QualType ty) : Ty(ty) {}
6261
6262public:
6263 /// Return the type wrapped by this type source info.
6264 QualType getType() const { return Ty; }
6265
6266 /// Return the TypeLoc wrapper for the type source info.
6267 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
6268
6269 /// Override the type stored in this TypeSourceInfo. Use with caution!
6270 void overrideType(QualType T) { Ty = T; }
6271};
6272
6273// Inline function definitions.
6274
6275inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6276 SplitQualType desugar =
6277 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6278 desugar.Quals.addConsistentQualifiers(Quals);
6279 return desugar;
6280}
6281
6282inline const Type *QualType::getTypePtr() const {
6283 return getCommonPtr()->BaseType;
6284}
6285
6286inline const Type *QualType::getTypePtrOrNull() const {
6287 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6288}
6289
6290inline SplitQualType QualType::split() const {
6291 if (!hasLocalNonFastQualifiers())
6292 return SplitQualType(getTypePtrUnsafe(),
6293 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6294
6295 const ExtQuals *eq = getExtQualsUnsafe();
6296 Qualifiers qs = eq->getQualifiers();
6297 qs.addFastQualifiers(getLocalFastQualifiers());
6298 return SplitQualType(eq->getBaseType(), qs);
6299}
6300
6301inline Qualifiers QualType::getLocalQualifiers() const {
6302 Qualifiers Quals;
6303 if (hasLocalNonFastQualifiers())
6304 Quals = getExtQualsUnsafe()->getQualifiers();
6305 Quals.addFastQualifiers(getLocalFastQualifiers());
6306 return Quals;
6307}
6308
6309inline Qualifiers QualType::getQualifiers() const {
6310 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6311 quals.addFastQualifiers(getLocalFastQualifiers());
6312 return quals;
6313}
6314
6315inline unsigned QualType::getCVRQualifiers() const {
6316 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6317 cvr |= getLocalCVRQualifiers();
6318 return cvr;
6319}
6320
6321inline QualType QualType::getCanonicalType() const {
6322 QualType canon = getCommonPtr()->CanonicalType;
6323 return canon.withFastQualifiers(getLocalFastQualifiers());
6324}
6325
6326inline bool QualType::isCanonical() const {
6327 return getTypePtr()->isCanonicalUnqualified();
6328}
6329
6330inline bool QualType::isCanonicalAsParam() const {
6331 if (!isCanonical()) return false;
6332 if (hasLocalQualifiers()) return false;
6333
6334 const Type *T = getTypePtr();
6335 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6336 return false;
6337
6338 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6339}
6340
6341inline bool QualType::isConstQualified() const {
6342 return isLocalConstQualified() ||
6343 getCommonPtr()->CanonicalType.isLocalConstQualified();
6344}
6345
6346inline bool QualType::isRestrictQualified() const {
6347 return isLocalRestrictQualified() ||
6348 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6349}
6350
6351
6352inline bool QualType::isVolatileQualified() const {
6353 return isLocalVolatileQualified() ||
6354 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6355}
6356
6357inline bool QualType::hasQualifiers() const {
6358 return hasLocalQualifiers() ||
6359 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6360}
6361
6362inline QualType QualType::getUnqualifiedType() const {
6363 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6364 return QualType(getTypePtr(), 0);
6365
6366 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6367}
6368
6369inline SplitQualType QualType::getSplitUnqualifiedType() const {
6370 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6371 return split();
6372
6373 return getSplitUnqualifiedTypeImpl(*this);
6374}
6375
6376inline void QualType::removeLocalConst() {
6377 removeLocalFastQualifiers(Qualifiers::Const);
6378}
6379
6380inline void QualType::removeLocalRestrict() {
6381 removeLocalFastQualifiers(Qualifiers::Restrict);
6382}
6383
6384inline void QualType::removeLocalVolatile() {
6385 removeLocalFastQualifiers(Qualifiers::Volatile);
6386}
6387
6388inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6389 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 6389, __PRETTY_FUNCTION__))
;
6390 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6391 "Fast bits differ from CVR bits!");
6392
6393 // Fast path: we don't need to touch the slow qualifiers.
6394 removeLocalFastQualifiers(Mask);
6395}
6396
6397/// Check if this type has any address space qualifier.
6398inline bool QualType::hasAddressSpace() const {
6399 return getQualifiers().hasAddressSpace();
6400}
6401
6402/// Return the address space of this type.
6403inline LangAS QualType::getAddressSpace() const {
6404 return getQualifiers().getAddressSpace();
6405}
6406
6407/// Return the gc attribute of this type.
6408inline Qualifiers::GC QualType::getObjCGCAttr() const {
6409 return getQualifiers().getObjCGCAttr();
6410}
6411
6412inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6413 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6414 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6415 return false;
6416}
6417
6418inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6419 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6420 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6421 return false;
6422}
6423
6424inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6425 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6426 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6427 return false;
6428}
6429
6430inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6431 if (const auto *PT = t.getAs<PointerType>()) {
6432 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6433 return FT->getExtInfo();
6434 } else if (const auto *FT = t.getAs<FunctionType>())
6435 return FT->getExtInfo();
6436
6437 return FunctionType::ExtInfo();
6438}
6439
6440inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6441 return getFunctionExtInfo(*t);
6442}
6443
6444/// Determine whether this type is more
6445/// qualified than the Other type. For example, "const volatile int"
6446/// is more qualified than "const int", "volatile int", and
6447/// "int". However, it is not more qualified than "const volatile
6448/// int".
6449inline bool QualType::isMoreQualifiedThan(QualType other) const {
6450 Qualifiers MyQuals = getQualifiers();
6451 Qualifiers OtherQuals = other.getQualifiers();
6452 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6453}
6454
6455/// Determine whether this type is at last
6456/// as qualified as the Other type. For example, "const volatile
6457/// int" is at least as qualified as "const int", "volatile int",
6458/// "int", and "const volatile int".
6459inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6460 Qualifiers OtherQuals = other.getQualifiers();
6461
6462 // Ignore __unaligned qualifier if this type is a void.
6463 if (getUnqualifiedType()->isVoidType())
6464 OtherQuals.removeUnaligned();
6465
6466 return getQualifiers().compatiblyIncludes(OtherQuals);
6467}
6468
6469/// If Type is a reference type (e.g., const
6470/// int&), returns the type that the reference refers to ("const
6471/// int"). Otherwise, returns the type itself. This routine is used
6472/// throughout Sema to implement C++ 5p6:
6473///
6474/// If an expression initially has the type "reference to T" (8.3.2,
6475/// 8.5.3), the type is adjusted to "T" prior to any further
6476/// analysis, the expression designates the object or function
6477/// denoted by the reference, and the expression is an lvalue.
6478inline QualType QualType::getNonReferenceType() const {
6479 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6480 return RefType->getPointeeType();
6481 else
6482 return *this;
6483}
6484
6485inline bool QualType::isCForbiddenLValueType() const {
6486 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6487 getTypePtr()->isFunctionType());
6488}
6489
6490/// Tests whether the type is categorized as a fundamental type.
6491///
6492/// \returns True for types specified in C++0x [basic.fundamental].
6493inline bool Type::isFundamentalType() const {
6494 return isVoidType() ||
6495 isNullPtrType() ||
6496 // FIXME: It's really annoying that we don't have an
6497 // 'isArithmeticType()' which agrees with the standard definition.
6498 (isArithmeticType() && !isEnumeralType());
6499}
6500
6501/// Tests whether the type is categorized as a compound type.
6502///
6503/// \returns True for types specified in C++0x [basic.compound].
6504inline bool Type::isCompoundType() const {
6505 // C++0x [basic.compound]p1:
6506 // Compound types can be constructed in the following ways:
6507 // -- arrays of objects of a given type [...];
6508 return isArrayType() ||
6509 // -- functions, which have parameters of given types [...];
6510 isFunctionType() ||
6511 // -- pointers to void or objects or functions [...];
6512 isPointerType() ||
6513 // -- references to objects or functions of a given type. [...]
6514 isReferenceType() ||
6515 // -- classes containing a sequence of objects of various types, [...];
6516 isRecordType() ||
6517 // -- unions, which are classes capable of containing objects of different
6518 // types at different times;
6519 isUnionType() ||
6520 // -- enumerations, which comprise a set of named constant values. [...];
6521 isEnumeralType() ||
6522 // -- pointers to non-static class members, [...].
6523 isMemberPointerType();
6524}
6525
6526inline bool Type::isFunctionType() const {
6527 return isa<FunctionType>(CanonicalType);
6528}
6529
6530inline bool Type::isPointerType() const {
6531 return isa<PointerType>(CanonicalType);
6532}
6533
6534inline bool Type::isAnyPointerType() const {
6535 return isPointerType() || isObjCObjectPointerType();
6536}
6537
6538inline bool Type::isBlockPointerType() const {
6539 return isa<BlockPointerType>(CanonicalType);
6540}
6541
6542inline bool Type::isReferenceType() const {
6543 return isa<ReferenceType>(CanonicalType);
6544}
6545
6546inline bool Type::isLValueReferenceType() const {
6547 return isa<LValueReferenceType>(CanonicalType);
6548}
6549
6550inline bool Type::isRValueReferenceType() const {
6551 return isa<RValueReferenceType>(CanonicalType);
6552}
6553
6554inline bool Type::isObjectPointerType() const {
6555 // Note: an "object pointer type" is not the same thing as a pointer to an
6556 // object type; rather, it is a pointer to an object type or a pointer to cv
6557 // void.
6558 if (const auto *T = getAs<PointerType>())
6559 return !T->getPointeeType()->isFunctionType();
6560 else
6561 return false;
6562}
6563
6564inline bool Type::isFunctionPointerType() const {
6565 if (const auto *T = getAs<PointerType>())
6566 return T->getPointeeType()->isFunctionType();
6567 else
6568 return false;
6569}
6570
6571inline bool Type::isFunctionReferenceType() const {
6572 if (const auto *T = getAs<ReferenceType>())
6573 return T->getPointeeType()->isFunctionType();
6574 else
6575 return false;
6576}
6577
6578inline bool Type::isMemberPointerType() const {
6579 return isa<MemberPointerType>(CanonicalType);
6580}
6581
6582inline bool Type::isMemberFunctionPointerType() const {
6583 if (const auto *T = getAs<MemberPointerType>())
6584 return T->isMemberFunctionPointer();
6585 else
6586 return false;
6587}
6588
6589inline bool Type::isMemberDataPointerType() const {
6590 if (const auto *T = getAs<MemberPointerType>())
6591 return T->isMemberDataPointer();
6592 else
6593 return false;
6594}
6595
6596inline bool Type::isArrayType() const {
6597 return isa<ArrayType>(CanonicalType);
6598}
6599
6600inline bool Type::isConstantArrayType() const {
6601 return isa<ConstantArrayType>(CanonicalType);
6602}
6603
6604inline bool Type::isIncompleteArrayType() const {
6605 return isa<IncompleteArrayType>(CanonicalType);
6606}
6607
6608inline bool Type::isVariableArrayType() const {
6609 return isa<VariableArrayType>(CanonicalType);
6610}
6611
6612inline bool Type::isDependentSizedArrayType() const {
6613 return isa<DependentSizedArrayType>(CanonicalType);
6614}
6615
6616inline bool Type::isBuiltinType() const {
6617 return isa<BuiltinType>(CanonicalType);
6618}
6619
6620inline bool Type::isRecordType() const {
6621 return isa<RecordType>(CanonicalType);
17
Assuming field 'CanonicalType' is a 'RecordType'
18
Returning the value 1, which participates in a condition later
6622}
6623
6624inline bool Type::isEnumeralType() const {
6625 return isa<EnumType>(CanonicalType);
6626}
6627
6628inline bool Type::isAnyComplexType() const {
6629 return isa<ComplexType>(CanonicalType);
6630}
6631
6632inline bool Type::isVectorType() const {
6633 return isa<VectorType>(CanonicalType);
6634}
6635
6636inline bool Type::isExtVectorType() const {
6637 return isa<ExtVectorType>(CanonicalType);
6638}
6639
6640inline bool Type::isDependentAddressSpaceType() const {
6641 return isa<DependentAddressSpaceType>(CanonicalType);
6642}
6643
6644inline bool Type::isObjCObjectPointerType() const {
6645 return isa<ObjCObjectPointerType>(CanonicalType);
3
Assuming field 'CanonicalType' is a 'ObjCObjectPointerType'
4
Returning the value 1, which participates in a condition later
6646}
6647
6648inline bool Type::isObjCObjectType() const {
6649 return isa<ObjCObjectType>(CanonicalType);
6650}
6651
6652inline bool Type::isObjCObjectOrInterfaceType() const {
6653 return isa<ObjCInterfaceType>(CanonicalType) ||
6654 isa<ObjCObjectType>(CanonicalType);
6655}
6656
6657inline bool Type::isAtomicType() const {
6658 return isa<AtomicType>(CanonicalType);
6659}
6660
6661inline bool Type::isUndeducedAutoType() const {
6662 return isa<AutoType>(CanonicalType);
6663}
6664
6665inline bool Type::isObjCQualifiedIdType() const {
6666 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6667 return OPT->isObjCQualifiedIdType();
6668 return false;
6669}
6670
6671inline bool Type::isObjCQualifiedClassType() const {
6672 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6673 return OPT->isObjCQualifiedClassType();
6674 return false;
6675}
6676
6677inline bool Type::isObjCIdType() const {
6678 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6679 return OPT->isObjCIdType();
6680 return false;
6681}
6682
6683inline bool Type::isObjCClassType() const {
6684 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6685 return OPT->isObjCClassType();
6686 return false;
6687}
6688
6689inline bool Type::isObjCSelType() const {
6690 if (const auto *OPT = getAs<PointerType>())
6691 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6692 return false;
6693}
6694
6695inline bool Type::isObjCBuiltinType() const {
6696 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6697}
6698
6699inline bool Type::isDecltypeType() const {
6700 return isa<DecltypeType>(this);
6701}
6702
6703#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6704 inline bool Type::is##Id##Type() const { \
6705 return isSpecificBuiltinType(BuiltinType::Id); \
6706 }
6707#include "clang/Basic/OpenCLImageTypes.def"
6708
6709inline bool Type::isSamplerT() const {
6710 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6711}
6712
6713inline bool Type::isEventT() const {
6714 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6715}
6716
6717inline bool Type::isClkEventT() const {
6718 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6719}
6720
6721inline bool Type::isQueueT() const {
6722 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6723}
6724
6725inline bool Type::isReserveIDT() const {
6726 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6727}
6728
6729inline bool Type::isImageType() const {
6730#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6731 return
6732#include "clang/Basic/OpenCLImageTypes.def"
6733 false; // end boolean or operation
6734}
6735
6736inline bool Type::isPipeType() const {
6737 return isa<PipeType>(CanonicalType);
6738}
6739
6740#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6741 inline bool Type::is##Id##Type() const { \
6742 return isSpecificBuiltinType(BuiltinType::Id); \
6743 }
6744#include "clang/Basic/OpenCLExtensionTypes.def"
6745
6746inline bool Type::isOCLIntelSubgroupAVCType() const {
6747#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6748 isOCLIntelSubgroupAVC##Id##Type() ||
6749 return
6750#include "clang/Basic/OpenCLExtensionTypes.def"
6751 false; // end of boolean or operation
6752}
6753
6754inline bool Type::isOCLExtOpaqueType() const {
6755#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6756 return
6757#include "clang/Basic/OpenCLExtensionTypes.def"
6758 false; // end of boolean or operation
6759}
6760
6761inline bool Type::isOpenCLSpecificType() const {
6762 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6763 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6764}
6765
6766inline bool Type::isTemplateTypeParmType() const {
6767 return isa<TemplateTypeParmType>(CanonicalType);
6768}
6769
6770inline bool Type::isSpecificBuiltinType(unsigned K) const {
6771 if (const BuiltinType *BT = getAs<BuiltinType>())
6772 if (BT->getKind() == (BuiltinType::Kind) K)
6773 return true;
6774 return false;
6775}
6776
6777inline bool Type::isPlaceholderType() const {
6778 if (const auto *BT = dyn_cast<BuiltinType>(this))
6779 return BT->isPlaceholderType();
6780 return false;
6781}
6782
6783inline const BuiltinType *Type::getAsPlaceholderType() const {
6784 if (const auto *BT = dyn_cast<BuiltinType>(this))
6785 if (BT->isPlaceholderType())
6786 return BT;
6787 return nullptr;
6788}
6789
6790inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6791 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ?
static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 6791, __PRETTY_FUNCTION__))
;
6792 if (const auto *BT = dyn_cast<BuiltinType>(this))
6793 return (BT->getKind() == (BuiltinType::Kind) K);
6794 return false;
6795}
6796
6797inline bool Type::isNonOverloadPlaceholderType() const {
6798 if (const auto *BT = dyn_cast<BuiltinType>(this))
6799 return BT->isNonOverloadPlaceholderType();
6800 return false;
6801}
6802
6803inline bool Type::isVoidType() const {
6804 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6805 return BT->getKind() == BuiltinType::Void;
6806 return false;
6807}
6808
6809inline bool Type::isHalfType() const {
6810 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6811 return BT->getKind() == BuiltinType::Half;
6812 // FIXME: Should we allow complex __fp16? Probably not.
6813 return false;
6814}
6815
6816inline bool Type::isFloat16Type() const {
6817 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6818 return BT->getKind() == BuiltinType::Float16;
6819 return false;
6820}
6821
6822inline bool Type::isFloat128Type() const {
6823 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6824 return BT->getKind() == BuiltinType::Float128;
6825 return false;
6826}
6827
6828inline bool Type::isNullPtrType() const {
6829 if (const auto *BT = getAs<BuiltinType>())
6830 return BT->getKind() == BuiltinType::NullPtr;
6831 return false;
6832}
6833
6834bool IsEnumDeclComplete(EnumDecl *);
6835bool IsEnumDeclScoped(EnumDecl *);
6836
6837inline bool Type::isIntegerType() const {
6838 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6839 return BT->getKind() >= BuiltinType::Bool &&
6840 BT->getKind() <= BuiltinType::Int128;
6841 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6842 // Incomplete enum types are not treated as integer types.
6843 // FIXME: In C++, enum types are never integer types.
6844 return IsEnumDeclComplete(ET->getDecl()) &&
6845 !IsEnumDeclScoped(ET->getDecl());
6846 }
6847 return false;
6848}
6849
6850inline bool Type::isFixedPointType() const {
6851 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6852 return BT->getKind() >= BuiltinType::ShortAccum &&
6853 BT->getKind() <= BuiltinType::SatULongFract;
6854 }
6855 return false;
6856}
6857
6858inline bool Type::isFixedPointOrIntegerType() const {
6859 return isFixedPointType() || isIntegerType();
6860}
6861
6862inline bool Type::isSaturatedFixedPointType() const {
6863 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6864 return BT->getKind() >= BuiltinType::SatShortAccum &&
6865 BT->getKind() <= BuiltinType::SatULongFract;
6866 }
6867 return false;
6868}
6869
6870inline bool Type::isUnsaturatedFixedPointType() const {
6871 return isFixedPointType() && !isSaturatedFixedPointType();
6872}
6873
6874inline bool Type::isSignedFixedPointType() const {
6875 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6876 return ((BT->getKind() >= BuiltinType::ShortAccum &&
6877 BT->getKind() <= BuiltinType::LongAccum) ||
6878 (BT->getKind() >= BuiltinType::ShortFract &&
6879 BT->getKind() <= BuiltinType::LongFract) ||
6880 (BT->getKind() >= BuiltinType::SatShortAccum &&
6881 BT->getKind() <= BuiltinType::SatLongAccum) ||
6882 (BT->getKind() >= BuiltinType::SatShortFract &&
6883 BT->getKind() <= BuiltinType::SatLongFract));
6884 }
6885 return false;
6886}
6887
6888inline bool Type::isUnsignedFixedPointType() const {
6889 return isFixedPointType() && !isSignedFixedPointType();
6890}
6891
6892inline bool Type::isScalarType() const {
6893 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6894 return BT->getKind() > BuiltinType::Void &&
6895 BT->getKind() <= BuiltinType::NullPtr;
6896 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
6897 // Enums are scalar types, but only if they are defined. Incomplete enums
6898 // are not treated as scalar types.
6899 return IsEnumDeclComplete(ET->getDecl());
6900 return isa<PointerType>(CanonicalType) ||
6901 isa<BlockPointerType>(CanonicalType) ||
6902 isa<MemberPointerType>(CanonicalType) ||
6903 isa<ComplexType>(CanonicalType) ||
6904 isa<ObjCObjectPointerType>(CanonicalType);
6905}
6906
6907inline bool Type::isIntegralOrEnumerationType() const {
6908 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6909 return BT->getKind() >= BuiltinType::Bool &&
6910 BT->getKind() <= BuiltinType::Int128;
6911
6912 // Check for a complete enum type; incomplete enum types are not properly an
6913 // enumeration type in the sense required here.
6914 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
6915 return IsEnumDeclComplete(ET->getDecl());
6916
6917 return false;
6918}
6919
6920inline bool Type::isBooleanType() const {
6921 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6922 return BT->getKind() == BuiltinType::Bool;
6923 return false;
6924}
6925
6926inline bool Type::isUndeducedType() const {
6927 auto *DT = getContainedDeducedType();
6928 return DT && !DT->isDeduced();
6929}
6930
6931/// Determines whether this is a type for which one can define
6932/// an overloaded operator.
6933inline bool Type::isOverloadableType() const {
6934 return isDependentType() || isRecordType() || isEnumeralType();
6935}
6936
6937/// Determines whether this type can decay to a pointer type.
6938inline bool Type::canDecayToPointerType() const {
6939 return isFunctionType() || isArrayType();
6940}
6941
6942inline bool Type::hasPointerRepresentation() const {
6943 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
6944 isObjCObjectPointerType() || isNullPtrType());
6945}
6946
6947inline bool Type::hasObjCPointerRepresentation() const {
6948 return isObjCObjectPointerType();
6949}
6950
6951inline const Type *Type::getBaseElementTypeUnsafe() const {
6952 const Type *type = this;
6953 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
6954 type = arrayType->getElementType().getTypePtr();
6955 return type;
6956}
6957
6958inline const Type *Type::getPointeeOrArrayElementType() const {
6959 const Type *type = this;
6960 if (type->isAnyPointerType())
6961 return type->getPointeeType().getTypePtr();
6962 else if (type->isArrayType())
6963 return type->getBaseElementTypeUnsafe();
6964 return type;
6965}
6966/// Insertion operator for diagnostics. This allows sending address spaces into
6967/// a diagnostic with <<.
6968inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6969 LangAS AS) {
6970 DB.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS),
6971 DiagnosticsEngine::ArgumentKind::ak_addrspace);
6972 return DB;
6973}
6974
6975/// Insertion operator for partial diagnostics. This allows sending adress
6976/// spaces into a diagnostic with <<.
6977inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6978 LangAS AS) {
6979 PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS),
6980 DiagnosticsEngine::ArgumentKind::ak_addrspace);
6981 return PD;
6982}
6983
6984/// Insertion operator for diagnostics. This allows sending Qualifiers into a
6985/// diagnostic with <<.
6986inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6987 Qualifiers Q) {
6988 DB.AddTaggedVal(Q.getAsOpaqueValue(),
6989 DiagnosticsEngine::ArgumentKind::ak_qual);
6990 return DB;
6991}
6992
6993/// Insertion operator for partial diagnostics. This allows sending Qualifiers
6994/// into a diagnostic with <<.
6995inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6996 Qualifiers Q) {
6997 PD.AddTaggedVal(Q.getAsOpaqueValue(),
6998 DiagnosticsEngine::ArgumentKind::ak_qual);
6999 return PD;
7000}
7001
7002/// Insertion operator for diagnostics. This allows sending QualType's into a
7003/// diagnostic with <<.
7004inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
7005 QualType T) {
7006 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
7007 DiagnosticsEngine::ak_qualtype);
7008 return DB;
7009}
7010
7011/// Insertion operator for partial diagnostics. This allows sending QualType's
7012/// into a diagnostic with <<.
7013inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
7014 QualType T) {
7015 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
7016 DiagnosticsEngine::ak_qualtype);
7017 return PD;
7018}
7019
7020// Helper class template that is used by Type::getAs to ensure that one does
7021// not try to look through a qualified type to get to an array type.
7022template <typename T>
7023using TypeIsArrayType =
7024 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
7025 std::is_base_of<ArrayType, T>::value>;
7026
7027// Member-template getAs<specific type>'.
7028template <typename T> const T *Type::getAs() const {
7029 static_assert(!TypeIsArrayType<T>::value,
7030 "ArrayType cannot be used with getAs!");
7031
7032 // If this is directly a T type, return it.
7033 if (const auto *Ty = dyn_cast<T>(this))
7034 return Ty;
7035
7036 // If the canonical form of this type isn't the right kind, reject it.
7037 if (!isa<T>(CanonicalType))
7038 return nullptr;
7039
7040 // If this is a typedef for the type, strip the typedef off without
7041 // losing all typedef information.
7042 return cast<T>(getUnqualifiedDesugaredType());
7043}
7044
7045template <typename T> const T *Type::getAsAdjusted() const {
7046 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
7047
7048 // If this is directly a T type, return it.
7049 if (const auto *Ty = dyn_cast<T>(this))
7050 return Ty;
7051
7052 // If the canonical form of this type isn't the right kind, reject it.
7053 if (!isa<T>(CanonicalType))
7054 return nullptr;
7055
7056 // Strip off type adjustments that do not modify the underlying nature of the
7057 // type.
7058 const Type *Ty = this;
7059 while (Ty) {
7060 if (const auto *A = dyn_cast<AttributedType>(Ty))
7061 Ty = A->getModifiedType().getTypePtr();
7062 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
7063 Ty = E->desugar().getTypePtr();
7064 else if (const auto *P = dyn_cast<ParenType>(Ty))
7065 Ty = P->desugar().getTypePtr();
7066 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
7067 Ty = A->desugar().getTypePtr();
7068 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
7069 Ty = M->desugar().getTypePtr();
7070 else
7071 break;
7072 }
7073
7074 // Just because the canonical type is correct does not mean we can use cast<>,
7075 // since we may not have stripped off all the sugar down to the base type.
7076 return dyn_cast<T>(Ty);
7077}
7078
7079inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
7080 // If this is directly an array type, return it.
7081 if (const auto *arr = dyn_cast<ArrayType>(this))
7082 return arr;
7083
7084 // If the canonical form of this type isn't the right kind, reject it.
7085 if (!isa<ArrayType>(CanonicalType))
7086 return nullptr;
7087
7088 // If this is a typedef for the type, strip the typedef off without
7089 // losing all typedef information.
7090 return cast<ArrayType>(getUnqualifiedDesugaredType());
7091}
7092
7093template <typename T> const T *Type::castAs() const {
7094 static_assert(!TypeIsArrayType<T>::value,
7095 "ArrayType cannot be used with castAs!");
7096
7097 if (const auto *ty = dyn_cast<T>(this)) return ty;
7098 assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) :
__assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 7098, __PRETTY_FUNCTION__))
;
7099 return cast<T>(getUnqualifiedDesugaredType());
7100}
7101
7102inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
7103 assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void>
(0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 7103, __PRETTY_FUNCTION__))
;
7104 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
7105 return cast<ArrayType>(getUnqualifiedDesugaredType());
7106}
7107
7108DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
7109 QualType CanonicalPtr)
7110 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
7111#ifndef NDEBUG
7112 QualType Adjusted = getAdjustedType();
7113 (void)AttributedType::stripOuterNullability(Adjusted);
7114 assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void>
(0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 7114, __PRETTY_FUNCTION__))
;
7115#endif
7116}
7117
7118QualType DecayedType::getPointeeType() const {
7119 QualType Decayed = getDecayedType();
7120 (void)AttributedType::stripOuterNullability(Decayed);
7121 return cast<PointerType>(Decayed)->getPointeeType();
7122}
7123
7124// Get the decimal string representation of a fixed point type, represented
7125// as a scaled integer.
7126// TODO: At some point, we should change the arguments to instead just accept an
7127// APFixedPoint instead of APSInt and scale.
7128void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
7129 unsigned Scale);
7130
7131} // namespace clang
7132
7133#endif // LLVM_CLANG_AST_TYPE_H