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