blob: 92ca1acfde14a366721a19e052e01b3083e36839 [file] [log] [blame]
Fariborz Jahanian11671902012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenekcdf81492012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000018#include "clang/AST/ParentMap.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/SourceManager.h"
Benjamin Kramerd7d2b1f2012-12-01 16:35:25 +000023#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000024#include "clang/Lex/Lexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000026#include "llvm/ADT/DenseSet.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000027#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000029#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000031#include <memory>
Fariborz Jahanian11671902012-02-07 17:11:38 +000032
Alp Toker0621cb22014-07-16 16:48:33 +000033#ifdef CLANG_ENABLE_OBJC_REWRITER
34
Fariborz Jahanian11671902012-02-07 17:11:38 +000035using namespace clang;
36using llvm::utostr;
37
38namespace {
39 class RewriteModernObjC : public ASTConsumer {
40 protected:
41
42 enum {
43 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
44 block, ... */
45 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
46 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
47 __block variable */
48 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
49 helpers */
50 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
51 support routines */
52 BLOCK_BYREF_CURRENT_MAX = 256
53 };
54
55 enum {
56 BLOCK_NEEDS_FREE = (1 << 24),
57 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
58 BLOCK_HAS_CXX_OBJ = (1 << 26),
59 BLOCK_IS_GC = (1 << 27),
60 BLOCK_IS_GLOBAL = (1 << 28),
61 BLOCK_HAS_DESCRIPTOR = (1 << 29)
62 };
Fariborz Jahanian11671902012-02-07 17:11:38 +000063
64 Rewriter Rewrite;
65 DiagnosticsEngine &Diags;
66 const LangOptions &LangOpts;
67 ASTContext *Context;
68 SourceManager *SM;
69 TranslationUnitDecl *TUDecl;
70 FileID MainFileID;
71 const char *MainFileStart, *MainFileEnd;
72 Stmt *CurrentBody;
73 ParentMap *PropParentMap; // created lazily.
74 std::string InFileName;
75 raw_ostream* OutFile;
76 std::string Preamble;
77
78 TypeDecl *ProtocolTypeDecl;
79 VarDecl *GlobalVarDecl;
Fariborz Jahaniane0050702012-03-23 00:00:49 +000080 Expr *GlobalConstructionExp;
Fariborz Jahanian11671902012-02-07 17:11:38 +000081 unsigned RewriteFailedDiag;
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +000082 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian11671902012-02-07 17:11:38 +000083 // ObjC string constant support.
84 unsigned NumObjCStringLiterals;
85 VarDecl *ConstantStringClassReference;
86 RecordDecl *NSStringRecord;
87
88 // ObjC foreach break/continue generation support.
89 int BcLabelCount;
90
91 unsigned TryFinallyContainsReturnDiag;
92 // Needed for super.
93 ObjCMethodDecl *CurMethodDef;
94 RecordDecl *SuperStructDecl;
95 RecordDecl *ConstantStringDecl;
96
97 FunctionDecl *MsgSendFunctionDecl;
98 FunctionDecl *MsgSendSuperFunctionDecl;
99 FunctionDecl *MsgSendStretFunctionDecl;
100 FunctionDecl *MsgSendSuperStretFunctionDecl;
101 FunctionDecl *MsgSendFpretFunctionDecl;
102 FunctionDecl *GetClassFunctionDecl;
103 FunctionDecl *GetMetaClassFunctionDecl;
104 FunctionDecl *GetSuperClassFunctionDecl;
105 FunctionDecl *SelGetUidFunctionDecl;
106 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000107 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000108 FunctionDecl *CurFunctionDef;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000109
110 /* Misc. containers needed for meta-data rewrite. */
111 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
112 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
114 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000115 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000116 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000117 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000118 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
119 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
120
121 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000122 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000123
Fariborz Jahanian11671902012-02-07 17:11:38 +0000124 SmallVector<Stmt *, 32> Stmts;
125 SmallVector<int, 8> ObjCBcLabelNo;
126 // Remember all the @protocol(<expr>) expressions.
127 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
128
129 llvm::DenseSet<uint64_t> CopyDestroyCache;
130
131 // Block expressions.
132 SmallVector<BlockExpr *, 32> Blocks;
133 SmallVector<int, 32> InnerDeclRefsCount;
John McCall113bee02012-03-10 09:33:50 +0000134 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000135
John McCall113bee02012-03-10 09:33:50 +0000136 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000137
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000138
Fariborz Jahanian11671902012-02-07 17:11:38 +0000139 // Block related declarations.
140 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
141 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
142 SmallVector<ValueDecl *, 8> BlockByRefDecls;
143 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
144 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
145 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
146 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
147
148 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000149 llvm::DenseMap<ObjCInterfaceDecl *,
150 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
151
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000152 // ivar bitfield grouping containers
153 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
154 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
155 // This container maps an <class, group number for ivar> tuple to the type
156 // of the struct where the bitfield belongs.
157 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000158 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000159
Fariborz Jahanian11671902012-02-07 17:11:38 +0000160 // This maps an original source AST to it's rewritten form. This allows
161 // us to avoid rewriting the same node twice (which is very uncommon).
162 // This is needed to support some of the exotic property rewriting.
163 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
164
165 // Needed for header files being rewritten
166 bool IsHeader;
167 bool SilenceRewriteMacroWarning;
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000168 bool GenerateLineInfo;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000169 bool objc_impl_method;
170
171 bool DisableReplaceStmt;
172 class DisableReplaceStmtScope {
173 RewriteModernObjC &R;
174 bool SavedValue;
175
176 public:
177 DisableReplaceStmtScope(RewriteModernObjC &R)
178 : R(R), SavedValue(R.DisableReplaceStmt) {
179 R.DisableReplaceStmt = true;
180 }
181 ~DisableReplaceStmtScope() {
182 R.DisableReplaceStmt = SavedValue;
183 }
184 };
185 void InitializeCommon(ASTContext &context);
186
187 public:
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +0000188 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000189 // Top Level Driver code.
Craig Topperfb6b25b2014-03-15 04:29:04 +0000190 bool HandleTopLevelDecl(DeclGroupRef D) override {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000191 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;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000196 } else {
197 // Keep track of all interface declarations seen.
Fariborz Jahanian0ed6cb72012-02-24 21:42:38 +0000198 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000199 break;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000200 }
201 }
202
203 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
204 if (!Proto->isThisDeclarationADefinition()) {
205 RewriteForwardProtocolDecl(D);
206 break;
207 }
208 }
209
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000210 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 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000222 HandleTopLevelSingleDecl(*I);
223 }
224 return true;
225 }
Craig Topperfb6b25b2014-03-15 04:29:04 +0000226
227 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Fariborz Jahaniand2940622013-10-07 19:54:22 +0000228 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 return;
239 }
240
Fariborz Jahanian11671902012-02-07 17:11:38 +0000241 void HandleTopLevelSingleDecl(Decl *D);
242 void HandleDeclInMainFile(Decl *D);
243 RewriteModernObjC(std::string inFile, raw_ostream *OS,
244 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000245 bool silenceMacroWarn, bool LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000246
247 ~RewriteModernObjC() {}
Craig Topperfb6b25b2014-03-15 04:29:04 +0000248
249 void HandleTranslationUnit(ASTContext &C) override;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000250
251 void ReplaceStmt(Stmt *Old, Stmt *New) {
Daniel Jasper4475a242014-10-23 19:47:36 +0000252 ReplaceStmtWithRange(Old, New, Old->getSourceRange());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000253 }
254
255 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Richard Trieuddd01ce2014-06-09 22:53:25 +0000256 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
Daniel Jasper4475a242014-10-23 19:47:36 +0000257
258 Stmt *ReplacingStmt = ReplacedNodes[Old];
259 if (ReplacingStmt)
260 return; // We can't rewrite the same node twice.
261
Fariborz Jahanian11671902012-02-07 17:11:38 +0000262 if (DisableReplaceStmt)
263 return;
264
265 // Measure the old text.
266 int Size = Rewrite.getRangeSize(SrcRange);
267 if (Size == -1) {
268 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
269 << Old->getSourceRange();
270 return;
271 }
272 // Get the new text.
273 std::string SStr;
274 llvm::raw_string_ostream S(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +0000275 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +0000276 const std::string &Str = S.str();
277
278 // If replacement succeeded or warning disabled return with no warning.
279 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
280 ReplacedNodes[Old] = New;
281 return;
282 }
283 if (SilenceRewriteMacroWarning)
284 return;
285 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
286 << Old->getSourceRange();
287 }
288
289 void InsertText(SourceLocation Loc, StringRef Str,
290 bool InsertAfter = true) {
291 // If insertion succeeded or warning disabled return with no warning.
292 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
293 SilenceRewriteMacroWarning)
294 return;
295
296 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
297 }
298
299 void ReplaceText(SourceLocation Start, unsigned OrigLength,
300 StringRef Str) {
301 // If removal succeeded or warning disabled return with no warning.
302 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
303 SilenceRewriteMacroWarning)
304 return;
305
306 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
307 }
308
309 // Syntactic Rewriting.
310 void RewriteRecordBody(RecordDecl *RD);
311 void RewriteInclude();
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +0000312 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +0000313 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
314 std::string &LineString);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000315 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000316 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000317 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
318 const std::string &typedefString);
319 void RewriteImplementations();
320 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
321 ObjCImplementationDecl *IMD,
322 ObjCCategoryImplDecl *CID);
323 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
324 void RewriteImplementationDecl(Decl *Dcl);
325 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
326 ObjCMethodDecl *MDecl, std::string &ResultStr);
327 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
328 const FunctionType *&FPRetType);
329 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
330 ValueDecl *VD, bool def=false);
331 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
332 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
333 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000334 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000335 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
336 void RewriteProperty(ObjCPropertyDecl *prop);
337 void RewriteFunctionDecl(FunctionDecl *FD);
338 void RewriteBlockPointerType(std::string& Str, QualType Type);
339 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianca357d92012-04-19 00:50:01 +0000340 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000341 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
342 void RewriteTypeOfDecl(VarDecl *VD);
343 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000344
345 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000346
347 // Expression Rewriting.
348 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
349 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
350 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
351 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
352 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
353 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
354 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +0000355 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beard0caa3942012-04-19 00:25:12 +0000356 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +0000357 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000358 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000359 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000360 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +0000361 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000362 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
363 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
364 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
365 SourceLocation OrigEnd);
366 Stmt *RewriteBreakStmt(BreakStmt *S);
367 Stmt *RewriteContinueStmt(ContinueStmt *S);
368 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +0000369 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000370 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000371
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000372 // Computes ivar bitfield group no.
373 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
374 // Names field decl. for ivar bitfield group.
375 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
376 // Names struct type for ivar bitfield group.
377 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
378 // Names symbol for ivar bitfield group field offset.
379 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
380 // Given an ivar bitfield, it builds (or finds) its group record type.
381 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
382 QualType SynthesizeBitfieldGroupStructType(
383 ObjCIvarDecl *IV,
384 SmallVectorImpl<ObjCIvarDecl *> &IVars);
385
Fariborz Jahanian11671902012-02-07 17:11:38 +0000386 // Block rewriting.
387 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
388
389 // Block specific rewrite rules.
390 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian847713a2012-04-24 19:38:45 +0000391 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCall113bee02012-03-10 09:33:50 +0000392 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000393 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
394 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
395
396 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
397 std::string &Result);
398
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000399 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanian144b7222012-05-01 17:46:45 +0000400 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000401 bool &IsNamedDefinition);
402 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
403 std::string &Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000404
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +0000405 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
406
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000407 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
408 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000409
410 void Initialize(ASTContext &context) override;
411
Benjamin Kramer474261a2012-06-02 10:20:41 +0000412 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian11671902012-02-07 17:11:38 +0000413 // rewriting routines on the new ASTs.
414 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
415 Expr **args, unsigned nargs,
416 SourceLocation StartLoc=SourceLocation(),
417 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000418
419 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000420 QualType returnType,
421 SmallVectorImpl<QualType> &ArgTypes,
422 SmallVectorImpl<Expr*> &MsgExprs,
423 ObjCMethodDecl *Method);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000424
425 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
426 SourceLocation StartLoc=SourceLocation(),
427 SourceLocation EndLoc=SourceLocation());
428
429 void SynthCountByEnumWithState(std::string &buf);
430 void SynthMsgSendFunctionDecl();
431 void SynthMsgSendSuperFunctionDecl();
432 void SynthMsgSendStretFunctionDecl();
433 void SynthMsgSendFpretFunctionDecl();
434 void SynthMsgSendSuperStretFunctionDecl();
435 void SynthGetClassFunctionDecl();
436 void SynthGetMetaClassFunctionDecl();
437 void SynthGetSuperClassFunctionDecl();
438 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000439 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000440
441 // Rewriting metadata
442 template<typename MethodIterator>
443 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
444 MethodIterator MethodEnd,
445 bool IsInstanceMethod,
446 StringRef prefix,
447 StringRef ClassName,
448 std::string &Result);
Fariborz Jahaniane18961b2012-02-08 19:53:58 +0000449 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
450 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000451 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian11671902012-02-07 17:11:38 +0000452 const ObjCList<ObjCProtocolDecl> &Prots,
453 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000454 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000455 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000456 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +0000457
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000458 void RewriteMetaDataIntoBuffer(std::string &Result);
459 void WriteImageInfo(std::string &Result);
460 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000461 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000462 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000463
464 // Rewriting ivar
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000465 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000466 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000467 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000468
469
470 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
471 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
472 StringRef funcName, std::string Tag);
473 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
474 StringRef funcName, std::string Tag);
475 std::string SynthesizeBlockImpl(BlockExpr *CE,
476 std::string Tag, std::string Desc);
477 std::string SynthesizeBlockDescriptor(std::string DescTag,
478 std::string ImplTag,
479 int i, StringRef funcName,
480 unsigned hasCopy);
481 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
482 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
483 StringRef FunName);
484 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
485 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000486 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000487
488 // Misc. helper routines.
489 QualType getProtocolType();
490 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000491 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
492 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
493 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
494
495 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
496 void CollectBlockDeclRefInfo(BlockExpr *Exp);
497 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000498 void GetInnerBlockDeclRefExprs(Stmt *S,
499 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +0000500 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000501
502 // We avoid calling Type::isBlockPointerType(), since it operates on the
503 // canonical type. We only care if the top-level type is a closure pointer.
504 bool isTopLevelBlockPointerType(QualType T) {
505 return isa<BlockPointerType>(T);
506 }
507
508 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
509 /// to a function pointer type and upon success, returns true; false
510 /// otherwise.
511 bool convertBlockPointerToFunctionPointer(QualType &T) {
512 if (isTopLevelBlockPointerType(T)) {
513 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
514 T = Context->getPointerType(BPT->getPointeeType());
515 return true;
516 }
517 return false;
518 }
519
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +0000520 bool convertObjCTypeToCStyleType(QualType &T);
521
Fariborz Jahanian11671902012-02-07 17:11:38 +0000522 bool needToScanForQualifiers(QualType T);
523 QualType getSuperStructType();
524 QualType getConstantStringStructType();
525 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
526 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
527
528 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000529 if (T->isObjCQualifiedIdType()) {
530 bool isConst = T.isConstQualified();
531 T = isConst ? Context->getObjCIdType().withConst()
532 : Context->getObjCIdType();
533 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000534 else if (T->isObjCQualifiedClassType())
535 T = Context->getObjCClassType();
536 else if (T->isObjCObjectPointerType() &&
537 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
538 if (const ObjCObjectPointerType * OBJPT =
539 T->getAsObjCInterfacePointerType()) {
540 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
541 T = QualType(IFaceT, 0);
542 T = Context->getPointerType(T);
543 }
544 }
545 }
546
547 // FIXME: This predicate seems like it would be useful to add to ASTContext.
548 bool isObjCType(QualType T) {
549 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
550 return false;
551
552 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
553
554 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
555 OCT == Context->getCanonicalType(Context->getObjCClassType()))
556 return true;
557
558 if (const PointerType *PT = OCT->getAs<PointerType>()) {
559 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
560 PT->getPointeeType()->isObjCQualifiedIdType())
561 return true;
562 }
563 return false;
564 }
565 bool PointerTypeTakesAnyBlockArguments(QualType QT);
566 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
567 void GetExtentOfArgList(const char *Name, const char *&LParen,
568 const char *&RParen);
569
570 void QuoteDoublequotes(std::string &From, std::string &To) {
571 for (unsigned i = 0; i < From.length(); i++) {
572 if (From[i] == '"')
573 To += "\\\"";
574 else
575 To += From[i];
576 }
577 }
578
579 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000580 ArrayRef<QualType> args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000581 bool variadic = false) {
582 if (result == Context->getObjCInstanceType())
583 result = Context->getObjCIdType();
584 FunctionProtoType::ExtProtoInfo fpi;
585 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000586 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000587 }
588
589 // Helper function: create a CStyleCastExpr with trivial type source info.
590 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
591 CastKind Kind, Expr *E) {
592 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +0000593 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
594 TInfo, SourceLocation(), SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000595 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000596
597 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
598 IdentifierInfo* II = &Context->Idents.get("load");
599 Selector LoadSel = Context->Selectors.getSelector(0, &II);
Craig Topper8ae12032014-05-07 06:21:57 +0000600 return OD->getClassMethod(LoadSel) != nullptr;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000601 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000602
603 StringLiteral *getStringLiteral(StringRef Str) {
604 QualType StrType = Context->getConstantArrayType(
605 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
606 0);
607 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
608 /*Pascal=*/false, StrType, SourceLocation());
609 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000610 };
611
612}
613
614void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
615 NamedDecl *D) {
616 if (const FunctionProtoType *fproto
617 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +0000618 for (const auto &I : fproto->param_types())
619 if (isTopLevelBlockPointerType(I)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000620 // All the args are checked/rewritten. Don't call twice!
621 RewriteBlockPointerDecl(D);
622 break;
623 }
624 }
625}
626
627void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
628 const PointerType *PT = funcType->getAs<PointerType>();
629 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
630 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
631}
632
633static bool IsHeaderFile(const std::string &Filename) {
634 std::string::size_type DotPos = Filename.rfind('.');
635
636 if (DotPos == std::string::npos) {
637 // no file extension
638 return false;
639 }
640
641 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
642 // C header: .h
643 // C++ header: .hh or .H;
644 return Ext == "h" || Ext == "hh" || Ext == "H";
645}
646
647RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
648 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000649 bool silenceMacroWarn,
650 bool LineInfo)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000651 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000652 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000653 IsHeader = IsHeaderFile(inFile);
654 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
655 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +0000656 // FIXME. This should be an error. But if block is not called, it is OK. And it
657 // may break including some headers.
658 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
659 "rewriting block literal declared in global scope is not implemented");
660
Fariborz Jahanian11671902012-02-07 17:11:38 +0000661 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
662 DiagnosticsEngine::Warning,
663 "rewriter doesn't support user-specified control flow semantics "
664 "for @try/@finally (code may not execute properly)");
665}
666
David Blaikie6beb6aa2014-08-10 19:56:51 +0000667std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
668 const std::string &InFile, raw_ostream *OS, DiagnosticsEngine &Diags,
669 const LangOptions &LOpts, bool SilenceRewriteMacroWarning, bool LineInfo) {
670 return llvm::make_unique<RewriteModernObjC>(
671 InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000672}
673
674void RewriteModernObjC::InitializeCommon(ASTContext &context) {
675 Context = &context;
676 SM = &Context->getSourceManager();
677 TUDecl = Context->getTranslationUnitDecl();
Craig Topper8ae12032014-05-07 06:21:57 +0000678 MsgSendFunctionDecl = nullptr;
679 MsgSendSuperFunctionDecl = nullptr;
680 MsgSendStretFunctionDecl = nullptr;
681 MsgSendSuperStretFunctionDecl = nullptr;
682 MsgSendFpretFunctionDecl = nullptr;
683 GetClassFunctionDecl = nullptr;
684 GetMetaClassFunctionDecl = nullptr;
685 GetSuperClassFunctionDecl = nullptr;
686 SelGetUidFunctionDecl = nullptr;
687 CFStringFunctionDecl = nullptr;
688 ConstantStringClassReference = nullptr;
689 NSStringRecord = nullptr;
690 CurMethodDef = nullptr;
691 CurFunctionDef = nullptr;
692 GlobalVarDecl = nullptr;
693 GlobalConstructionExp = nullptr;
694 SuperStructDecl = nullptr;
695 ProtocolTypeDecl = nullptr;
696 ConstantStringDecl = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000697 BcLabelCount = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000698 SuperConstructorFunctionDecl = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000699 NumObjCStringLiterals = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000700 PropParentMap = nullptr;
701 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000702 DisableReplaceStmt = false;
703 objc_impl_method = false;
704
705 // Get the ID and start/end of the main file.
706 MainFileID = SM->getMainFileID();
707 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
708 MainFileStart = MainBuf->getBufferStart();
709 MainFileEnd = MainBuf->getBufferEnd();
710
David Blaikiebbafb8a2012-03-11 07:00:24 +0000711 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000712}
713
714//===----------------------------------------------------------------------===//
715// Top Level Driver Code
716//===----------------------------------------------------------------------===//
717
718void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
719 if (Diags.hasErrorOccurred())
720 return;
721
722 // Two cases: either the decl could be in the main file, or it could be in a
723 // #included file. If the former, rewrite it now. If the later, check to see
724 // if we rewrote the #include/#import.
725 SourceLocation Loc = D->getLocation();
726 Loc = SM->getExpansionLoc(Loc);
727
728 // If this is for a builtin, ignore it.
729 if (Loc.isInvalid()) return;
730
731 // Look for built-in declarations that we need to refer during the rewrite.
732 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
733 RewriteFunctionDecl(FD);
734 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
735 // declared in <Foundation/NSString.h>
736 if (FVD->getName() == "_NSConstantStringClassReference") {
737 ConstantStringClassReference = FVD;
738 return;
739 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000740 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
741 RewriteCategoryDecl(CD);
742 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
743 if (PD->isThisDeclarationADefinition())
744 RewriteProtocolDecl(PD);
745 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanianf264d5d2012-04-04 17:16:15 +0000746 // FIXME. This will not work in all situations and leaving it out
747 // is harmless.
748 // RewriteLinkageSpec(LSD);
749
Fariborz Jahanian11671902012-02-07 17:11:38 +0000750 // Recurse into linkage specifications
751 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
752 DIEnd = LSD->decls_end();
753 DI != DIEnd; ) {
754 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
755 if (!IFace->isThisDeclarationADefinition()) {
756 SmallVector<Decl *, 8> DG;
757 SourceLocation StartLoc = IFace->getLocStart();
758 do {
759 if (isa<ObjCInterfaceDecl>(*DI) &&
760 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
761 StartLoc == (*DI)->getLocStart())
762 DG.push_back(*DI);
763 else
764 break;
765
766 ++DI;
767 } while (DI != DIEnd);
768 RewriteForwardClassDecl(DG);
769 continue;
770 }
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000771 else {
772 // Keep track of all interface declarations seen.
773 ObjCInterfacesSeen.push_back(IFace);
774 ++DI;
775 continue;
776 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000777 }
778
779 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
780 if (!Proto->isThisDeclarationADefinition()) {
781 SmallVector<Decl *, 8> DG;
782 SourceLocation StartLoc = Proto->getLocStart();
783 do {
784 if (isa<ObjCProtocolDecl>(*DI) &&
785 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
786 StartLoc == (*DI)->getLocStart())
787 DG.push_back(*DI);
788 else
789 break;
790
791 ++DI;
792 } while (DI != DIEnd);
793 RewriteForwardProtocolDecl(DG);
794 continue;
795 }
796 }
797
798 HandleTopLevelSingleDecl(*DI);
799 ++DI;
800 }
801 }
802 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000803 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian11671902012-02-07 17:11:38 +0000804 return HandleDeclInMainFile(D);
805}
806
807//===----------------------------------------------------------------------===//
808// Syntactic (non-AST) Rewriting Code
809//===----------------------------------------------------------------------===//
810
811void RewriteModernObjC::RewriteInclude() {
812 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
813 StringRef MainBuf = SM->getBufferData(MainFileID);
814 const char *MainBufStart = MainBuf.begin();
815 const char *MainBufEnd = MainBuf.end();
816 size_t ImportLen = strlen("import");
817
818 // Loop over the whole file, looking for includes.
819 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
820 if (*BufPtr == '#') {
821 if (++BufPtr == MainBufEnd)
822 return;
823 while (*BufPtr == ' ' || *BufPtr == '\t')
824 if (++BufPtr == MainBufEnd)
825 return;
826 if (!strncmp(BufPtr, "import", ImportLen)) {
827 // replace import with include
828 SourceLocation ImportLoc =
829 LocStart.getLocWithOffset(BufPtr-MainBufStart);
830 ReplaceText(ImportLoc, ImportLen, "include");
831 BufPtr += ImportLen;
832 }
833 }
834 }
835}
836
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000837static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
838 ObjCIvarDecl *IvarDecl, std::string &Result) {
839 Result += "OBJC_IVAR_$_";
840 Result += IDecl->getName();
841 Result += "$";
842 Result += IvarDecl->getName();
843}
844
845std::string
846RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
847 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
848
849 // Build name of symbol holding ivar offset.
850 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000851 if (D->isBitField())
852 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
853 else
854 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000855
856
857 std::string S = "(*(";
858 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000859 if (D->isBitField())
860 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000861
862 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
863 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
864 RD = RD->getDefinition();
865 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
866 // decltype(((Foo_IMPL*)0)->bar) *
867 ObjCContainerDecl *CDecl =
868 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
869 // ivar in class extensions requires special treatment.
870 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
871 CDecl = CatDecl->getClassInterface();
872 std::string RecName = CDecl->getName();
873 RecName += "_IMPL";
874 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
875 SourceLocation(), SourceLocation(),
876 &Context->Idents.get(RecName.c_str()));
877 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
878 unsigned UnsignedIntSize =
879 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
880 Expr *Zero = IntegerLiteral::Create(*Context,
881 llvm::APInt(UnsignedIntSize, 0),
882 Context->UnsignedIntTy, SourceLocation());
883 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
884 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
885 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +0000886 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000887 SourceLocation(),
888 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +0000889 IvarT, nullptr,
890 /*BitWidth=*/nullptr, /*Mutable=*/true,
891 ICIS_NoInit);
892 MemberExpr *ME = new (Context)
893 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
894 FD->getType(), VK_LValue, OK_Ordinary);
895 IvarT = Context->getDecltypeType(ME, ME->getType());
896 }
897 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000898 convertObjCTypeToCStyleType(IvarT);
899 QualType castT = Context->getPointerType(IvarT);
900 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
901 S += TypeString;
902 S += ")";
903
904 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
905 S += "((char *)self + ";
906 S += IvarOffsetName;
907 S += "))";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000908 if (D->isBitField()) {
909 S += ".";
910 S += D->getNameAsString();
911 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000912 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000913 return S;
914}
915
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000916/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
917/// been found in the class implementation. In this case, it must be synthesized.
918static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
919 ObjCPropertyDecl *PD,
920 bool getter) {
921 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
922 : !IMP->getInstanceMethod(PD->getSetterName());
923
924}
925
Fariborz Jahanian11671902012-02-07 17:11:38 +0000926void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
927 ObjCImplementationDecl *IMD,
928 ObjCCategoryImplDecl *CID) {
929 static bool objcGetPropertyDefined = false;
930 static bool objcSetPropertyDefined = false;
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000931 SourceLocation startGetterSetterLoc;
932
933 if (PID->getLocStart().isValid()) {
934 SourceLocation startLoc = PID->getLocStart();
935 InsertText(startLoc, "// ");
936 const char *startBuf = SM->getCharacterData(startLoc);
937 assert((*startBuf == '@') && "bogus @synthesize location");
938 const char *semiBuf = strchr(startBuf, ';');
939 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
940 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
941 }
942 else
943 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000944
945 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
946 return; // FIXME: is this correct?
947
948 // Generate the 'getter' function.
949 ObjCPropertyDecl *PD = PID->getPropertyDecl();
950 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose755a2ff2013-03-15 21:41:35 +0000951 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000952
Bill Wendling44426052012-12-20 19:22:21 +0000953 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000954 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendling44426052012-12-20 19:22:21 +0000955 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
956 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +0000957 ObjCPropertyDecl::OBJC_PR_copy));
958 std::string Getr;
959 if (GenGetProperty && !objcGetPropertyDefined) {
960 objcGetPropertyDefined = true;
961 // FIXME. Is this attribute correct in all cases?
962 Getr = "\nextern \"C\" __declspec(dllimport) "
963 "id objc_getProperty(id, SEL, long, bool);\n";
964 }
965 RewriteObjCMethodDecl(OID->getContainingInterface(),
966 PD->getGetterMethodDecl(), Getr);
967 Getr += "{ ";
968 // Synthesize an explicit cast to gain access to the ivar.
969 // See objc-act.c:objc_synthesize_new_getter() for details.
970 if (GenGetProperty) {
971 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
972 Getr += "typedef ";
Craig Topper8ae12032014-05-07 06:21:57 +0000973 const FunctionType *FPRetType = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000974 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000975 FPRetType);
976 Getr += " _TYPE";
977 if (FPRetType) {
978 Getr += ")"; // close the precedence "scope" for "*".
979
980 // Now, emit the argument types (if any).
981 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
982 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000983 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000984 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000985 std::string ParamStr =
986 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000987 Getr += ParamStr;
988 }
989 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000990 if (FT->getNumParams())
991 Getr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +0000992 Getr += "...";
993 }
994 Getr += ")";
995 } else
996 Getr += "()";
997 }
998 Getr += ";\n";
999 Getr += "return (_TYPE)";
1000 Getr += "objc_getProperty(self, _cmd, ";
1001 RewriteIvarOffsetComputation(OID, Getr);
1002 Getr += ", 1)";
1003 }
1004 else
1005 Getr += "return " + getIvarAccessString(OID);
1006 Getr += "; }";
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001007 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001008 }
1009
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001010 if (PD->isReadOnly() ||
1011 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001012 return;
1013
1014 // Generate the 'setter' function.
1015 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +00001016 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +00001017 ObjCPropertyDecl::OBJC_PR_copy);
1018 if (GenSetProperty && !objcSetPropertyDefined) {
1019 objcSetPropertyDefined = true;
1020 // FIXME. Is this attribute correct in all cases?
1021 Setr = "\nextern \"C\" __declspec(dllimport) "
1022 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1023 }
1024
1025 RewriteObjCMethodDecl(OID->getContainingInterface(),
1026 PD->getSetterMethodDecl(), Setr);
1027 Setr += "{ ";
1028 // Synthesize an explicit cast to initialize the ivar.
1029 // See objc-act.c:objc_synthesize_new_setter() for details.
1030 if (GenSetProperty) {
1031 Setr += "objc_setProperty (self, _cmd, ";
1032 RewriteIvarOffsetComputation(OID, Setr);
1033 Setr += ", (id)";
1034 Setr += PD->getName();
1035 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +00001036 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001037 Setr += "0, ";
1038 else
1039 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +00001040 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001041 Setr += "1)";
1042 else
1043 Setr += "0)";
1044 }
1045 else {
1046 Setr += getIvarAccessString(OID) + " = ";
1047 Setr += PD->getName();
1048 }
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001049 Setr += "; }\n";
1050 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001051}
1052
1053static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1054 std::string &typedefString) {
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001055 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001056 typedefString += ForwardDecl->getNameAsString();
1057 typedefString += "\n";
1058 typedefString += "#define _REWRITER_typedef_";
1059 typedefString += ForwardDecl->getNameAsString();
1060 typedefString += "\n";
1061 typedefString += "typedef struct objc_object ";
1062 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001063 // typedef struct { } _objc_exc_Classname;
1064 typedefString += ";\ntypedef struct {} _objc_exc_";
1065 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001066 typedefString += ";\n#endif\n";
1067}
1068
1069void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1070 const std::string &typedefString) {
1071 SourceLocation startLoc = ClassDecl->getLocStart();
1072 const char *startBuf = SM->getCharacterData(startLoc);
1073 const char *semiPtr = strchr(startBuf, ';');
1074 // Replace the @class with typedefs corresponding to the classes.
1075 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1076}
1077
1078void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1079 std::string typedefString;
1080 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001081 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1082 if (I == D.begin()) {
1083 // Translate to typedef's that forward reference structs with the same name
1084 // as the class. As a convenience, we include the original declaration
1085 // as a comment.
1086 typedefString += "// @class ";
1087 typedefString += ForwardDecl->getNameAsString();
1088 typedefString += ";";
1089 }
1090 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001091 }
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001092 else
1093 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001094 }
1095 DeclGroupRef::iterator I = D.begin();
1096 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1097}
1098
1099void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper5603df42013-07-05 19:34:19 +00001100 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001101 std::string typedefString;
1102 for (unsigned i = 0; i < D.size(); i++) {
1103 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1104 if (i == 0) {
1105 typedefString += "// @class ";
1106 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001107 typedefString += ";";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001108 }
1109 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1110 }
1111 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1112}
1113
1114void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1115 // When method is a synthesized one, such as a getter/setter there is
1116 // nothing to rewrite.
1117 if (Method->isImplicit())
1118 return;
1119 SourceLocation LocStart = Method->getLocStart();
1120 SourceLocation LocEnd = Method->getLocEnd();
1121
1122 if (SM->getExpansionLineNumber(LocEnd) >
1123 SM->getExpansionLineNumber(LocStart)) {
1124 InsertText(LocStart, "#if 0\n");
1125 ReplaceText(LocEnd, 1, ";\n#endif\n");
1126 } else {
1127 InsertText(LocStart, "// ");
1128 }
1129}
1130
1131void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1132 SourceLocation Loc = prop->getAtLoc();
1133
1134 ReplaceText(Loc, 0, "// ");
1135 // FIXME: handle properties that are declared across multiple lines.
1136}
1137
1138void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1139 SourceLocation LocStart = CatDecl->getLocStart();
1140
1141 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001142 if (CatDecl->getIvarRBraceLoc().isValid()) {
1143 ReplaceText(LocStart, 1, "/** ");
1144 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1145 }
1146 else {
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001147 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001148 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +00001149
Aaron Ballmand174edf2014-03-13 19:11:50 +00001150 for (auto *I : CatDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001151 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001152
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001153 for (auto *I : CatDecl->instance_methods())
1154 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001155 for (auto *I : CatDecl->class_methods())
1156 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001157
1158 // Lastly, comment out the @end.
1159 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001160 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001161}
1162
1163void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1164 SourceLocation LocStart = PDecl->getLocStart();
1165 assert(PDecl->isThisDeclarationADefinition());
1166
1167 // FIXME: handle protocol headers that are declared across multiple lines.
1168 ReplaceText(LocStart, 0, "// ");
1169
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001170 for (auto *I : PDecl->instance_methods())
1171 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001172 for (auto *I : PDecl->class_methods())
1173 RewriteMethodDeclaration(I);
Aaron Ballmand174edf2014-03-13 19:11:50 +00001174 for (auto *I : PDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001175 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001176
1177 // Lastly, comment out the @end.
1178 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001179 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001180
1181 // Must comment out @optional/@required
1182 const char *startBuf = SM->getCharacterData(LocStart);
1183 const char *endBuf = SM->getCharacterData(LocEnd);
1184 for (const char *p = startBuf; p < endBuf; p++) {
1185 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1186 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1187 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1188
1189 }
1190 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1191 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1192 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1193
1194 }
1195 }
1196}
1197
1198void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1199 SourceLocation LocStart = (*D.begin())->getLocStart();
1200 if (LocStart.isInvalid())
1201 llvm_unreachable("Invalid SourceLocation");
1202 // FIXME: handle forward protocol that are declared across multiple lines.
1203 ReplaceText(LocStart, 0, "// ");
1204}
1205
1206void
Craig Topper5603df42013-07-05 19:34:19 +00001207RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001208 SourceLocation LocStart = DG[0]->getLocStart();
1209 if (LocStart.isInvalid())
1210 llvm_unreachable("Invalid SourceLocation");
1211 // FIXME: handle forward protocol that are declared across multiple lines.
1212 ReplaceText(LocStart, 0, "// ");
1213}
1214
Fariborz Jahanian08ed8922012-04-03 17:35:38 +00001215void
1216RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1217 SourceLocation LocStart = LSD->getExternLoc();
1218 if (LocStart.isInvalid())
1219 llvm_unreachable("Invalid extern SourceLocation");
1220
1221 ReplaceText(LocStart, 0, "// ");
1222 if (!LSD->hasBraces())
1223 return;
1224 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1225 SourceLocation LocRBrace = LSD->getRBraceLoc();
1226 if (LocRBrace.isInvalid())
1227 llvm_unreachable("Invalid rbrace SourceLocation");
1228 ReplaceText(LocRBrace, 0, "// ");
1229}
1230
Fariborz Jahanian11671902012-02-07 17:11:38 +00001231void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1232 const FunctionType *&FPRetType) {
1233 if (T->isObjCQualifiedIdType())
1234 ResultStr += "id";
1235 else if (T->isFunctionPointerType() ||
1236 T->isBlockPointerType()) {
1237 // needs special handling, since pointer-to-functions have special
1238 // syntax (where a decaration models use).
1239 QualType retType = T;
1240 QualType PointeeTy;
1241 if (const PointerType* PT = retType->getAs<PointerType>())
1242 PointeeTy = PT->getPointeeType();
1243 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1244 PointeeTy = BPT->getPointeeType();
1245 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001246 ResultStr +=
1247 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001248 ResultStr += "(*";
1249 }
1250 } else
1251 ResultStr += T.getAsString(Context->getPrintingPolicy());
1252}
1253
1254void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1255 ObjCMethodDecl *OMD,
1256 std::string &ResultStr) {
1257 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001258 const FunctionType *FPRetType = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001259 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001260 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001261 ResultStr += " ";
1262
1263 // Unique method name
1264 std::string NameStr;
1265
1266 if (OMD->isInstanceMethod())
1267 NameStr += "_I_";
1268 else
1269 NameStr += "_C_";
1270
1271 NameStr += IDecl->getNameAsString();
1272 NameStr += "_";
1273
1274 if (ObjCCategoryImplDecl *CID =
1275 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1276 NameStr += CID->getNameAsString();
1277 NameStr += "_";
1278 }
1279 // Append selector names, replacing ':' with '_'
1280 {
1281 std::string selString = OMD->getSelector().getAsString();
1282 int len = selString.size();
1283 for (int i = 0; i < len; i++)
1284 if (selString[i] == ':')
1285 selString[i] = '_';
1286 NameStr += selString;
1287 }
1288 // Remember this name for metadata emission
1289 MethodInternalNames[OMD] = NameStr;
1290 ResultStr += NameStr;
1291
1292 // Rewrite arguments
1293 ResultStr += "(";
1294
1295 // invisible arguments
1296 if (OMD->isInstanceMethod()) {
1297 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1298 selfTy = Context->getPointerType(selfTy);
1299 if (!LangOpts.MicrosoftExt) {
1300 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1301 ResultStr += "struct ";
1302 }
1303 // When rewriting for Microsoft, explicitly omit the structure name.
1304 ResultStr += IDecl->getNameAsString();
1305 ResultStr += " *";
1306 }
1307 else
1308 ResultStr += Context->getObjCClassType().getAsString(
1309 Context->getPrintingPolicy());
1310
1311 ResultStr += " self, ";
1312 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1313 ResultStr += " _cmd";
1314
1315 // Method arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00001316 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001317 ResultStr += ", ";
1318 if (PDecl->getType()->isObjCQualifiedIdType()) {
1319 ResultStr += "id ";
1320 ResultStr += PDecl->getNameAsString();
1321 } else {
1322 std::string Name = PDecl->getNameAsString();
1323 QualType QT = PDecl->getType();
1324 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001325 (void)convertBlockPointerToFunctionPointer(QT);
1326 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001327 ResultStr += Name;
1328 }
1329 }
1330 if (OMD->isVariadic())
1331 ResultStr += ", ...";
1332 ResultStr += ") ";
1333
1334 if (FPRetType) {
1335 ResultStr += ")"; // close the precedence "scope" for "*".
1336
1337 // Now, emit the argument types (if any).
1338 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1339 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001340 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001341 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001342 std::string ParamStr =
1343 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001344 ResultStr += ParamStr;
1345 }
1346 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001347 if (FT->getNumParams())
1348 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001349 ResultStr += "...";
1350 }
1351 ResultStr += ")";
1352 } else {
1353 ResultStr += "()";
1354 }
1355 }
1356}
1357void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1358 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1359 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1360
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001361 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001362 if (IMD->getIvarRBraceLoc().isValid()) {
1363 ReplaceText(IMD->getLocStart(), 1, "/** ");
1364 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001365 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001366 else {
1367 InsertText(IMD->getLocStart(), "// ");
1368 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001369 }
1370 else
1371 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001372
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001373 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001374 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001375 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1376 SourceLocation LocStart = OMD->getLocStart();
1377 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1378
1379 const char *startBuf = SM->getCharacterData(LocStart);
1380 const char *endBuf = SM->getCharacterData(LocEnd);
1381 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1382 }
1383
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001384 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001385 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001386 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1387 SourceLocation LocStart = OMD->getLocStart();
1388 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1389
1390 const char *startBuf = SM->getCharacterData(LocStart);
1391 const char *endBuf = SM->getCharacterData(LocEnd);
1392 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1393 }
Aaron Ballmand85eff42014-03-14 15:02:45 +00001394 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1395 RewritePropertyImplDecl(I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001396
1397 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1398}
1399
1400void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001401 // Do not synthesize more than once.
1402 if (ObjCSynthesizedStructs.count(ClassDecl))
1403 return;
1404 // Make sure super class's are written before current class is written.
1405 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1406 while (SuperClass) {
1407 RewriteInterfaceDecl(SuperClass);
1408 SuperClass = SuperClass->getSuperClass();
1409 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001410 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001411 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001412 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001413 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001414 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1415
Fariborz Jahanianff513382012-02-15 22:01:47 +00001416 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001417 // Mark this typedef as having been written into its c++ equivalent.
1418 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanianff513382012-02-15 22:01:47 +00001419
Aaron Ballmand174edf2014-03-13 19:11:50 +00001420 for (auto *I : ClassDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001421 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001422 for (auto *I : ClassDecl->instance_methods())
1423 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001424 for (auto *I : ClassDecl->class_methods())
1425 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001426
Fariborz Jahanianff513382012-02-15 22:01:47 +00001427 // Lastly, comment out the @end.
1428 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001429 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001430 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001431}
1432
1433Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1434 SourceRange OldRange = PseudoOp->getSourceRange();
1435
1436 // We just magically know some things about the structure of this
1437 // expression.
1438 ObjCMessageExpr *OldMsg =
1439 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1440 PseudoOp->getNumSemanticExprs() - 1));
1441
1442 // Because the rewriter doesn't allow us to rewrite rewritten code,
1443 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001444 Expr *Base;
1445 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001446 {
1447 DisableReplaceStmtScope S(*this);
1448
1449 // Rebuild the base expression if we have one.
Craig Topper8ae12032014-05-07 06:21:57 +00001450 Base = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001451 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1452 Base = OldMsg->getInstanceReceiver();
1453 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1454 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1455 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001456
1457 unsigned numArgs = OldMsg->getNumArgs();
1458 for (unsigned i = 0; i < numArgs; i++) {
1459 Expr *Arg = OldMsg->getArg(i);
1460 if (isa<OpaqueValueExpr>(Arg))
1461 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1462 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1463 Args.push_back(Arg);
1464 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001465 }
1466
1467 // TODO: avoid this copy.
1468 SmallVector<SourceLocation, 1> SelLocs;
1469 OldMsg->getSelectorLocs(SelLocs);
1470
Craig Topper8ae12032014-05-07 06:21:57 +00001471 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001472 switch (OldMsg->getReceiverKind()) {
1473 case ObjCMessageExpr::Class:
1474 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1475 OldMsg->getValueKind(),
1476 OldMsg->getLeftLoc(),
1477 OldMsg->getClassReceiverTypeInfo(),
1478 OldMsg->getSelector(),
1479 SelLocs,
1480 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001481 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001482 OldMsg->getRightLoc(),
1483 OldMsg->isImplicit());
1484 break;
1485
1486 case ObjCMessageExpr::Instance:
1487 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1488 OldMsg->getValueKind(),
1489 OldMsg->getLeftLoc(),
1490 Base,
1491 OldMsg->getSelector(),
1492 SelLocs,
1493 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001494 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001495 OldMsg->getRightLoc(),
1496 OldMsg->isImplicit());
1497 break;
1498
1499 case ObjCMessageExpr::SuperClass:
1500 case ObjCMessageExpr::SuperInstance:
1501 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1502 OldMsg->getValueKind(),
1503 OldMsg->getLeftLoc(),
1504 OldMsg->getSuperLoc(),
1505 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1506 OldMsg->getSuperType(),
1507 OldMsg->getSelector(),
1508 SelLocs,
1509 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001510 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001511 OldMsg->getRightLoc(),
1512 OldMsg->isImplicit());
1513 break;
1514 }
1515
1516 Stmt *Replacement = SynthMessageExpr(NewMsg);
1517 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1518 return Replacement;
1519}
1520
1521Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1522 SourceRange OldRange = PseudoOp->getSourceRange();
1523
1524 // We just magically know some things about the structure of this
1525 // expression.
1526 ObjCMessageExpr *OldMsg =
1527 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1528
1529 // Because the rewriter doesn't allow us to rewrite rewritten code,
1530 // we need to suppress rewriting the sub-statements.
Craig Topper8ae12032014-05-07 06:21:57 +00001531 Expr *Base = nullptr;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001532 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001533 {
1534 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001535 // Rebuild the base expression if we have one.
1536 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1537 Base = OldMsg->getInstanceReceiver();
1538 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1539 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1540 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001541 unsigned numArgs = OldMsg->getNumArgs();
1542 for (unsigned i = 0; i < numArgs; i++) {
1543 Expr *Arg = OldMsg->getArg(i);
1544 if (isa<OpaqueValueExpr>(Arg))
1545 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1546 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1547 Args.push_back(Arg);
1548 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001549 }
1550
1551 // Intentionally empty.
1552 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001553
Craig Topper8ae12032014-05-07 06:21:57 +00001554 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001555 switch (OldMsg->getReceiverKind()) {
1556 case ObjCMessageExpr::Class:
1557 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1558 OldMsg->getValueKind(),
1559 OldMsg->getLeftLoc(),
1560 OldMsg->getClassReceiverTypeInfo(),
1561 OldMsg->getSelector(),
1562 SelLocs,
1563 OldMsg->getMethodDecl(),
1564 Args,
1565 OldMsg->getRightLoc(),
1566 OldMsg->isImplicit());
1567 break;
1568
1569 case ObjCMessageExpr::Instance:
1570 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1571 OldMsg->getValueKind(),
1572 OldMsg->getLeftLoc(),
1573 Base,
1574 OldMsg->getSelector(),
1575 SelLocs,
1576 OldMsg->getMethodDecl(),
1577 Args,
1578 OldMsg->getRightLoc(),
1579 OldMsg->isImplicit());
1580 break;
1581
1582 case ObjCMessageExpr::SuperClass:
1583 case ObjCMessageExpr::SuperInstance:
1584 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1585 OldMsg->getValueKind(),
1586 OldMsg->getLeftLoc(),
1587 OldMsg->getSuperLoc(),
1588 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1589 OldMsg->getSuperType(),
1590 OldMsg->getSelector(),
1591 SelLocs,
1592 OldMsg->getMethodDecl(),
1593 Args,
1594 OldMsg->getRightLoc(),
1595 OldMsg->isImplicit());
1596 break;
1597 }
1598
1599 Stmt *Replacement = SynthMessageExpr(NewMsg);
1600 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1601 return Replacement;
1602}
1603
1604/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001605/// ((NSUInteger (*)
1606/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001607/// (void *)objc_msgSend)((id)l_collection,
1608/// sel_registerName(
1609/// "countByEnumeratingWithState:objects:count:"),
1610/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001611/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001612///
1613void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001614 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1615 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001616 buf += "\n\t\t";
1617 buf += "((id)l_collection,\n\t\t";
1618 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1619 buf += "\n\t\t";
1620 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001621 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001622}
1623
1624/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1625/// statement to exit to its outer synthesized loop.
1626///
1627Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1628 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1629 return S;
1630 // replace break with goto __break_label
1631 std::string buf;
1632
1633 SourceLocation startLoc = S->getLocStart();
1634 buf = "goto __break_label_";
1635 buf += utostr(ObjCBcLabelNo.back());
1636 ReplaceText(startLoc, strlen("break"), buf);
1637
Craig Topper8ae12032014-05-07 06:21:57 +00001638 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001639}
1640
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001641void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1642 SourceLocation Loc,
1643 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001644 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001645 LineString += "\n#line ";
1646 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1647 LineString += utostr(PLoc.getLine());
1648 LineString += " \"";
1649 LineString += Lexer::Stringify(PLoc.getFilename());
1650 LineString += "\"\n";
1651 }
1652}
1653
Fariborz Jahanian11671902012-02-07 17:11:38 +00001654/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1655/// statement to continue with its inner synthesized loop.
1656///
1657Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1658 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1659 return S;
1660 // replace continue with goto __continue_label
1661 std::string buf;
1662
1663 SourceLocation startLoc = S->getLocStart();
1664 buf = "goto __continue_label_";
1665 buf += utostr(ObjCBcLabelNo.back());
1666 ReplaceText(startLoc, strlen("continue"), buf);
1667
Craig Topper8ae12032014-05-07 06:21:57 +00001668 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001669}
1670
1671/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1672/// It rewrites:
1673/// for ( type elem in collection) { stmts; }
1674
1675/// Into:
1676/// {
1677/// type elem;
1678/// struct __objcFastEnumerationState enumState = { 0 };
1679/// id __rw_items[16];
1680/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001681/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001682/// objects:__rw_items count:16];
1683/// if (limit) {
1684/// unsigned long startMutations = *enumState.mutationsPtr;
1685/// do {
1686/// unsigned long counter = 0;
1687/// do {
1688/// if (startMutations != *enumState.mutationsPtr)
1689/// objc_enumerationMutation(l_collection);
1690/// elem = (type)enumState.itemsPtr[counter++];
1691/// stmts;
1692/// __continue_label: ;
1693/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001694/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1695/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001696/// elem = nil;
1697/// __break_label: ;
1698/// }
1699/// else
1700/// elem = nil;
1701/// }
1702///
1703Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1704 SourceLocation OrigEnd) {
1705 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1706 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1707 "ObjCForCollectionStmt Statement stack mismatch");
1708 assert(!ObjCBcLabelNo.empty() &&
1709 "ObjCForCollectionStmt - Label No stack empty");
1710
1711 SourceLocation startLoc = S->getLocStart();
1712 const char *startBuf = SM->getCharacterData(startLoc);
1713 StringRef elementName;
1714 std::string elementTypeAsString;
1715 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001716 // line directive first.
1717 SourceLocation ForEachLoc = S->getForLoc();
1718 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1719 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001720 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1721 // type elem;
1722 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1723 QualType ElementType = cast<ValueDecl>(D)->getType();
1724 if (ElementType->isObjCQualifiedIdType() ||
1725 ElementType->isObjCQualifiedInterfaceType())
1726 // Simply use 'id' for all qualified types.
1727 elementTypeAsString = "id";
1728 else
1729 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1730 buf += elementTypeAsString;
1731 buf += " ";
1732 elementName = D->getName();
1733 buf += elementName;
1734 buf += ";\n\t";
1735 }
1736 else {
1737 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1738 elementName = DR->getDecl()->getName();
1739 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1740 if (VD->getType()->isObjCQualifiedIdType() ||
1741 VD->getType()->isObjCQualifiedInterfaceType())
1742 // Simply use 'id' for all qualified types.
1743 elementTypeAsString = "id";
1744 else
1745 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1746 }
1747
1748 // struct __objcFastEnumerationState enumState = { 0 };
1749 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1750 // id __rw_items[16];
1751 buf += "id __rw_items[16];\n\t";
1752 // id l_collection = (id)
1753 buf += "id l_collection = (id)";
1754 // Find start location of 'collection' the hard way!
1755 const char *startCollectionBuf = startBuf;
1756 startCollectionBuf += 3; // skip 'for'
1757 startCollectionBuf = strchr(startCollectionBuf, '(');
1758 startCollectionBuf++; // skip '('
1759 // find 'in' and skip it.
1760 while (*startCollectionBuf != ' ' ||
1761 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1762 (*(startCollectionBuf+3) != ' ' &&
1763 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1764 startCollectionBuf++;
1765 startCollectionBuf += 3;
1766
1767 // Replace: "for (type element in" with string constructed thus far.
1768 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1769 // Replace ')' in for '(' type elem in collection ')' with ';'
1770 SourceLocation rightParenLoc = S->getRParenLoc();
1771 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1772 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1773 buf = ";\n\t";
1774
1775 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1776 // objects:__rw_items count:16];
1777 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001778 // NSUInteger limit =
1779 // ((NSUInteger (*)
1780 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001781 // (void *)objc_msgSend)((id)l_collection,
1782 // sel_registerName(
1783 // "countByEnumeratingWithState:objects:count:"),
1784 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001785 // (id *)__rw_items, (NSUInteger)16);
1786 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001787 SynthCountByEnumWithState(buf);
1788 buf += ";\n\t";
1789 /// if (limit) {
1790 /// unsigned long startMutations = *enumState.mutationsPtr;
1791 /// do {
1792 /// unsigned long counter = 0;
1793 /// do {
1794 /// if (startMutations != *enumState.mutationsPtr)
1795 /// objc_enumerationMutation(l_collection);
1796 /// elem = (type)enumState.itemsPtr[counter++];
1797 buf += "if (limit) {\n\t";
1798 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1799 buf += "do {\n\t\t";
1800 buf += "unsigned long counter = 0;\n\t\t";
1801 buf += "do {\n\t\t\t";
1802 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1803 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1804 buf += elementName;
1805 buf += " = (";
1806 buf += elementTypeAsString;
1807 buf += ")enumState.itemsPtr[counter++];";
1808 // Replace ')' in for '(' type elem in collection ')' with all of these.
1809 ReplaceText(lparenLoc, 1, buf);
1810
1811 /// __continue_label: ;
1812 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001813 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1814 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001815 /// elem = nil;
1816 /// __break_label: ;
1817 /// }
1818 /// else
1819 /// elem = nil;
1820 /// }
1821 ///
1822 buf = ";\n\t";
1823 buf += "__continue_label_";
1824 buf += utostr(ObjCBcLabelNo.back());
1825 buf += ": ;";
1826 buf += "\n\t\t";
1827 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001828 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001829 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001830 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001831 buf += elementName;
1832 buf += " = ((";
1833 buf += elementTypeAsString;
1834 buf += ")0);\n\t";
1835 buf += "__break_label_";
1836 buf += utostr(ObjCBcLabelNo.back());
1837 buf += ": ;\n\t";
1838 buf += "}\n\t";
1839 buf += "else\n\t\t";
1840 buf += elementName;
1841 buf += " = ((";
1842 buf += elementTypeAsString;
1843 buf += ")0);\n\t";
1844 buf += "}\n";
1845
1846 // Insert all these *after* the statement body.
1847 // FIXME: If this should support Obj-C++, support CXXTryStmt
1848 if (isa<CompoundStmt>(S->getBody())) {
1849 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1850 InsertText(endBodyLoc, buf);
1851 } else {
1852 /* Need to treat single statements specially. For example:
1853 *
1854 * for (A *a in b) if (stuff()) break;
1855 * for (A *a in b) xxxyy;
1856 *
1857 * The following code simply scans ahead to the semi to find the actual end.
1858 */
1859 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1860 const char *semiBuf = strchr(stmtBuf, ';');
1861 assert(semiBuf && "Can't find ';'");
1862 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1863 InsertText(endBodyLoc, buf);
1864 }
1865 Stmts.pop_back();
1866 ObjCBcLabelNo.pop_back();
Craig Topper8ae12032014-05-07 06:21:57 +00001867 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001868}
1869
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001870static void Write_RethrowObject(std::string &buf) {
1871 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1872 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1873 buf += "\tid rethrow;\n";
1874 buf += "\t} _fin_force_rethow(_rethrow);";
1875}
1876
Fariborz Jahanian11671902012-02-07 17:11:38 +00001877/// RewriteObjCSynchronizedStmt -
1878/// This routine rewrites @synchronized(expr) stmt;
1879/// into:
1880/// objc_sync_enter(expr);
1881/// @try stmt @finally { objc_sync_exit(expr); }
1882///
1883Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1884 // Get the start location and compute the semi location.
1885 SourceLocation startLoc = S->getLocStart();
1886 const char *startBuf = SM->getCharacterData(startLoc);
1887
1888 assert((*startBuf == '@') && "bogus @synchronized location");
1889
1890 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001891 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1892 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001893 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001894
Fariborz Jahanian11671902012-02-07 17:11:38 +00001895 const char *lparenBuf = startBuf;
1896 while (*lparenBuf != '(') lparenBuf++;
1897 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001898
1899 buf = "; objc_sync_enter(_sync_obj);\n";
1900 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1901 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1902 buf += "\n\tid sync_exit;";
1903 buf += "\n\t} _sync_exit(_sync_obj);\n";
1904
1905 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1906 // the sync expression is typically a message expression that's already
1907 // been rewritten! (which implies the SourceLocation's are invalid).
1908 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1909 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1910 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1911 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1912
1913 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1914 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1915 assert (*LBraceLocBuf == '{');
1916 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001917
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001918 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001919 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1920 "bogus @synchronized block");
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001921
1922 buf = "} catch (id e) {_rethrow = e;}\n";
1923 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001924 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001925 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001926
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001927 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001928
Craig Topper8ae12032014-05-07 06:21:57 +00001929 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001930}
1931
1932void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1933{
1934 // Perform a bottom up traversal of all children.
1935 for (Stmt::child_range CI = S->children(); CI; ++CI)
1936 if (*CI)
1937 WarnAboutReturnGotoStmts(*CI);
1938
1939 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1940 Diags.Report(Context->getFullLoc(S->getLocStart()),
1941 TryFinallyContainsReturnDiag);
1942 }
1943 return;
1944}
1945
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001946Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1947 SourceLocation startLoc = S->getAtLoc();
1948 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001949 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1950 "{ __AtAutoreleasePool __autoreleasepool; ");
Craig Topper8ae12032014-05-07 06:21:57 +00001951
1952 return nullptr;
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001953}
1954
Fariborz Jahanian11671902012-02-07 17:11:38 +00001955Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001956 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001957 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001958 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001959 SourceLocation TryLocation = S->getAtTryLoc();
1960 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001961
1962 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001963 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001964 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001965 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001966 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001967 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001968 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001969 // Get the start location and compute the semi location.
1970 SourceLocation startLoc = S->getLocStart();
1971 const char *startBuf = SM->getCharacterData(startLoc);
1972
1973 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001974 if (finalStmt)
1975 ReplaceText(startLoc, 1, buf);
1976 else
1977 // @try -> try
1978 ReplaceText(startLoc, 1, "");
1979
Fariborz Jahanian11671902012-02-07 17:11:38 +00001980 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1981 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001982 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001983
Fariborz Jahanian11671902012-02-07 17:11:38 +00001984 startLoc = Catch->getLocStart();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001985 bool AtRemoved = false;
1986 if (catchDecl) {
1987 QualType t = catchDecl->getType();
1988 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1989 // Should be a pointer to a class.
1990 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1991 if (IDecl) {
1992 std::string Result;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001993 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
1994
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001995 startBuf = SM->getCharacterData(startLoc);
1996 assert((*startBuf == '@') && "bogus @catch location");
1997 SourceLocation rParenLoc = Catch->getRParenLoc();
1998 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1999
2000 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002001 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002002 Result += " *_"; Result += catchDecl->getNameAsString();
2003 Result += ")";
2004 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2005 // Foo *e = (Foo *)_e;
2006 Result.clear();
2007 Result = "{ ";
2008 Result += IDecl->getNameAsString();
2009 Result += " *"; Result += catchDecl->getNameAsString();
2010 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2011 Result += "_"; Result += catchDecl->getNameAsString();
2012
2013 Result += "; ";
2014 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2015 ReplaceText(lBraceLoc, 1, Result);
2016 AtRemoved = true;
2017 }
2018 }
2019 }
2020 if (!AtRemoved)
2021 // @catch -> catch
2022 ReplaceText(startLoc, 1, "");
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002023
Fariborz Jahanian11671902012-02-07 17:11:38 +00002024 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002025 if (finalStmt) {
2026 buf.clear();
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002027 SourceLocation FinallyLoc = finalStmt->getLocStart();
2028
2029 if (noCatch) {
2030 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2031 buf += "catch (id e) {_rethrow = e;}\n";
2032 }
2033 else {
2034 buf += "}\n";
2035 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2036 buf += "catch (id e) {_rethrow = e;}\n";
2037 }
2038
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002039 SourceLocation startFinalLoc = finalStmt->getLocStart();
2040 ReplaceText(startFinalLoc, 8, buf);
2041 Stmt *body = finalStmt->getFinallyBody();
2042 SourceLocation startFinalBodyLoc = body->getLocStart();
2043 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002044 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002045 ReplaceText(startFinalBodyLoc, 1, buf);
2046
2047 SourceLocation endFinalBodyLoc = body->getLocEnd();
2048 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002049 // Now check for any return/continue/go statements within the @try.
2050 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002051 }
2052
Craig Topper8ae12032014-05-07 06:21:57 +00002053 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002054}
2055
2056// This can't be done with ReplaceStmt(S, ThrowExpr), since
2057// the throw expression is typically a message expression that's already
2058// been rewritten! (which implies the SourceLocation's are invalid).
2059Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2060 // Get the start location and compute the semi location.
2061 SourceLocation startLoc = S->getLocStart();
2062 const char *startBuf = SM->getCharacterData(startLoc);
2063
2064 assert((*startBuf == '@') && "bogus @throw location");
2065
2066 std::string buf;
2067 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2068 if (S->getThrowExpr())
2069 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002070 else
2071 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002072
2073 // handle "@ throw" correctly.
2074 const char *wBuf = strchr(startBuf, 'w');
2075 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2076 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2077
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002078 SourceLocation endLoc = S->getLocEnd();
2079 const char *endBuf = SM->getCharacterData(endLoc);
2080 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002081 assert((*semiBuf == ';') && "@throw: can't find ';'");
2082 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002083 if (S->getThrowExpr())
2084 ReplaceText(semiLoc, 1, ");");
Craig Topper8ae12032014-05-07 06:21:57 +00002085 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002086}
2087
2088Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2089 // Create a new string expression.
Fariborz Jahanian11671902012-02-07 17:11:38 +00002090 std::string StrEncoding;
2091 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002092 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002093 ReplaceStmt(Exp, Replacement);
2094
2095 // Replace this subexpr in the parent.
2096 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2097 return Replacement;
2098}
2099
2100Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2101 if (!SelGetUidFunctionDecl)
2102 SynthSelGetUidFunctionDecl();
2103 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2104 // Create a call to sel_registerName("selName").
2105 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002106 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002107 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2108 &SelExprs[0], SelExprs.size());
2109 ReplaceStmt(Exp, SelExp);
2110 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2111 return SelExp;
2112}
2113
2114CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2115 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2116 SourceLocation EndLoc) {
2117 // Get the type, we will need to reference it in a couple spots.
2118 QualType msgSendType = FD->getType();
2119
2120 // Create a reference to the objc_msgSend() declaration.
2121 DeclRefExpr *DRE =
John McCall113bee02012-03-10 09:33:50 +00002122 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002123
2124 // Now, we cast the reference to a pointer to the objc_msgSend type.
2125 QualType pToFunc = Context->getPointerType(msgSendType);
2126 ImplicitCastExpr *ICE =
2127 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
Craig Topper8ae12032014-05-07 06:21:57 +00002128 DRE, nullptr, VK_RValue);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002129
2130 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2131
2132 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002133 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian11671902012-02-07 17:11:38 +00002134 FT->getCallResultType(*Context),
2135 VK_RValue, EndLoc);
2136 return Exp;
2137}
2138
2139static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2140 const char *&startRef, const char *&endRef) {
2141 while (startBuf < endBuf) {
2142 if (*startBuf == '<')
2143 startRef = startBuf; // mark the start.
2144 if (*startBuf == '>') {
2145 if (startRef && *startRef == '<') {
2146 endRef = startBuf; // mark the end.
2147 return true;
2148 }
2149 return false;
2150 }
2151 startBuf++;
2152 }
2153 return false;
2154}
2155
2156static void scanToNextArgument(const char *&argRef) {
2157 int angle = 0;
2158 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2159 if (*argRef == '<')
2160 angle++;
2161 else if (*argRef == '>')
2162 angle--;
2163 argRef++;
2164 }
2165 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2166}
2167
2168bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2169 if (T->isObjCQualifiedIdType())
2170 return true;
2171 if (const PointerType *PT = T->getAs<PointerType>()) {
2172 if (PT->getPointeeType()->isObjCQualifiedIdType())
2173 return true;
2174 }
2175 if (T->isObjCObjectPointerType()) {
2176 T = T->getPointeeType();
2177 return T->isObjCQualifiedInterfaceType();
2178 }
2179 if (T->isArrayType()) {
2180 QualType ElemTy = Context->getBaseElementType(T);
2181 return needToScanForQualifiers(ElemTy);
2182 }
2183 return false;
2184}
2185
2186void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2187 QualType Type = E->getType();
2188 if (needToScanForQualifiers(Type)) {
2189 SourceLocation Loc, EndLoc;
2190
2191 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2192 Loc = ECE->getLParenLoc();
2193 EndLoc = ECE->getRParenLoc();
2194 } else {
2195 Loc = E->getLocStart();
2196 EndLoc = E->getLocEnd();
2197 }
2198 // This will defend against trying to rewrite synthesized expressions.
2199 if (Loc.isInvalid() || EndLoc.isInvalid())
2200 return;
2201
2202 const char *startBuf = SM->getCharacterData(Loc);
2203 const char *endBuf = SM->getCharacterData(EndLoc);
Craig Topper8ae12032014-05-07 06:21:57 +00002204 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002205 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2206 // Get the locations of the startRef, endRef.
2207 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2208 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2209 // Comment out the protocol references.
2210 InsertText(LessLoc, "/*");
2211 InsertText(GreaterLoc, "*/");
2212 }
2213 }
2214}
2215
2216void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2217 SourceLocation Loc;
2218 QualType Type;
Craig Topper8ae12032014-05-07 06:21:57 +00002219 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002220 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2221 Loc = VD->getLocation();
2222 Type = VD->getType();
2223 }
2224 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2225 Loc = FD->getLocation();
2226 // Check for ObjC 'id' and class types that have been adorned with protocol
2227 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2228 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2229 assert(funcType && "missing function type");
2230 proto = dyn_cast<FunctionProtoType>(funcType);
2231 if (!proto)
2232 return;
Alp Toker314cc812014-01-25 16:55:45 +00002233 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002234 }
2235 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2236 Loc = FD->getLocation();
2237 Type = FD->getType();
2238 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002239 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2240 Loc = TD->getLocation();
2241 Type = TD->getUnderlyingType();
2242 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002243 else
2244 return;
2245
2246 if (needToScanForQualifiers(Type)) {
2247 // Since types are unique, we need to scan the buffer.
2248
2249 const char *endBuf = SM->getCharacterData(Loc);
2250 const char *startBuf = endBuf;
2251 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2252 startBuf--; // scan backward (from the decl location) for return type.
Craig Topper8ae12032014-05-07 06:21:57 +00002253 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002254 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2255 // Get the locations of the startRef, endRef.
2256 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2257 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2258 // Comment out the protocol references.
2259 InsertText(LessLoc, "/*");
2260 InsertText(GreaterLoc, "*/");
2261 }
2262 }
2263 if (!proto)
2264 return; // most likely, was a variable
2265 // Now check arguments.
2266 const char *startBuf = SM->getCharacterData(Loc);
2267 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002268 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2269 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002270 // Since types are unique, we need to scan the buffer.
2271
2272 const char *endBuf = startBuf;
2273 // scan forward (from the decl location) for argument types.
2274 scanToNextArgument(endBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00002275 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002276 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2277 // Get the locations of the startRef, endRef.
2278 SourceLocation LessLoc =
2279 Loc.getLocWithOffset(startRef-startFuncBuf);
2280 SourceLocation GreaterLoc =
2281 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2282 // Comment out the protocol references.
2283 InsertText(LessLoc, "/*");
2284 InsertText(GreaterLoc, "*/");
2285 }
2286 startBuf = ++endBuf;
2287 }
2288 else {
2289 // If the function name is derived from a macro expansion, then the
2290 // argument buffer will not follow the name. Need to speak with Chris.
2291 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2292 startBuf++; // scan forward (from the decl location) for argument types.
2293 startBuf++;
2294 }
2295 }
2296}
2297
2298void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2299 QualType QT = ND->getType();
2300 const Type* TypePtr = QT->getAs<Type>();
2301 if (!isa<TypeOfExprType>(TypePtr))
2302 return;
2303 while (isa<TypeOfExprType>(TypePtr)) {
2304 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2305 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2306 TypePtr = QT->getAs<Type>();
2307 }
2308 // FIXME. This will not work for multiple declarators; as in:
2309 // __typeof__(a) b,c,d;
2310 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2311 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2312 const char *startBuf = SM->getCharacterData(DeclLoc);
2313 if (ND->getInit()) {
2314 std::string Name(ND->getNameAsString());
2315 TypeAsString += " " + Name + " = ";
2316 Expr *E = ND->getInit();
2317 SourceLocation startLoc;
2318 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2319 startLoc = ECE->getLParenLoc();
2320 else
2321 startLoc = E->getLocStart();
2322 startLoc = SM->getExpansionLoc(startLoc);
2323 const char *endBuf = SM->getCharacterData(startLoc);
2324 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2325 }
2326 else {
2327 SourceLocation X = ND->getLocEnd();
2328 X = SM->getExpansionLoc(X);
2329 const char *endBuf = SM->getCharacterData(X);
2330 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2331 }
2332}
2333
2334// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2335void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2336 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2337 SmallVector<QualType, 16> ArgTys;
2338 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2339 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002340 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002341 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002342 SourceLocation(),
2343 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002344 SelGetUidIdent, getFuncType,
2345 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002346}
2347
2348void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2349 // declared in <objc/objc.h>
2350 if (FD->getIdentifier() &&
2351 FD->getName() == "sel_registerName") {
2352 SelGetUidFunctionDecl = FD;
2353 return;
2354 }
2355 RewriteObjCQualifiedInterfaceTypes(FD);
2356}
2357
2358void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2359 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2360 const char *argPtr = TypeString.c_str();
2361 if (!strchr(argPtr, '^')) {
2362 Str += TypeString;
2363 return;
2364 }
2365 while (*argPtr) {
2366 Str += (*argPtr == '^' ? '*' : *argPtr);
2367 argPtr++;
2368 }
2369}
2370
2371// FIXME. Consolidate this routine with RewriteBlockPointerType.
2372void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2373 ValueDecl *VD) {
2374 QualType Type = VD->getType();
2375 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2376 const char *argPtr = TypeString.c_str();
2377 int paren = 0;
2378 while (*argPtr) {
2379 switch (*argPtr) {
2380 case '(':
2381 Str += *argPtr;
2382 paren++;
2383 break;
2384 case ')':
2385 Str += *argPtr;
2386 paren--;
2387 break;
2388 case '^':
2389 Str += '*';
2390 if (paren == 1)
2391 Str += VD->getNameAsString();
2392 break;
2393 default:
2394 Str += *argPtr;
2395 break;
2396 }
2397 argPtr++;
2398 }
2399}
2400
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002401void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2402 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2403 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2404 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2405 if (!proto)
2406 return;
Alp Toker314cc812014-01-25 16:55:45 +00002407 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002408 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2409 FdStr += " ";
2410 FdStr += FD->getName();
2411 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002412 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002413 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002414 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002415 RewriteBlockPointerType(FdStr, ArgType);
2416 if (i+1 < numArgs)
2417 FdStr += ", ";
2418 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002419 if (FD->isVariadic()) {
2420 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2421 }
2422 else
2423 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002424 InsertText(FunLocStart, FdStr);
2425}
2426
Benjamin Kramer60509af2013-09-09 14:48:42 +00002427// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2428void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2429 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002430 return;
2431 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2432 SmallVector<QualType, 16> ArgTys;
2433 QualType argT = Context->getObjCIdType();
2434 assert(!argT.isNull() && "Can't find 'id' type");
2435 ArgTys.push_back(argT);
2436 ArgTys.push_back(argT);
2437 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002438 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002439 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002440 SourceLocation(),
2441 SourceLocation(),
2442 msgSendIdent, msgSendType,
Craig Topper8ae12032014-05-07 06:21:57 +00002443 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002444}
2445
2446// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2447void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2448 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2449 SmallVector<QualType, 16> ArgTys;
2450 QualType argT = Context->getObjCIdType();
2451 assert(!argT.isNull() && "Can't find 'id' type");
2452 ArgTys.push_back(argT);
2453 argT = Context->getObjCSelType();
2454 assert(!argT.isNull() && "Can't find 'SEL' type");
2455 ArgTys.push_back(argT);
2456 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002457 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002458 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002459 SourceLocation(),
2460 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002461 msgSendIdent, msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002462 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002463}
2464
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002465// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002466void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2467 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002468 SmallVector<QualType, 2> ArgTys;
2469 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002470 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002471 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002472 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002473 SourceLocation(),
2474 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002475 msgSendIdent, msgSendType,
2476 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002477}
2478
2479// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2480void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2481 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2482 SmallVector<QualType, 16> ArgTys;
2483 QualType argT = Context->getObjCIdType();
2484 assert(!argT.isNull() && "Can't find 'id' type");
2485 ArgTys.push_back(argT);
2486 argT = Context->getObjCSelType();
2487 assert(!argT.isNull() && "Can't find 'SEL' type");
2488 ArgTys.push_back(argT);
2489 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002490 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002491 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002492 SourceLocation(),
2493 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002494 msgSendIdent, msgSendType,
2495 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002496}
2497
2498// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002499// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002500void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2501 IdentifierInfo *msgSendIdent =
2502 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002503 SmallVector<QualType, 2> ArgTys;
2504 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002505 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002506 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002507 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2508 SourceLocation(),
2509 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002510 msgSendIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002511 msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002512 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002513}
2514
2515// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2516void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2517 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2518 SmallVector<QualType, 16> ArgTys;
2519 QualType argT = Context->getObjCIdType();
2520 assert(!argT.isNull() && "Can't find 'id' type");
2521 ArgTys.push_back(argT);
2522 argT = Context->getObjCSelType();
2523 assert(!argT.isNull() && "Can't find 'SEL' type");
2524 ArgTys.push_back(argT);
2525 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002526 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002527 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002528 SourceLocation(),
2529 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002530 msgSendIdent, msgSendType,
2531 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002532}
2533
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002534// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002535void RewriteModernObjC::SynthGetClassFunctionDecl() {
2536 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2537 SmallVector<QualType, 16> ArgTys;
2538 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002539 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002540 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002541 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002542 SourceLocation(),
2543 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002544 getClassIdent, getClassType,
2545 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002546}
2547
2548// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2549void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2550 IdentifierInfo *getSuperClassIdent =
2551 &Context->Idents.get("class_getSuperclass");
2552 SmallVector<QualType, 16> ArgTys;
2553 ArgTys.push_back(Context->getObjCClassType());
2554 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002555 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002556 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2557 SourceLocation(),
2558 SourceLocation(),
2559 getSuperClassIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002560 getClassType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002561 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002562}
2563
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002564// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002565void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2566 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2567 SmallVector<QualType, 16> ArgTys;
2568 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002569 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002570 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002571 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002572 SourceLocation(),
2573 SourceLocation(),
2574 getClassIdent, getClassType,
Craig Topper8ae12032014-05-07 06:21:57 +00002575 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002576}
2577
2578Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00002579 assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002580 QualType strType = getConstantStringStructType();
2581
2582 std::string S = "__NSConstantStringImpl_";
2583
2584 std::string tmpName = InFileName;
2585 unsigned i;
2586 for (i=0; i < tmpName.length(); i++) {
2587 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002588 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002589 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002590 tmpName[i] = '_';
2591 }
2592 S += tmpName;
2593 S += "_";
2594 S += utostr(NumObjCStringLiterals++);
2595
2596 Preamble += "static __NSConstantStringImpl " + S;
2597 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2598 Preamble += "0x000007c8,"; // utf8_str
2599 // The pretty printer for StringLiteral handles escape characters properly.
2600 std::string prettyBufS;
2601 llvm::raw_string_ostream prettyBuf(prettyBufS);
Craig Topper8ae12032014-05-07 06:21:57 +00002602 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002603 Preamble += prettyBuf.str();
2604 Preamble += ",";
2605 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2606
2607 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2608 SourceLocation(), &Context->Idents.get(S),
Craig Topper8ae12032014-05-07 06:21:57 +00002609 strType, nullptr, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002610 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002611 SourceLocation());
2612 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2613 Context->getPointerType(DRE->getType()),
2614 VK_RValue, OK_Ordinary,
2615 SourceLocation());
2616 // cast to NSConstantString *
2617 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2618 CK_CPointerToObjCPointerCast, Unop);
2619 ReplaceStmt(Exp, cast);
2620 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2621 return cast;
2622}
2623
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002624Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2625 unsigned IntSize =
2626 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2627
2628 Expr *FlagExp = IntegerLiteral::Create(*Context,
2629 llvm::APInt(IntSize, Exp->getValue()),
2630 Context->IntTy, Exp->getLocation());
2631 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2632 CK_BitCast, FlagExp);
2633 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2634 cast);
2635 ReplaceStmt(Exp, PE);
2636 return PE;
2637}
2638
Patrick Beard0caa3942012-04-19 00:25:12 +00002639Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002640 // synthesize declaration of helper functions needed in this routine.
2641 if (!SelGetUidFunctionDecl)
2642 SynthSelGetUidFunctionDecl();
2643 // use objc_msgSend() for all.
2644 if (!MsgSendFunctionDecl)
2645 SynthMsgSendFunctionDecl();
2646 if (!GetClassFunctionDecl)
2647 SynthGetClassFunctionDecl();
2648
2649 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2650 SourceLocation StartLoc = Exp->getLocStart();
2651 SourceLocation EndLoc = Exp->getLocEnd();
2652
2653 // Synthesize a call to objc_msgSend().
2654 SmallVector<Expr*, 4> MsgExprs;
2655 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002656
Patrick Beard0caa3942012-04-19 00:25:12 +00002657 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2658 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2659 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002660
Patrick Beard0caa3942012-04-19 00:25:12 +00002661 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002662 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002663 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2664 &ClsExprs[0],
2665 ClsExprs.size(),
2666 StartLoc, EndLoc);
2667 MsgExprs.push_back(Cls);
2668
Patrick Beard0caa3942012-04-19 00:25:12 +00002669 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002670 // it will be the 2nd argument.
2671 SmallVector<Expr*, 4> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002672 SelExprs.push_back(
2673 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002674 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2675 &SelExprs[0], SelExprs.size(),
2676 StartLoc, EndLoc);
2677 MsgExprs.push_back(SelExp);
2678
Patrick Beard0caa3942012-04-19 00:25:12 +00002679 // User provided sub-expression is the 3rd, and last, argument.
2680 Expr *subExpr = Exp->getSubExpr();
2681 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002682 QualType type = ICE->getType();
2683 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2684 CastKind CK = CK_BitCast;
2685 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2686 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002687 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002688 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002689 MsgExprs.push_back(subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002690
2691 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002692 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002693 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002694 for (const auto PI : BoxingMethod->parameters())
2695 ArgTypes.push_back(PI->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002696
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002697 QualType returnType = Exp->getType();
2698 // Get the type, we will need to reference it in a couple spots.
2699 QualType msgSendType = MsgSendFlavor->getType();
2700
2701 // Create a reference to the objc_msgSend() declaration.
2702 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2703 VK_LValue, SourceLocation());
2704
2705 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002706 Context->getPointerType(Context->VoidTy),
2707 CK_BitCast, DRE);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002708
2709 // Now do the "normal" pointer to function cast.
2710 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002711 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002712 castType = Context->getPointerType(castType);
2713 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2714 cast);
2715
2716 // Don't forget the parens to enforce the proper binding.
2717 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2718
2719 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002720 CallExpr *CE = new (Context)
2721 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002722 ReplaceStmt(Exp, CE);
2723 return CE;
2724}
2725
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002726Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2727 // synthesize declaration of helper functions needed in this routine.
2728 if (!SelGetUidFunctionDecl)
2729 SynthSelGetUidFunctionDecl();
2730 // use objc_msgSend() for all.
2731 if (!MsgSendFunctionDecl)
2732 SynthMsgSendFunctionDecl();
2733 if (!GetClassFunctionDecl)
2734 SynthGetClassFunctionDecl();
2735
2736 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2737 SourceLocation StartLoc = Exp->getLocStart();
2738 SourceLocation EndLoc = Exp->getLocEnd();
2739
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002740 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002741 QualType IntQT = Context->IntTy;
2742 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002743 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002744 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002745 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2746 DeclRefExpr *NSArrayDRE =
2747 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2748 SourceLocation());
2749
2750 SmallVector<Expr*, 16> InitExprs;
2751 unsigned NumElements = Exp->getNumElements();
2752 unsigned UnsignedIntSize =
2753 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2754 Expr *count = IntegerLiteral::Create(*Context,
2755 llvm::APInt(UnsignedIntSize, NumElements),
2756 Context->UnsignedIntTy, SourceLocation());
2757 InitExprs.push_back(count);
2758 for (unsigned i = 0; i < NumElements; i++)
2759 InitExprs.push_back(Exp->getElement(i));
2760 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002761 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002762 NSArrayFType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002763
2764 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002765 SourceLocation(),
2766 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002767 Context->getPointerType(Context->VoidPtrTy),
2768 nullptr, /*BitWidth=*/nullptr,
2769 /*Mutable=*/true, ICIS_NoInit);
2770 MemberExpr *ArrayLiteralME = new (Context)
2771 MemberExpr(NSArrayCallExpr, false, SourceLocation(), ARRFD,
2772 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2773 QualType ConstIdT = Context->getObjCIdType().withConst();
2774 CStyleCastExpr * ArrayLiteralObjects =
2775 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002776 Context->getPointerType(ConstIdT),
2777 CK_BitCast,
2778 ArrayLiteralME);
2779
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002780 // Synthesize a call to objc_msgSend().
2781 SmallVector<Expr*, 32> MsgExprs;
2782 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002783 QualType expType = Exp->getType();
2784
2785 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2786 ObjCInterfaceDecl *Class =
2787 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2788
2789 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002790 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002791 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2792 &ClsExprs[0],
2793 ClsExprs.size(),
2794 StartLoc, EndLoc);
2795 MsgExprs.push_back(Cls);
2796
2797 // Create a call to sel_registerName("arrayWithObjects:count:").
2798 // it will be the 2nd argument.
2799 SmallVector<Expr*, 4> SelExprs;
2800 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002801 SelExprs.push_back(
2802 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002803 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2804 &SelExprs[0], SelExprs.size(),
2805 StartLoc, EndLoc);
2806 MsgExprs.push_back(SelExp);
2807
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002808 // (const id [])objects
2809 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002810
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002811 // (NSUInteger)cnt
2812 Expr *cnt = IntegerLiteral::Create(*Context,
2813 llvm::APInt(UnsignedIntSize, NumElements),
2814 Context->UnsignedIntTy, SourceLocation());
2815 MsgExprs.push_back(cnt);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002816
2817
2818 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002819 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002820 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002821 for (const auto *PI : ArrayMethod->params())
2822 ArgTypes.push_back(PI->getType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002823
2824 QualType returnType = Exp->getType();
2825 // Get the type, we will need to reference it in a couple spots.
2826 QualType msgSendType = MsgSendFlavor->getType();
2827
2828 // Create a reference to the objc_msgSend() declaration.
2829 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2830 VK_LValue, SourceLocation());
2831
2832 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2833 Context->getPointerType(Context->VoidTy),
2834 CK_BitCast, DRE);
2835
2836 // Now do the "normal" pointer to function cast.
2837 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002838 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002839 castType = Context->getPointerType(castType);
2840 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2841 cast);
2842
2843 // Don't forget the parens to enforce the proper binding.
2844 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2845
2846 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002847 CallExpr *CE = new (Context)
2848 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002849 ReplaceStmt(Exp, CE);
2850 return CE;
2851}
2852
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002853Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2854 // synthesize declaration of helper functions needed in this routine.
2855 if (!SelGetUidFunctionDecl)
2856 SynthSelGetUidFunctionDecl();
2857 // use objc_msgSend() for all.
2858 if (!MsgSendFunctionDecl)
2859 SynthMsgSendFunctionDecl();
2860 if (!GetClassFunctionDecl)
2861 SynthGetClassFunctionDecl();
2862
2863 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2864 SourceLocation StartLoc = Exp->getLocStart();
2865 SourceLocation EndLoc = Exp->getLocEnd();
2866
2867 // Build the expression: __NSContainer_literal(int, ...).arr
2868 QualType IntQT = Context->IntTy;
2869 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002870 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002871 std::string NSDictFName("__NSContainer_literal");
2872 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2873 DeclRefExpr *NSDictDRE =
2874 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2875 SourceLocation());
2876
2877 SmallVector<Expr*, 16> KeyExprs;
2878 SmallVector<Expr*, 16> ValueExprs;
2879
2880 unsigned NumElements = Exp->getNumElements();
2881 unsigned UnsignedIntSize =
2882 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2883 Expr *count = IntegerLiteral::Create(*Context,
2884 llvm::APInt(UnsignedIntSize, NumElements),
2885 Context->UnsignedIntTy, SourceLocation());
2886 KeyExprs.push_back(count);
2887 ValueExprs.push_back(count);
2888 for (unsigned i = 0; i < NumElements; i++) {
2889 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2890 KeyExprs.push_back(Element.Key);
2891 ValueExprs.push_back(Element.Value);
2892 }
2893
2894 // (const id [])objects
2895 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002896 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002897 NSDictFType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002898
2899 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002900 SourceLocation(),
2901 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002902 Context->getPointerType(Context->VoidPtrTy),
2903 nullptr, /*BitWidth=*/nullptr,
2904 /*Mutable=*/true, ICIS_NoInit);
2905 MemberExpr *DictLiteralValueME = new (Context)
2906 MemberExpr(NSValueCallExpr, false, SourceLocation(), ARRFD,
2907 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2908 QualType ConstIdT = Context->getObjCIdType().withConst();
2909 CStyleCastExpr * DictValueObjects =
2910 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002911 Context->getPointerType(ConstIdT),
2912 CK_BitCast,
2913 DictLiteralValueME);
2914 // (const id <NSCopying> [])keys
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002915 Expr *NSKeyCallExpr =
2916 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
2917 NSDictFType, VK_LValue, SourceLocation());
2918
2919 MemberExpr *DictLiteralKeyME = new (Context)
2920 MemberExpr(NSKeyCallExpr, false, SourceLocation(), ARRFD,
2921 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2922
2923 CStyleCastExpr * DictKeyObjects =
2924 NoTypeInfoCStyleCastExpr(Context,
2925 Context->getPointerType(ConstIdT),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002926 CK_BitCast,
2927 DictLiteralKeyME);
2928
2929
2930
2931 // Synthesize a call to objc_msgSend().
2932 SmallVector<Expr*, 32> MsgExprs;
2933 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002934 QualType expType = Exp->getType();
2935
2936 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2937 ObjCInterfaceDecl *Class =
2938 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2939
2940 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002941 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002942 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2943 &ClsExprs[0],
2944 ClsExprs.size(),
2945 StartLoc, EndLoc);
2946 MsgExprs.push_back(Cls);
2947
2948 // Create a call to sel_registerName("arrayWithObjects:count:").
2949 // it will be the 2nd argument.
2950 SmallVector<Expr*, 4> SelExprs;
2951 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002952 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002953 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2954 &SelExprs[0], SelExprs.size(),
2955 StartLoc, EndLoc);
2956 MsgExprs.push_back(SelExp);
2957
2958 // (const id [])objects
2959 MsgExprs.push_back(DictValueObjects);
2960
2961 // (const id <NSCopying> [])keys
2962 MsgExprs.push_back(DictKeyObjects);
2963
2964 // (NSUInteger)cnt
2965 Expr *cnt = IntegerLiteral::Create(*Context,
2966 llvm::APInt(UnsignedIntSize, NumElements),
2967 Context->UnsignedIntTy, SourceLocation());
2968 MsgExprs.push_back(cnt);
2969
2970
2971 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002972 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002973 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002974 for (const auto *PI : DictMethod->params()) {
2975 QualType T = PI->getType();
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002976 if (const PointerType* PT = T->getAs<PointerType>()) {
2977 QualType PointeeTy = PT->getPointeeType();
2978 convertToUnqualifiedObjCType(PointeeTy);
2979 T = Context->getPointerType(PointeeTy);
2980 }
2981 ArgTypes.push_back(T);
2982 }
2983
2984 QualType returnType = Exp->getType();
2985 // Get the type, we will need to reference it in a couple spots.
2986 QualType msgSendType = MsgSendFlavor->getType();
2987
2988 // Create a reference to the objc_msgSend() declaration.
2989 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2990 VK_LValue, SourceLocation());
2991
2992 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2993 Context->getPointerType(Context->VoidTy),
2994 CK_BitCast, DRE);
2995
2996 // Now do the "normal" pointer to function cast.
2997 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002998 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002999 castType = Context->getPointerType(castType);
3000 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3001 cast);
3002
3003 // Don't forget the parens to enforce the proper binding.
3004 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3005
3006 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003007 CallExpr *CE = new (Context)
3008 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003009 ReplaceStmt(Exp, CE);
3010 return CE;
3011}
3012
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003013// struct __rw_objc_super {
3014// struct objc_object *object; struct objc_object *superClass;
3015// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00003016QualType RewriteModernObjC::getSuperStructType() {
3017 if (!SuperStructDecl) {
3018 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3019 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003020 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003021 QualType FieldTypes[2];
3022
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003023 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003024 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003025 // struct objc_object *superClass;
3026 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003027
3028 // Create fields
3029 for (unsigned i = 0; i < 2; ++i) {
3030 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3031 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003032 SourceLocation(), nullptr,
3033 FieldTypes[i], nullptr,
3034 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003035 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003036 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003037 }
3038
3039 SuperStructDecl->completeDefinition();
3040 }
3041 return Context->getTagDeclType(SuperStructDecl);
3042}
3043
3044QualType RewriteModernObjC::getConstantStringStructType() {
3045 if (!ConstantStringDecl) {
3046 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3047 SourceLocation(), SourceLocation(),
3048 &Context->Idents.get("__NSConstantStringImpl"));
3049 QualType FieldTypes[4];
3050
3051 // struct objc_object *receiver;
3052 FieldTypes[0] = Context->getObjCIdType();
3053 // int flags;
3054 FieldTypes[1] = Context->IntTy;
3055 // char *str;
3056 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3057 // long length;
3058 FieldTypes[3] = Context->LongTy;
3059
3060 // Create fields
3061 for (unsigned i = 0; i < 4; ++i) {
3062 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3063 ConstantStringDecl,
3064 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003065 SourceLocation(), nullptr,
3066 FieldTypes[i], nullptr,
3067 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003068 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003069 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003070 }
3071
3072 ConstantStringDecl->completeDefinition();
3073 }
3074 return Context->getTagDeclType(ConstantStringDecl);
3075}
3076
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003077/// getFunctionSourceLocation - returns start location of a function
3078/// definition. Complication arises when function has declared as
3079/// extern "C" or extern "C" {...}
3080static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3081 FunctionDecl *FD) {
3082 if (FD->isExternC() && !FD->isMain()) {
3083 const DeclContext *DC = FD->getDeclContext();
3084 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3085 // if it is extern "C" {...}, return function decl's own location.
3086 if (!LSD->getRBraceLoc().isValid())
3087 return LSD->getExternLoc();
3088 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003089 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003090 R.RewriteBlockLiteralFunctionDecl(FD);
3091 return FD->getTypeSpecStartLoc();
3092}
3093
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003094void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3095
3096 SourceLocation Location = D->getLocation();
3097
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003098 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003099 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003100 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3101 LineString += utostr(PLoc.getLine());
3102 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003103 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003104 if (isa<ObjCMethodDecl>(D))
3105 LineString += "\"";
3106 else LineString += "\"\n";
3107
3108 Location = D->getLocStart();
3109 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3110 if (FD->isExternC() && !FD->isMain()) {
3111 const DeclContext *DC = FD->getDeclContext();
3112 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3113 // if it is extern "C" {...}, return function decl's own location.
3114 if (!LSD->getRBraceLoc().isValid())
3115 Location = LSD->getExternLoc();
3116 }
3117 }
3118 InsertText(Location, LineString);
3119 }
3120}
3121
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003122/// SynthMsgSendStretCallExpr - This routine translates message expression
3123/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3124/// nil check on receiver must be performed before calling objc_msgSend_stret.
3125/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3126/// msgSendType - function type of objc_msgSend_stret(...)
3127/// returnType - Result type of the method being synthesized.
3128/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3129/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3130/// starting with receiver.
3131/// Method - Method being rewritten.
3132Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003133 QualType returnType,
3134 SmallVectorImpl<QualType> &ArgTypes,
3135 SmallVectorImpl<Expr*> &MsgExprs,
3136 ObjCMethodDecl *Method) {
3137 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003138 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3139 Method ? Method->isVariadic()
3140 : false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003141 castType = Context->getPointerType(castType);
3142
3143 // build type for containing the objc_msgSend_stret object.
3144 static unsigned stretCount=0;
3145 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003146 std::string str =
3147 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003148 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003149 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003150 str += " {\n\t";
3151 str += name;
3152 str += "(id receiver, SEL sel";
3153 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003154 std::string ArgName = "arg"; ArgName += utostr(i);
3155 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3156 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003157 }
3158 // could be vararg.
3159 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003160 std::string ArgName = "arg"; ArgName += utostr(i);
3161 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3162 Context->getPrintingPolicy());
3163 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003164 }
3165
3166 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003167 str += "\t unsigned size = sizeof(";
3168 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3169
3170 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3171
3172 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3173 str += ")(void *)objc_msgSend)(receiver, sel";
3174 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3175 str += ", arg"; str += utostr(i);
3176 }
3177 // could be vararg.
3178 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3179 str += ", arg"; str += utostr(i);
3180 }
3181 str+= ");\n";
3182
3183 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003184 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3185 str += "\t else\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003186
3187
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003188 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3189 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3190 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3191 str += ", arg"; str += utostr(i);
3192 }
3193 // could be vararg.
3194 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3195 str += ", arg"; str += utostr(i);
3196 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003197 str += ");\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003198
3199
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003200 str += "\t}\n";
3201 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3202 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003203 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003204 SourceLocation FunLocStart;
3205 if (CurFunctionDef)
3206 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3207 else {
3208 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3209 FunLocStart = CurMethodDef->getLocStart();
3210 }
3211
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003212 InsertText(FunLocStart, str);
3213 ++stretCount;
3214
3215 // AST for __Stretn(receiver, args).s;
3216 IdentifierInfo *ID = &Context->Idents.get(name);
3217 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003218 SourceLocation(), ID, castType,
3219 nullptr, SC_Extern, false, false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003220 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3221 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003222 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003223 castType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00003224
3225 FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003226 SourceLocation(),
3227 &Context->Idents.get("s"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00003228 returnType, nullptr,
3229 /*BitWidth=*/nullptr,
3230 /*Mutable=*/true, ICIS_NoInit);
3231 MemberExpr *ME = new (Context)
3232 MemberExpr(STCE, false, SourceLocation(), FieldD, SourceLocation(),
3233 FieldD->getType(), VK_LValue, OK_Ordinary);
3234
3235 return ME;
3236}
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003237
Fariborz Jahanian11671902012-02-07 17:11:38 +00003238Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3239 SourceLocation StartLoc,
3240 SourceLocation EndLoc) {
3241 if (!SelGetUidFunctionDecl)
3242 SynthSelGetUidFunctionDecl();
3243 if (!MsgSendFunctionDecl)
3244 SynthMsgSendFunctionDecl();
3245 if (!MsgSendSuperFunctionDecl)
3246 SynthMsgSendSuperFunctionDecl();
3247 if (!MsgSendStretFunctionDecl)
3248 SynthMsgSendStretFunctionDecl();
3249 if (!MsgSendSuperStretFunctionDecl)
3250 SynthMsgSendSuperStretFunctionDecl();
3251 if (!MsgSendFpretFunctionDecl)
3252 SynthMsgSendFpretFunctionDecl();
3253 if (!GetClassFunctionDecl)
3254 SynthGetClassFunctionDecl();
3255 if (!GetSuperClassFunctionDecl)
3256 SynthGetSuperClassFunctionDecl();
3257 if (!GetMetaClassFunctionDecl)
3258 SynthGetMetaClassFunctionDecl();
3259
3260 // default to objc_msgSend().
3261 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3262 // May need to use objc_msgSend_stret() as well.
Craig Topper8ae12032014-05-07 06:21:57 +00003263 FunctionDecl *MsgSendStretFlavor = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003264 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003265 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003266 if (resultType->isRecordType())
3267 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3268 else if (resultType->isRealFloatingType())
3269 MsgSendFlavor = MsgSendFpretFunctionDecl;
3270 }
3271
3272 // Synthesize a call to objc_msgSend().
3273 SmallVector<Expr*, 8> MsgExprs;
3274 switch (Exp->getReceiverKind()) {
3275 case ObjCMessageExpr::SuperClass: {
3276 MsgSendFlavor = MsgSendSuperFunctionDecl;
3277 if (MsgSendStretFlavor)
3278 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3279 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3280
3281 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3282
3283 SmallVector<Expr*, 4> InitExprs;
3284
3285 // set the receiver to self, the first argument to all methods.
3286 InitExprs.push_back(
3287 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3288 CK_BitCast,
3289 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003290 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003291 Context->getObjCIdType(),
3292 VK_RValue,
3293 SourceLocation()))
3294 ); // set the 'receiver'.
3295
3296 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3297 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003298 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003299 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003300 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3301 &ClsExprs[0],
3302 ClsExprs.size(),
3303 StartLoc,
3304 EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003305 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003306 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003307 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3308 &ClsExprs[0], ClsExprs.size(),
3309 StartLoc, EndLoc);
3310
3311 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3312 // To turn off a warning, type-cast to 'id'
3313 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3314 NoTypeInfoCStyleCastExpr(Context,
3315 Context->getObjCIdType(),
3316 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003317 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003318 QualType superType = getSuperStructType();
3319 Expr *SuperRep;
3320
3321 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003322 SynthSuperConstructorFunctionDecl();
3323 // Simulate a constructor call...
3324 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003325 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003326 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003327 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003328 superType, VK_LValue,
3329 SourceLocation());
3330 // The code for super is a little tricky to prevent collision with
3331 // the structure definition in the header. The rewriter has it's own
3332 // internal definition (__rw_objc_super) that is uses. This is why
3333 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003334 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003335 //
3336 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3337 Context->getPointerType(SuperRep->getType()),
3338 VK_RValue, OK_Ordinary,
3339 SourceLocation());
3340 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3341 Context->getPointerType(superType),
3342 CK_BitCast, SuperRep);
3343 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003344 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003345 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003346 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003347 SourceLocation());
3348 TypeSourceInfo *superTInfo
3349 = Context->getTrivialTypeSourceInfo(superType);
3350 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3351 superType, VK_LValue,
3352 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003353 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003354 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3355 Context->getPointerType(SuperRep->getType()),
3356 VK_RValue, OK_Ordinary,
3357 SourceLocation());
3358 }
3359 MsgExprs.push_back(SuperRep);
3360 break;
3361 }
3362
3363 case ObjCMessageExpr::Class: {
3364 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003365 ObjCInterfaceDecl *Class
3366 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3367 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003368 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003369 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3370 &ClsExprs[0],
3371 ClsExprs.size(),
3372 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003373 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3374 Context->getObjCIdType(),
3375 CK_BitCast, Cls);
3376 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003377 break;
3378 }
3379
3380 case ObjCMessageExpr::SuperInstance:{
3381 MsgSendFlavor = MsgSendSuperFunctionDecl;
3382 if (MsgSendStretFlavor)
3383 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3384 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3385 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3386 SmallVector<Expr*, 4> InitExprs;
3387
3388 InitExprs.push_back(
3389 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3390 CK_BitCast,
3391 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003392 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003393 Context->getObjCIdType(),
3394 VK_RValue, SourceLocation()))
3395 ); // set the 'receiver'.
3396
3397 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3398 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003399 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003400 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003401 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3402 &ClsExprs[0],
3403 ClsExprs.size(),
3404 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003405 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003406 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003407 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3408 &ClsExprs[0], ClsExprs.size(),
3409 StartLoc, EndLoc);
3410
3411 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3412 // To turn off a warning, type-cast to 'id'
3413 InitExprs.push_back(
3414 // set 'super class', using class_getSuperclass().
3415 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3416 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003417 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003418 QualType superType = getSuperStructType();
3419 Expr *SuperRep;
3420
3421 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003422 SynthSuperConstructorFunctionDecl();
3423 // Simulate a constructor call...
3424 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003425 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003426 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003427 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003428 superType, VK_LValue, SourceLocation());
3429 // The code for super is a little tricky to prevent collision with
3430 // the structure definition in the header. The rewriter has it's own
3431 // internal definition (__rw_objc_super) that is uses. This is why
3432 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003433 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003434 //
3435 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3436 Context->getPointerType(SuperRep->getType()),
3437 VK_RValue, OK_Ordinary,
3438 SourceLocation());
3439 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3440 Context->getPointerType(superType),
3441 CK_BitCast, SuperRep);
3442 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003443 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003444 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003445 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003446 SourceLocation());
3447 TypeSourceInfo *superTInfo
3448 = Context->getTrivialTypeSourceInfo(superType);
3449 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3450 superType, VK_RValue, ILE,
3451 false);
3452 }
3453 MsgExprs.push_back(SuperRep);
3454 break;
3455 }
3456
3457 case ObjCMessageExpr::Instance: {
3458 // Remove all type-casts because it may contain objc-style types; e.g.
3459 // Foo<Proto> *.
3460 Expr *recExpr = Exp->getInstanceReceiver();
3461 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3462 recExpr = CE->getSubExpr();
3463 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3464 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3465 ? CK_BlockPointerToObjCPointerCast
3466 : CK_CPointerToObjCPointerCast;
3467
3468 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3469 CK, recExpr);
3470 MsgExprs.push_back(recExpr);
3471 break;
3472 }
3473 }
3474
3475 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3476 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003477 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003478 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3479 &SelExprs[0], SelExprs.size(),
3480 StartLoc,
3481 EndLoc);
3482 MsgExprs.push_back(SelExp);
3483
3484 // Now push any user supplied arguments.
3485 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3486 Expr *userExpr = Exp->getArg(i);
3487 // Make all implicit casts explicit...ICE comes in handy:-)
3488 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3489 // Reuse the ICE type, it is exactly what the doctor ordered.
3490 QualType type = ICE->getType();
3491 if (needToScanForQualifiers(type))
3492 type = Context->getObjCIdType();
3493 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3494 (void)convertBlockPointerToFunctionPointer(type);
3495 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3496 CastKind CK;
3497 if (SubExpr->getType()->isIntegralType(*Context) &&
3498 type->isBooleanType()) {
3499 CK = CK_IntegralToBoolean;
3500 } else if (type->isObjCObjectPointerType()) {
3501 if (SubExpr->getType()->isBlockPointerType()) {
3502 CK = CK_BlockPointerToObjCPointerCast;
3503 } else if (SubExpr->getType()->isPointerType()) {
3504 CK = CK_CPointerToObjCPointerCast;
3505 } else {
3506 CK = CK_BitCast;
3507 }
3508 } else {
3509 CK = CK_BitCast;
3510 }
3511
3512 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3513 }
3514 // Make id<P...> cast into an 'id' cast.
3515 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3516 if (CE->getType()->isObjCQualifiedIdType()) {
3517 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3518 userExpr = CE->getSubExpr();
3519 CastKind CK;
3520 if (userExpr->getType()->isIntegralType(*Context)) {
3521 CK = CK_IntegralToPointer;
3522 } else if (userExpr->getType()->isBlockPointerType()) {
3523 CK = CK_BlockPointerToObjCPointerCast;
3524 } else if (userExpr->getType()->isPointerType()) {
3525 CK = CK_CPointerToObjCPointerCast;
3526 } else {
3527 CK = CK_BitCast;
3528 }
3529 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3530 CK, userExpr);
3531 }
3532 }
3533 MsgExprs.push_back(userExpr);
3534 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3535 // out the argument in the original expression (since we aren't deleting
3536 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3537 //Exp->setArg(i, 0);
3538 }
3539 // Generate the funky cast.
3540 CastExpr *cast;
3541 SmallVector<QualType, 8> ArgTypes;
3542 QualType returnType;
3543
3544 // Push 'id' and 'SEL', the 2 implicit arguments.
3545 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3546 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3547 else
3548 ArgTypes.push_back(Context->getObjCIdType());
3549 ArgTypes.push_back(Context->getObjCSelType());
3550 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3551 // Push any user argument types.
Aaron Ballman43b68be2014-03-07 17:50:17 +00003552 for (const auto *PI : OMD->params()) {
3553 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian11671902012-02-07 17:11:38 +00003554 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00003555 : PI->getType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003556 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3557 (void)convertBlockPointerToFunctionPointer(t);
3558 ArgTypes.push_back(t);
3559 }
3560 returnType = Exp->getType();
3561 convertToUnqualifiedObjCType(returnType);
3562 (void)convertBlockPointerToFunctionPointer(returnType);
3563 } else {
3564 returnType = Context->getObjCIdType();
3565 }
3566 // Get the type, we will need to reference it in a couple spots.
3567 QualType msgSendType = MsgSendFlavor->getType();
3568
3569 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003570 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003571 VK_LValue, SourceLocation());
3572
3573 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3574 // If we don't do this cast, we get the following bizarre warning/note:
3575 // xx.m:13: warning: function called through a non-compatible type
3576 // xx.m:13: note: if this code is reached, the program will abort
3577 cast = NoTypeInfoCStyleCastExpr(Context,
3578 Context->getPointerType(Context->VoidTy),
3579 CK_BitCast, DRE);
3580
3581 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003582 // If we don't have a method decl, force a variadic cast.
3583 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003584 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003585 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003586 castType = Context->getPointerType(castType);
3587 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3588 cast);
3589
3590 // Don't forget the parens to enforce the proper binding.
3591 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3592
3593 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003594 CallExpr *CE = new (Context)
3595 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003596 Stmt *ReplacingStmt = CE;
3597 if (MsgSendStretFlavor) {
3598 // We have the method which returns a struct/union. Must also generate
3599 // call to objc_msgSend_stret and hang both varieties on a conditional
3600 // expression which dictate which one to envoke depending on size of
3601 // method's return type.
3602
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003603 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3604 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003605 ArgTypes, MsgExprs,
3606 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003607 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003608 }
3609 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3610 return ReplacingStmt;
3611}
3612
3613Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3614 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3615 Exp->getLocEnd());
3616
3617 // Now do the actual rewrite.
3618 ReplaceStmt(Exp, ReplacingStmt);
3619
3620 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3621 return ReplacingStmt;
3622}
3623
3624// typedef struct objc_object Protocol;
3625QualType RewriteModernObjC::getProtocolType() {
3626 if (!ProtocolTypeDecl) {
3627 TypeSourceInfo *TInfo
3628 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3629 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3630 SourceLocation(), SourceLocation(),
3631 &Context->Idents.get("Protocol"),
3632 TInfo);
3633 }
3634 return Context->getTypeDeclType(ProtocolTypeDecl);
3635}
3636
3637/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3638/// a synthesized/forward data reference (to the protocol's metadata).
3639/// The forward references (and metadata) are generated in
3640/// RewriteModernObjC::HandleTranslationUnit().
3641Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003642 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3643 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003644 IdentifierInfo *ID = &Context->Idents.get(Name);
3645 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003646 SourceLocation(), ID, getProtocolType(),
3647 nullptr, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003648 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3649 VK_LValue, SourceLocation());
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003650 CastExpr *castExpr =
3651 NoTypeInfoCStyleCastExpr(
3652 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003653 ReplaceStmt(Exp, castExpr);
3654 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3655 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3656 return castExpr;
3657
3658}
3659
3660bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3661 const char *endBuf) {
3662 while (startBuf < endBuf) {
3663 if (*startBuf == '#') {
3664 // Skip whitespace.
3665 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3666 ;
3667 if (!strncmp(startBuf, "if", strlen("if")) ||
3668 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3669 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3670 !strncmp(startBuf, "define", strlen("define")) ||
3671 !strncmp(startBuf, "undef", strlen("undef")) ||
3672 !strncmp(startBuf, "else", strlen("else")) ||
3673 !strncmp(startBuf, "elif", strlen("elif")) ||
3674 !strncmp(startBuf, "endif", strlen("endif")) ||
3675 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3676 !strncmp(startBuf, "include", strlen("include")) ||
3677 !strncmp(startBuf, "import", strlen("import")) ||
3678 !strncmp(startBuf, "include_next", strlen("include_next")))
3679 return true;
3680 }
3681 startBuf++;
3682 }
3683 return false;
3684}
3685
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003686/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3687/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003688bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003689 TagDecl *Tag,
3690 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003691 if (!IDecl)
3692 return false;
3693 SourceLocation TagLocation;
3694 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3695 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003696 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003697 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003698 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003699 TagLocation = RD->getLocation();
3700 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003701 IDecl->getLocation(), TagLocation);
3702 }
3703 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3704 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3705 return false;
3706 IsNamedDefinition = true;
3707 TagLocation = ED->getLocation();
3708 return Context->getSourceManager().isBeforeInTranslationUnit(
3709 IDecl->getLocation(), TagLocation);
3710
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003711 }
3712 return false;
3713}
3714
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003715/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003716/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003717bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3718 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003719 if (isa<TypedefType>(Type)) {
3720 Result += "\t";
3721 return false;
3722 }
3723
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003724 if (Type->isArrayType()) {
3725 QualType ElemTy = Context->getBaseElementType(Type);
3726 return RewriteObjCFieldDeclType(ElemTy, Result);
3727 }
3728 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003729 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3730 if (RD->isCompleteDefinition()) {
3731 if (RD->isStruct())
3732 Result += "\n\tstruct ";
3733 else if (RD->isUnion())
3734 Result += "\n\tunion ";
3735 else
3736 assert(false && "class not allowed as an ivar type");
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003737
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003738 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003739 if (GlobalDefinedTags.count(RD)) {
3740 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003741 Result += " ";
3742 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003743 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003744 Result += " {\n";
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003745 for (auto *FD : RD->fields())
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003746 RewriteObjCFieldDecl(FD, Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003747 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003748 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003749 }
3750 }
3751 else if (Type->isEnumeralType()) {
3752 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3753 if (ED->isCompleteDefinition()) {
3754 Result += "\n\tenum ";
3755 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003756 if (GlobalDefinedTags.count(ED)) {
3757 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003758 Result += " ";
3759 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003760 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003761
3762 Result += " {\n";
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003763 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003764 Result += "\t"; Result += EC->getName(); Result += " = ";
3765 llvm::APSInt Val = EC->getInitVal();
3766 Result += Val.toString(10);
3767 Result += ",\n";
3768 }
3769 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003770 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003771 }
3772 }
3773
3774 Result += "\t";
3775 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003776 return false;
3777}
3778
3779
3780/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3781/// It handles elaborated types, as well as enum types in the process.
3782void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3783 std::string &Result) {
3784 QualType Type = fieldDecl->getType();
3785 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003786
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003787 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3788 if (!EleboratedType)
3789 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003790 Result += Name;
3791 if (fieldDecl->isBitField()) {
3792 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3793 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003794 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003795 const ArrayType *AT = Context->getAsArrayType(Type);
3796 do {
3797 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003798 Result += "[";
3799 llvm::APInt Dim = CAT->getSize();
3800 Result += utostr(Dim.getZExtValue());
3801 Result += "]";
3802 }
Eli Friedman07bab732012-12-13 01:43:21 +00003803 AT = Context->getAsArrayType(AT->getElementType());
3804 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003805 }
3806
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003807 Result += ";\n";
3808}
3809
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003810/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3811/// named aggregate types into the input buffer.
3812void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3813 std::string &Result) {
3814 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003815 if (isa<TypedefType>(Type))
3816 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003817 if (Type->isArrayType())
3818 Type = Context->getBaseElementType(Type);
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003819 ObjCContainerDecl *IDecl =
3820 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Craig Topper8ae12032014-05-07 06:21:57 +00003821
3822 TagDecl *TD = nullptr;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003823 if (Type->isRecordType()) {
3824 TD = Type->getAs<RecordType>()->getDecl();
3825 }
3826 else if (Type->isEnumeralType()) {
3827 TD = Type->getAs<EnumType>()->getDecl();
3828 }
3829
3830 if (TD) {
3831 if (GlobalDefinedTags.count(TD))
3832 return;
3833
3834 bool IsNamedDefinition = false;
3835 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3836 RewriteObjCFieldDeclType(Type, Result);
3837 Result += ";";
3838 }
3839 if (IsNamedDefinition)
3840 GlobalDefinedTags.insert(TD);
3841 }
3842
3843}
3844
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003845unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3846 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3847 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3848 return IvarGroupNumber[IV];
3849 }
3850 unsigned GroupNo = 0;
3851 SmallVector<const ObjCIvarDecl *, 8> IVars;
3852 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3853 IVD; IVD = IVD->getNextIvar())
3854 IVars.push_back(IVD);
3855
3856 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3857 if (IVars[i]->isBitField()) {
3858 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3859 while (i < e && IVars[i]->isBitField())
3860 IvarGroupNumber[IVars[i++]] = GroupNo;
3861 if (i < e)
3862 --i;
3863 }
3864
3865 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3866 return IvarGroupNumber[IV];
3867}
3868
3869QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3870 ObjCIvarDecl *IV,
3871 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3872 std::string StructTagName;
3873 ObjCIvarBitfieldGroupType(IV, StructTagName);
3874 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3875 Context->getTranslationUnitDecl(),
3876 SourceLocation(), SourceLocation(),
3877 &Context->Idents.get(StructTagName));
3878 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3879 ObjCIvarDecl *Ivar = IVars[i];
3880 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3881 &Context->Idents.get(Ivar->getName()),
3882 Ivar->getType(),
Craig Topper8ae12032014-05-07 06:21:57 +00003883 nullptr, /*Expr *BW */Ivar->getBitWidth(),
3884 false, ICIS_NoInit));
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003885 }
3886 RD->completeDefinition();
3887 return Context->getTagDeclType(RD);
3888}
3889
3890QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3891 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3892 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3893 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3894 if (GroupRecordType.count(tuple))
3895 return GroupRecordType[tuple];
3896
3897 SmallVector<ObjCIvarDecl *, 8> IVars;
3898 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3899 IVD; IVD = IVD->getNextIvar()) {
3900 if (IVD->isBitField())
3901 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3902 else {
3903 if (!IVars.empty()) {
3904 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3905 // Generate the struct type for this group of bitfield ivars.
3906 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3907 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3908 IVars.clear();
3909 }
3910 }
3911 }
3912 if (!IVars.empty()) {
3913 // Do the last one.
3914 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3915 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3916 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3917 }
3918 QualType RetQT = GroupRecordType[tuple];
3919 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3920
3921 return RetQT;
3922}
3923
3924/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3925/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3926void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3927 std::string &Result) {
3928 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3929 Result += CDecl->getName();
3930 Result += "__GRBF_";
3931 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3932 Result += utostr(GroupNo);
3933 return;
3934}
3935
3936/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3937/// Name of the struct would be: classname__T_n where n is the group number for
3938/// this ivar.
3939void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3940 std::string &Result) {
3941 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3942 Result += CDecl->getName();
3943 Result += "__T_";
3944 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3945 Result += utostr(GroupNo);
3946 return;
3947}
3948
3949/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3950/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3951/// this ivar.
3952void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3953 std::string &Result) {
3954 Result += "OBJC_IVAR_$_";
3955 ObjCIvarBitfieldGroupDecl(IV, Result);
3956}
3957
3958#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3959 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3960 ++IX; \
3961 if (IX < ENDIX) \
3962 --IX; \
3963}
3964
Fariborz Jahanian11671902012-02-07 17:11:38 +00003965/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3966/// an objective-c class with ivars.
3967void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3968 std::string &Result) {
3969 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3970 assert(CDecl->getName() != "" &&
3971 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003972 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003973 SmallVector<ObjCIvarDecl *, 8> IVars;
3974 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003975 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003976 IVars.push_back(IVD);
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003977
Fariborz Jahanian11671902012-02-07 17:11:38 +00003978 SourceLocation LocStart = CDecl->getLocStart();
3979 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003980
Fariborz Jahanian11671902012-02-07 17:11:38 +00003981 const char *startBuf = SM->getCharacterData(LocStart);
3982 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003983
Fariborz Jahanian11671902012-02-07 17:11:38 +00003984 // If no ivars and no root or if its root, directly or indirectly,
3985 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003986 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00003987 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3988 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3989 ReplaceText(LocStart, endBuf-startBuf, Result);
3990 return;
3991 }
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003992
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003993 // Insert named struct/union definitions inside class to
3994 // outer scope. This follows semantics of locally defined
3995 // struct/unions in objective-c classes.
3996 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3997 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003998
3999 // Insert named structs which are syntheized to group ivar bitfields
4000 // to outer scope as well.
4001 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4002 if (IVars[i]->isBitField()) {
4003 ObjCIvarDecl *IV = IVars[i];
4004 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4005 RewriteObjCFieldDeclType(QT, Result);
4006 Result += ";";
4007 // skip over ivar bitfields in this group.
4008 SKIP_BITFIELDS(i , e, IVars);
4009 }
4010
Fariborz Jahanian11671902012-02-07 17:11:38 +00004011 Result += "\nstruct ";
4012 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004013 Result += "_IMPL {\n";
4014
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004015 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004016 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4017 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4018 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004019 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004020
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004021 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4022 if (IVars[i]->isBitField()) {
4023 ObjCIvarDecl *IV = IVars[i];
4024 Result += "\tstruct ";
4025 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4026 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4027 // skip over ivar bitfields in this group.
4028 SKIP_BITFIELDS(i , e, IVars);
4029 }
4030 else
4031 RewriteObjCFieldDecl(IVars[i], Result);
4032 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00004033
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004034 Result += "};\n";
4035 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4036 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004037 // Mark this struct as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00004038 if (!ObjCSynthesizedStructs.insert(CDecl).second)
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004039 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004040}
4041
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004042/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4043/// have been referenced in an ivar access expression.
4044void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4045 std::string &Result) {
4046 // write out ivar offset symbols which have been referenced in an ivar
4047 // access expression.
4048 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4049 if (Ivars.empty())
4050 return;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004051
4052 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Craig Topperc6914d02014-08-25 04:15:02 +00004053 for (ObjCIvarDecl *IvarDecl : Ivars) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004054 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4055 unsigned GroupNo = 0;
4056 if (IvarDecl->isBitField()) {
4057 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4058 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4059 continue;
4060 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004061 Result += "\n";
4062 if (LangOpts.MicrosoftExt)
4063 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004064 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004065 if (LangOpts.MicrosoftExt &&
4066 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004067 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4068 Result += "__declspec(dllimport) ";
4069
Fariborz Jahanian38c59102012-03-27 16:21:30 +00004070 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004071 if (IvarDecl->isBitField()) {
4072 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4073 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4074 }
4075 else
4076 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00004077 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004078 }
4079}
4080
Fariborz Jahanian11671902012-02-07 17:11:38 +00004081//===----------------------------------------------------------------------===//
4082// Meta Data Emission
4083//===----------------------------------------------------------------------===//
4084
4085
4086/// RewriteImplementations - This routine rewrites all method implementations
4087/// and emits meta-data.
4088
4089void RewriteModernObjC::RewriteImplementations() {
4090 int ClsDefCount = ClassImplementation.size();
4091 int CatDefCount = CategoryImplementation.size();
4092
4093 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004094 for (int i = 0; i < ClsDefCount; i++) {
4095 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4096 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4097 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004098 assert(false &&
4099 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004100 RewriteImplementationDecl(OIMP);
4101 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004102
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004103 for (int i = 0; i < CatDefCount; i++) {
4104 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4105 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4106 if (CDecl->isImplicitInterfaceDecl())
4107 assert(false &&
4108 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004109 RewriteImplementationDecl(CIMP);
4110 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004111}
4112
4113void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4114 const std::string &Name,
4115 ValueDecl *VD, bool def) {
4116 assert(BlockByRefDeclNo.count(VD) &&
4117 "RewriteByRefString: ByRef decl missing");
4118 if (def)
4119 ResultStr += "struct ";
4120 ResultStr += "__Block_byref_" + Name +
4121 "_" + utostr(BlockByRefDeclNo[VD]) ;
4122}
4123
4124static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4125 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4126 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4127 return false;
4128}
4129
4130std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4131 StringRef funcName,
4132 std::string Tag) {
4133 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004134 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004135 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004136 SourceLocation BlockLoc = CE->getExprLoc();
4137 std::string S;
4138 ConvertSourceLocationToLineDirective(BlockLoc, S);
4139
4140 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4141 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004142
4143 BlockDecl *BD = CE->getBlockDecl();
4144
4145 if (isa<FunctionNoProtoType>(AFT)) {
4146 // No user-supplied arguments. Still need to pass in a pointer to the
4147 // block (to reference imported block decl refs).
4148 S += "(" + StructRef + " *__cself)";
4149 } else if (BD->param_empty()) {
4150 S += "(" + StructRef + " *__cself)";
4151 } else {
4152 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4153 assert(FT && "SynthesizeBlockFunc: No function proto");
4154 S += '(';
4155 // first add the implicit argument.
4156 S += StructRef + " *__cself, ";
4157 std::string ParamStr;
4158 for (BlockDecl::param_iterator AI = BD->param_begin(),
4159 E = BD->param_end(); AI != E; ++AI) {
4160 if (AI != BD->param_begin()) S += ", ";
4161 ParamStr = (*AI)->getNameAsString();
4162 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004163 (void)convertBlockPointerToFunctionPointer(QT);
4164 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004165 S += ParamStr;
4166 }
4167 if (FT->isVariadic()) {
4168 if (!BD->param_empty()) S += ", ";
4169 S += "...";
4170 }
4171 S += ')';
4172 }
4173 S += " {\n";
4174
4175 // Create local declarations to avoid rewriting all closure decl ref exprs.
4176 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004177 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004178 E = BlockByRefDecls.end(); I != E; ++I) {
4179 S += " ";
4180 std::string Name = (*I)->getNameAsString();
4181 std::string TypeString;
4182 RewriteByRefString(TypeString, Name, (*I));
4183 TypeString += " *";
4184 Name = TypeString + Name;
4185 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4186 }
4187 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004188 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004189 E = BlockByCopyDecls.end(); I != E; ++I) {
4190 S += " ";
4191 // Handle nested closure invocation. For example:
4192 //
4193 // void (^myImportedClosure)(void);
4194 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4195 //
4196 // void (^anotherClosure)(void);
4197 // anotherClosure = ^(void) {
4198 // myImportedClosure(); // import and invoke the closure
4199 // };
4200 //
4201 if (isTopLevelBlockPointerType((*I)->getType())) {
4202 RewriteBlockPointerTypeVariable(S, (*I));
4203 S += " = (";
4204 RewriteBlockPointerType(S, (*I)->getType());
4205 S += ")";
4206 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4207 }
4208 else {
4209 std::string Name = (*I)->getNameAsString();
4210 QualType QT = (*I)->getType();
4211 if (HasLocalVariableExternalStorage(*I))
4212 QT = Context->getPointerType(QT);
4213 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4214 S += Name + " = __cself->" +
4215 (*I)->getNameAsString() + "; // bound by copy\n";
4216 }
4217 }
4218 std::string RewrittenStr = RewrittenBlockExprs[CE];
4219 const char *cstr = RewrittenStr.c_str();
4220 while (*cstr++ != '{') ;
4221 S += cstr;
4222 S += "\n";
4223 return S;
4224}
4225
4226std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4227 StringRef funcName,
4228 std::string Tag) {
4229 std::string StructRef = "struct " + Tag;
4230 std::string S = "static void __";
4231
4232 S += funcName;
4233 S += "_block_copy_" + utostr(i);
4234 S += "(" + StructRef;
4235 S += "*dst, " + StructRef;
4236 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004237 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004238 S += "_Block_object_assign((void*)&dst->";
Craig Topperc6914d02014-08-25 04:15:02 +00004239 S += VD->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004240 S += ", (void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004241 S += VD->getNameAsString();
4242 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004243 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4244 else if (VD->getType()->isBlockPointerType())
4245 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4246 else
4247 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4248 }
4249 S += "}\n";
4250
4251 S += "\nstatic void __";
4252 S += funcName;
4253 S += "_block_dispose_" + utostr(i);
4254 S += "(" + StructRef;
4255 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004256 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004257 S += "_Block_object_dispose((void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004258 S += VD->getNameAsString();
4259 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004260 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4261 else if (VD->getType()->isBlockPointerType())
4262 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4263 else
4264 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4265 }
4266 S += "}\n";
4267 return S;
4268}
4269
4270std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4271 std::string Desc) {
4272 std::string S = "\nstruct " + Tag;
4273 std::string Constructor = " " + Tag;
4274
4275 S += " {\n struct __block_impl impl;\n";
4276 S += " struct " + Desc;
4277 S += "* Desc;\n";
4278
4279 Constructor += "(void *fp, "; // Invoke function pointer.
4280 Constructor += "struct " + Desc; // Descriptor pointer.
4281 Constructor += " *desc";
4282
4283 if (BlockDeclRefs.size()) {
4284 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004285 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004286 E = BlockByCopyDecls.end(); I != E; ++I) {
4287 S += " ";
4288 std::string FieldName = (*I)->getNameAsString();
4289 std::string ArgName = "_" + FieldName;
4290 // Handle nested closure invocation. For example:
4291 //
4292 // void (^myImportedBlock)(void);
4293 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4294 //
4295 // void (^anotherBlock)(void);
4296 // anotherBlock = ^(void) {
4297 // myImportedBlock(); // import and invoke the closure
4298 // };
4299 //
4300 if (isTopLevelBlockPointerType((*I)->getType())) {
4301 S += "struct __block_impl *";
4302 Constructor += ", void *" + ArgName;
4303 } else {
4304 QualType QT = (*I)->getType();
4305 if (HasLocalVariableExternalStorage(*I))
4306 QT = Context->getPointerType(QT);
4307 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4308 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4309 Constructor += ", " + ArgName;
4310 }
4311 S += FieldName + ";\n";
4312 }
4313 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004314 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004315 E = BlockByRefDecls.end(); I != E; ++I) {
4316 S += " ";
4317 std::string FieldName = (*I)->getNameAsString();
4318 std::string ArgName = "_" + FieldName;
4319 {
4320 std::string TypeString;
4321 RewriteByRefString(TypeString, FieldName, (*I));
4322 TypeString += " *";
4323 FieldName = TypeString + FieldName;
4324 ArgName = TypeString + ArgName;
4325 Constructor += ", " + ArgName;
4326 }
4327 S += FieldName + "; // by ref\n";
4328 }
4329 // Finish writing the constructor.
4330 Constructor += ", int flags=0)";
4331 // Initialize all "by copy" arguments.
4332 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004333 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004334 E = BlockByCopyDecls.end(); I != E; ++I) {
4335 std::string Name = (*I)->getNameAsString();
4336 if (firsTime) {
4337 Constructor += " : ";
4338 firsTime = false;
4339 }
4340 else
4341 Constructor += ", ";
4342 if (isTopLevelBlockPointerType((*I)->getType()))
4343 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4344 else
4345 Constructor += Name + "(_" + Name + ")";
4346 }
4347 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004348 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004349 E = BlockByRefDecls.end(); I != E; ++I) {
4350 std::string Name = (*I)->getNameAsString();
4351 if (firsTime) {
4352 Constructor += " : ";
4353 firsTime = false;
4354 }
4355 else
4356 Constructor += ", ";
4357 Constructor += Name + "(_" + Name + "->__forwarding)";
4358 }
4359
4360 Constructor += " {\n";
4361 if (GlobalVarDecl)
4362 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4363 else
4364 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4365 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4366
4367 Constructor += " Desc = desc;\n";
4368 } else {
4369 // Finish writing the constructor.
4370 Constructor += ", int flags=0) {\n";
4371 if (GlobalVarDecl)
4372 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4373 else
4374 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4375 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4376 Constructor += " Desc = desc;\n";
4377 }
4378 Constructor += " ";
4379 Constructor += "}\n";
4380 S += Constructor;
4381 S += "};\n";
4382 return S;
4383}
4384
4385std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4386 std::string ImplTag, int i,
4387 StringRef FunName,
4388 unsigned hasCopy) {
4389 std::string S = "\nstatic struct " + DescTag;
4390
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004391 S += " {\n size_t reserved;\n";
4392 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004393 if (hasCopy) {
4394 S += " void (*copy)(struct ";
4395 S += ImplTag; S += "*, struct ";
4396 S += ImplTag; S += "*);\n";
4397
4398 S += " void (*dispose)(struct ";
4399 S += ImplTag; S += "*);\n";
4400 }
4401 S += "} ";
4402
4403 S += DescTag + "_DATA = { 0, sizeof(struct ";
4404 S += ImplTag + ")";
4405 if (hasCopy) {
4406 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4407 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4408 }
4409 S += "};\n";
4410 return S;
4411}
4412
4413void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4414 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004415 bool RewriteSC = (GlobalVarDecl &&
4416 !Blocks.empty() &&
4417 GlobalVarDecl->getStorageClass() == SC_Static &&
4418 GlobalVarDecl->getType().getCVRQualifiers());
4419 if (RewriteSC) {
4420 std::string SC(" void __");
4421 SC += GlobalVarDecl->getNameAsString();
4422 SC += "() {}";
4423 InsertText(FunLocStart, SC);
4424 }
4425
4426 // Insert closures that were part of the function.
4427 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4428 CollectBlockDeclRefInfo(Blocks[i]);
4429 // Need to copy-in the inner copied-in variables not actually used in this
4430 // block.
4431 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004432 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004433 ValueDecl *VD = Exp->getDecl();
4434 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004435 if (!VD->hasAttr<BlocksAttr>()) {
4436 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4437 BlockByCopyDeclsPtrSet.insert(VD);
4438 BlockByCopyDecls.push_back(VD);
4439 }
4440 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004441 }
John McCall113bee02012-03-10 09:33:50 +00004442
4443 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004444 BlockByRefDeclsPtrSet.insert(VD);
4445 BlockByRefDecls.push_back(VD);
4446 }
John McCall113bee02012-03-10 09:33:50 +00004447
Fariborz Jahanian11671902012-02-07 17:11:38 +00004448 // imported objects in the inner blocks not used in the outer
4449 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004450 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004451 VD->getType()->isBlockPointerType())
4452 ImportedBlockDecls.insert(VD);
4453 }
4454
4455 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4456 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4457
4458 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4459
4460 InsertText(FunLocStart, CI);
4461
4462 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4463
4464 InsertText(FunLocStart, CF);
4465
4466 if (ImportedBlockDecls.size()) {
4467 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4468 InsertText(FunLocStart, HF);
4469 }
4470 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4471 ImportedBlockDecls.size() > 0);
4472 InsertText(FunLocStart, BD);
4473
4474 BlockDeclRefs.clear();
4475 BlockByRefDecls.clear();
4476 BlockByRefDeclsPtrSet.clear();
4477 BlockByCopyDecls.clear();
4478 BlockByCopyDeclsPtrSet.clear();
4479 ImportedBlockDecls.clear();
4480 }
4481 if (RewriteSC) {
4482 // Must insert any 'const/volatile/static here. Since it has been
4483 // removed as result of rewriting of block literals.
4484 std::string SC;
4485 if (GlobalVarDecl->getStorageClass() == SC_Static)
4486 SC = "static ";
4487 if (GlobalVarDecl->getType().isConstQualified())
4488 SC += "const ";
4489 if (GlobalVarDecl->getType().isVolatileQualified())
4490 SC += "volatile ";
4491 if (GlobalVarDecl->getType().isRestrictQualified())
4492 SC += "restrict ";
4493 InsertText(FunLocStart, SC);
4494 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004495 if (GlobalConstructionExp) {
4496 // extra fancy dance for global literal expression.
4497
4498 // Always the latest block expression on the block stack.
4499 std::string Tag = "__";
4500 Tag += FunName;
4501 Tag += "_block_impl_";
4502 Tag += utostr(Blocks.size()-1);
4503 std::string globalBuf = "static ";
4504 globalBuf += Tag; globalBuf += " ";
4505 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004506
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004507 llvm::raw_string_ostream constructorExprBuf(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +00004508 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4509 PrintingPolicy(LangOpts));
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004510 globalBuf += constructorExprBuf.str();
4511 globalBuf += ";\n";
4512 InsertText(FunLocStart, globalBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00004513 GlobalConstructionExp = nullptr;
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004514 }
4515
Fariborz Jahanian11671902012-02-07 17:11:38 +00004516 Blocks.clear();
4517 InnerDeclRefsCount.clear();
4518 InnerDeclRefs.clear();
4519 RewrittenBlockExprs.clear();
4520}
4521
4522void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004523 SourceLocation FunLocStart =
4524 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4525 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004526 StringRef FuncName = FD->getName();
4527
4528 SynthesizeBlockLiterals(FunLocStart, FuncName);
4529}
4530
4531static void BuildUniqueMethodName(std::string &Name,
4532 ObjCMethodDecl *MD) {
4533 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4534 Name = IFace->getName();
4535 Name += "__" + MD->getSelector().getAsString();
4536 // Convert colons to underscores.
4537 std::string::size_type loc = 0;
4538 while ((loc = Name.find(":", loc)) != std::string::npos)
4539 Name.replace(loc, 1, "_");
4540}
4541
4542void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4543 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4544 //SourceLocation FunLocStart = MD->getLocStart();
4545 SourceLocation FunLocStart = MD->getLocStart();
4546 std::string FuncName;
4547 BuildUniqueMethodName(FuncName, MD);
4548 SynthesizeBlockLiterals(FunLocStart, FuncName);
4549}
4550
4551void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4552 for (Stmt::child_range CI = S->children(); CI; ++CI)
4553 if (*CI) {
4554 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4555 GetBlockDeclRefExprs(CBE->getBody());
4556 else
4557 GetBlockDeclRefExprs(*CI);
4558 }
4559 // Handle specific things.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004560 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004561 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004562 HasLocalVariableExternalStorage(DRE->getDecl()))
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004563 // FIXME: Handle enums.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004564 BlockDeclRefs.push_back(DRE);
4565
Fariborz Jahanian11671902012-02-07 17:11:38 +00004566 return;
4567}
4568
Craig Topper5603df42013-07-05 19:34:19 +00004569void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4570 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +00004571 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004572 for (Stmt::child_range CI = S->children(); CI; ++CI)
4573 if (*CI) {
4574 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4575 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4576 GetInnerBlockDeclRefExprs(CBE->getBody(),
4577 InnerBlockDeclRefs,
4578 InnerContexts);
4579 }
4580 else
4581 GetInnerBlockDeclRefExprs(*CI,
4582 InnerBlockDeclRefs,
4583 InnerContexts);
4584
4585 }
4586 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004587 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004588 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004589 HasLocalVariableExternalStorage(DRE->getDecl())) {
4590 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
John McCall113bee02012-03-10 09:33:50 +00004591 InnerBlockDeclRefs.push_back(DRE);
Alexey Bataevf841bd92014-12-16 07:00:22 +00004592 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
John McCall113bee02012-03-10 09:33:50 +00004593 if (Var->isFunctionOrMethodVarDecl())
4594 ImportedLocalExternalDecls.insert(Var);
4595 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004596 }
4597
4598 return;
4599}
4600
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004601/// convertObjCTypeToCStyleType - This routine converts such objc types
4602/// as qualified objects, and blocks to their closest c/c++ types that
4603/// it can. It returns true if input type was modified.
4604bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4605 QualType oldT = T;
4606 convertBlockPointerToFunctionPointer(T);
4607 if (T->isFunctionPointerType()) {
4608 QualType PointeeTy;
4609 if (const PointerType* PT = T->getAs<PointerType>()) {
4610 PointeeTy = PT->getPointeeType();
4611 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4612 T = convertFunctionTypeOfBlocks(FT);
4613 T = Context->getPointerType(T);
4614 }
4615 }
4616 }
4617
4618 convertToUnqualifiedObjCType(T);
4619 return T != oldT;
4620}
4621
Fariborz Jahanian11671902012-02-07 17:11:38 +00004622/// convertFunctionTypeOfBlocks - This routine converts a function type
4623/// whose result type may be a block pointer or whose argument type(s)
4624/// might be block pointers to an equivalent function type replacing
4625/// all block pointers to function pointers.
4626QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4627 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4628 // FTP will be null for closures that don't take arguments.
4629 // Generate a funky cast.
4630 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004631 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004632 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004633
4634 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004635 for (auto &I : FTP->param_types()) {
4636 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004637 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004638 if (convertObjCTypeToCStyleType(t))
4639 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004640 ArgTypes.push_back(t);
4641 }
4642 }
4643 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004644 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004645 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004646 else FuncType = QualType(FT, 0);
4647 return FuncType;
4648}
4649
4650Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4651 // Navigate to relevant type information.
Craig Topper8ae12032014-05-07 06:21:57 +00004652 const BlockPointerType *CPT = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004653
4654 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4655 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004656 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4657 CPT = MExpr->getType()->getAs<BlockPointerType>();
4658 }
4659 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4660 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4661 }
4662 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4663 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4664 else if (const ConditionalOperator *CEXPR =
4665 dyn_cast<ConditionalOperator>(BlockExp)) {
4666 Expr *LHSExp = CEXPR->getLHS();
4667 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4668 Expr *RHSExp = CEXPR->getRHS();
4669 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4670 Expr *CONDExp = CEXPR->getCond();
4671 ConditionalOperator *CondExpr =
4672 new (Context) ConditionalOperator(CONDExp,
4673 SourceLocation(), cast<Expr>(LHSStmt),
4674 SourceLocation(), cast<Expr>(RHSStmt),
4675 Exp->getType(), VK_RValue, OK_Ordinary);
4676 return CondExpr;
4677 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4678 CPT = IRE->getType()->getAs<BlockPointerType>();
4679 } else if (const PseudoObjectExpr *POE
4680 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4681 CPT = POE->getType()->castAs<BlockPointerType>();
4682 } else {
4683 assert(1 && "RewriteBlockClass: Bad type");
4684 }
4685 assert(CPT && "RewriteBlockClass: Bad type");
4686 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4687 assert(FT && "RewriteBlockClass: Bad type");
4688 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4689 // FTP will be null for closures that don't take arguments.
4690
4691 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4692 SourceLocation(), SourceLocation(),
4693 &Context->Idents.get("__block_impl"));
4694 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4695
4696 // Generate a funky cast.
4697 SmallVector<QualType, 8> ArgTypes;
4698
4699 // Push the block argument type.
4700 ArgTypes.push_back(PtrBlock);
4701 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004702 for (auto &I : FTP->param_types()) {
4703 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004704 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4705 if (!convertBlockPointerToFunctionPointer(t))
4706 convertToUnqualifiedObjCType(t);
4707 ArgTypes.push_back(t);
4708 }
4709 }
4710 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004711 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004712
4713 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4714
4715 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4716 CK_BitCast,
4717 const_cast<Expr*>(BlockExp));
4718 // Don't forget the parens to enforce the proper binding.
4719 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4720 BlkCast);
4721 //PE->dump();
4722
Craig Topper8ae12032014-05-07 06:21:57 +00004723 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004724 SourceLocation(),
4725 &Context->Idents.get("FuncPtr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004726 Context->VoidPtrTy, nullptr,
4727 /*BitWidth=*/nullptr, /*Mutable=*/true,
4728 ICIS_NoInit);
4729 MemberExpr *ME =
4730 new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
4731 FD->getType(), VK_LValue, OK_Ordinary);
4732
4733 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4734 CK_BitCast, ME);
4735 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004736
4737 SmallVector<Expr*, 8> BlkExprs;
4738 // Add the implicit argument.
4739 BlkExprs.push_back(BlkCast);
4740 // Add the user arguments.
4741 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4742 E = Exp->arg_end(); I != E; ++I) {
4743 BlkExprs.push_back(*I);
4744 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004745 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004746 Exp->getType(), VK_RValue,
4747 SourceLocation());
4748 return CE;
4749}
4750
4751// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004752// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004753// For example:
4754//
4755// int main() {
4756// __block Foo *f;
4757// __block int i;
4758//
4759// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004760// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004761// i = 77;
4762// };
4763//}
John McCall113bee02012-03-10 09:33:50 +00004764Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004765 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4766 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004767 ValueDecl *VD = DeclRefExp->getDecl();
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004768 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004769 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
Craig Topper8ae12032014-05-07 06:21:57 +00004770
4771 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004772 SourceLocation(),
4773 &Context->Idents.get("__forwarding"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004774 Context->VoidPtrTy, nullptr,
4775 /*BitWidth=*/nullptr, /*Mutable=*/true,
4776 ICIS_NoInit);
4777 MemberExpr *ME = new (Context)
4778 MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(),
4779 FD->getType(), VK_LValue, OK_Ordinary);
4780
4781 StringRef Name = VD->getName();
4782 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004783 &Context->Idents.get(Name),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004784 Context->VoidPtrTy, nullptr,
4785 /*BitWidth=*/nullptr, /*Mutable=*/true,
4786 ICIS_NoInit);
4787 ME =
4788 new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(),
4789 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4790
4791 // Need parens to enforce precedence.
4792 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4793 DeclRefExp->getExprLoc(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004794 ME);
4795 ReplaceStmt(DeclRefExp, PE);
4796 return PE;
4797}
4798
4799// Rewrites the imported local variable V with external storage
4800// (static, extern, etc.) as *V
4801//
4802Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4803 ValueDecl *VD = DRE->getDecl();
4804 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4805 if (!ImportedLocalExternalDecls.count(Var))
4806 return DRE;
4807 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4808 VK_LValue, OK_Ordinary,
4809 DRE->getLocation());
4810 // Need parens to enforce precedence.
4811 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4812 Exp);
4813 ReplaceStmt(DRE, PE);
4814 return PE;
4815}
4816
4817void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4818 SourceLocation LocStart = CE->getLParenLoc();
4819 SourceLocation LocEnd = CE->getRParenLoc();
4820
4821 // Need to avoid trying to rewrite synthesized casts.
4822 if (LocStart.isInvalid())
4823 return;
4824 // Need to avoid trying to rewrite casts contained in macros.
4825 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4826 return;
4827
4828 const char *startBuf = SM->getCharacterData(LocStart);
4829 const char *endBuf = SM->getCharacterData(LocEnd);
4830 QualType QT = CE->getType();
4831 const Type* TypePtr = QT->getAs<Type>();
4832 if (isa<TypeOfExprType>(TypePtr)) {
4833 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4834 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4835 std::string TypeAsString = "(";
4836 RewriteBlockPointerType(TypeAsString, QT);
4837 TypeAsString += ")";
4838 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4839 return;
4840 }
4841 // advance the location to startArgList.
4842 const char *argPtr = startBuf;
4843
4844 while (*argPtr++ && (argPtr < endBuf)) {
4845 switch (*argPtr) {
4846 case '^':
4847 // Replace the '^' with '*'.
4848 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4849 ReplaceText(LocStart, 1, "*");
4850 break;
4851 }
4852 }
4853 return;
4854}
4855
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004856void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4857 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004858 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4859 CastKind != CK_AnyPointerToBlockPointerCast)
4860 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004861
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004862 QualType QT = IC->getType();
4863 (void)convertBlockPointerToFunctionPointer(QT);
4864 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4865 std::string Str = "(";
4866 Str += TypeString;
4867 Str += ")";
4868 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4869
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004870 return;
4871}
4872
Fariborz Jahanian11671902012-02-07 17:11:38 +00004873void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4874 SourceLocation DeclLoc = FD->getLocation();
4875 unsigned parenCount = 0;
4876
4877 // We have 1 or more arguments that have closure pointers.
4878 const char *startBuf = SM->getCharacterData(DeclLoc);
4879 const char *startArgList = strchr(startBuf, '(');
4880
4881 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4882
4883 parenCount++;
4884 // advance the location to startArgList.
4885 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4886 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4887
4888 const char *argPtr = startArgList;
4889
4890 while (*argPtr++ && parenCount) {
4891 switch (*argPtr) {
4892 case '^':
4893 // Replace the '^' with '*'.
4894 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4895 ReplaceText(DeclLoc, 1, "*");
4896 break;
4897 case '(':
4898 parenCount++;
4899 break;
4900 case ')':
4901 parenCount--;
4902 break;
4903 }
4904 }
4905 return;
4906}
4907
4908bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4909 const FunctionProtoType *FTP;
4910 const PointerType *PT = QT->getAs<PointerType>();
4911 if (PT) {
4912 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4913 } else {
4914 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4915 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4916 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4917 }
4918 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004919 for (const auto &I : FTP->param_types())
4920 if (isTopLevelBlockPointerType(I))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004921 return true;
4922 }
4923 return false;
4924}
4925
4926bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4927 const FunctionProtoType *FTP;
4928 const PointerType *PT = QT->getAs<PointerType>();
4929 if (PT) {
4930 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4931 } else {
4932 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4933 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4934 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4935 }
4936 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004937 for (const auto &I : FTP->param_types()) {
4938 if (I->isObjCQualifiedIdType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004939 return true;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004940 if (I->isObjCObjectPointerType() &&
4941 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004942 return true;
4943 }
4944
4945 }
4946 return false;
4947}
4948
4949void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4950 const char *&RParen) {
4951 const char *argPtr = strchr(Name, '(');
4952 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4953
4954 LParen = argPtr; // output the start.
4955 argPtr++; // skip past the left paren.
4956 unsigned parenCount = 1;
4957
4958 while (*argPtr && parenCount) {
4959 switch (*argPtr) {
4960 case '(': parenCount++; break;
4961 case ')': parenCount--; break;
4962 default: break;
4963 }
4964 if (parenCount) argPtr++;
4965 }
4966 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4967 RParen = argPtr; // output the end
4968}
4969
4970void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4971 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4972 RewriteBlockPointerFunctionArgs(FD);
4973 return;
4974 }
4975 // Handle Variables and Typedefs.
4976 SourceLocation DeclLoc = ND->getLocation();
4977 QualType DeclT;
4978 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4979 DeclT = VD->getType();
4980 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4981 DeclT = TDD->getUnderlyingType();
4982 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4983 DeclT = FD->getType();
4984 else
4985 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4986
4987 const char *startBuf = SM->getCharacterData(DeclLoc);
4988 const char *endBuf = startBuf;
4989 // scan backward (from the decl location) for the end of the previous decl.
4990 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4991 startBuf--;
4992 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4993 std::string buf;
4994 unsigned OrigLength=0;
4995 // *startBuf != '^' if we are dealing with a pointer to function that
4996 // may take block argument types (which will be handled below).
4997 if (*startBuf == '^') {
4998 // Replace the '^' with '*', computing a negative offset.
4999 buf = '*';
5000 startBuf++;
5001 OrigLength++;
5002 }
5003 while (*startBuf != ')') {
5004 buf += *startBuf;
5005 startBuf++;
5006 OrigLength++;
5007 }
5008 buf += ')';
5009 OrigLength++;
5010
5011 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5012 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5013 // Replace the '^' with '*' for arguments.
5014 // Replace id<P> with id/*<>*/
5015 DeclLoc = ND->getLocation();
5016 startBuf = SM->getCharacterData(DeclLoc);
5017 const char *argListBegin, *argListEnd;
5018 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5019 while (argListBegin < argListEnd) {
5020 if (*argListBegin == '^')
5021 buf += '*';
5022 else if (*argListBegin == '<') {
5023 buf += "/*";
5024 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005025 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005026 while (*argListBegin != '>') {
5027 buf += *argListBegin++;
5028 OrigLength++;
5029 }
5030 buf += *argListBegin;
5031 buf += "*/";
5032 }
5033 else
5034 buf += *argListBegin;
5035 argListBegin++;
5036 OrigLength++;
5037 }
5038 buf += ')';
5039 OrigLength++;
5040 }
5041 ReplaceText(Start, OrigLength, buf);
5042
5043 return;
5044}
5045
5046
5047/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5048/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5049/// struct Block_byref_id_object *src) {
5050/// _Block_object_assign (&_dest->object, _src->object,
5051/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5052/// [|BLOCK_FIELD_IS_WEAK]) // object
5053/// _Block_object_assign(&_dest->object, _src->object,
5054/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5055/// [|BLOCK_FIELD_IS_WEAK]) // block
5056/// }
5057/// And:
5058/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5059/// _Block_object_dispose(_src->object,
5060/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5061/// [|BLOCK_FIELD_IS_WEAK]) // object
5062/// _Block_object_dispose(_src->object,
5063/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5064/// [|BLOCK_FIELD_IS_WEAK]) // block
5065/// }
5066
5067std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5068 int flag) {
5069 std::string S;
5070 if (CopyDestroyCache.count(flag))
5071 return S;
5072 CopyDestroyCache.insert(flag);
5073 S = "static void __Block_byref_id_object_copy_";
5074 S += utostr(flag);
5075 S += "(void *dst, void *src) {\n";
5076
5077 // offset into the object pointer is computed as:
5078 // void * + void* + int + int + void* + void *
5079 unsigned IntSize =
5080 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5081 unsigned VoidPtrSize =
5082 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5083
5084 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5085 S += " _Block_object_assign((char*)dst + ";
5086 S += utostr(offset);
5087 S += ", *(void * *) ((char*)src + ";
5088 S += utostr(offset);
5089 S += "), ";
5090 S += utostr(flag);
5091 S += ");\n}\n";
5092
5093 S += "static void __Block_byref_id_object_dispose_";
5094 S += utostr(flag);
5095 S += "(void *src) {\n";
5096 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5097 S += utostr(offset);
5098 S += "), ";
5099 S += utostr(flag);
5100 S += ");\n}\n";
5101 return S;
5102}
5103
5104/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5105/// the declaration into:
5106/// struct __Block_byref_ND {
5107/// void *__isa; // NULL for everything except __weak pointers
5108/// struct __Block_byref_ND *__forwarding;
5109/// int32_t __flags;
5110/// int32_t __size;
5111/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5112/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5113/// typex ND;
5114/// };
5115///
5116/// It then replaces declaration of ND variable with:
5117/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5118/// __size=sizeof(struct __Block_byref_ND),
5119/// ND=initializer-if-any};
5120///
5121///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005122void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5123 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005124 int flag = 0;
5125 int isa = 0;
5126 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5127 if (DeclLoc.isInvalid())
5128 // If type location is missing, it is because of missing type (a warning).
5129 // Use variable's location which is good for this case.
5130 DeclLoc = ND->getLocation();
5131 const char *startBuf = SM->getCharacterData(DeclLoc);
5132 SourceLocation X = ND->getLocEnd();
5133 X = SM->getExpansionLoc(X);
5134 const char *endBuf = SM->getCharacterData(X);
5135 std::string Name(ND->getNameAsString());
5136 std::string ByrefType;
5137 RewriteByRefString(ByrefType, Name, ND, true);
5138 ByrefType += " {\n";
5139 ByrefType += " void *__isa;\n";
5140 RewriteByRefString(ByrefType, Name, ND);
5141 ByrefType += " *__forwarding;\n";
5142 ByrefType += " int __flags;\n";
5143 ByrefType += " int __size;\n";
5144 // Add void *__Block_byref_id_object_copy;
5145 // void *__Block_byref_id_object_dispose; if needed.
5146 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005147 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005148 if (HasCopyAndDispose) {
5149 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5150 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5151 }
5152
5153 QualType T = Ty;
5154 (void)convertBlockPointerToFunctionPointer(T);
5155 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5156
5157 ByrefType += " " + Name + ";\n";
5158 ByrefType += "};\n";
5159 // Insert this type in global scope. It is needed by helper function.
5160 SourceLocation FunLocStart;
5161 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005162 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005163 else {
5164 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5165 FunLocStart = CurMethodDef->getLocStart();
5166 }
5167 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005168
Fariborz Jahanian11671902012-02-07 17:11:38 +00005169 if (Ty.isObjCGCWeak()) {
5170 flag |= BLOCK_FIELD_IS_WEAK;
5171 isa = 1;
5172 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005173 if (HasCopyAndDispose) {
5174 flag = BLOCK_BYREF_CALLER;
5175 QualType Ty = ND->getType();
5176 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5177 if (Ty->isBlockPointerType())
5178 flag |= BLOCK_FIELD_IS_BLOCK;
5179 else
5180 flag |= BLOCK_FIELD_IS_OBJECT;
5181 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5182 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005183 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005184 }
5185
5186 // struct __Block_byref_ND ND =
5187 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5188 // initializer-if-any};
Craig Topper8ae12032014-05-07 06:21:57 +00005189 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005190 // FIXME. rewriter does not support __block c++ objects which
5191 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005192 if (hasInit)
5193 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5194 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5195 if (CXXDecl && CXXDecl->isDefaultConstructor())
5196 hasInit = false;
5197 }
5198
Fariborz Jahanian11671902012-02-07 17:11:38 +00005199 unsigned flags = 0;
5200 if (HasCopyAndDispose)
5201 flags |= BLOCK_HAS_COPY_DISPOSE;
5202 Name = ND->getNameAsString();
5203 ByrefType.clear();
5204 RewriteByRefString(ByrefType, Name, ND);
5205 std::string ForwardingCastType("(");
5206 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005207 ByrefType += " " + Name + " = {(void*)";
5208 ByrefType += utostr(isa);
5209 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5210 ByrefType += utostr(flags);
5211 ByrefType += ", ";
5212 ByrefType += "sizeof(";
5213 RewriteByRefString(ByrefType, Name, ND);
5214 ByrefType += ")";
5215 if (HasCopyAndDispose) {
5216 ByrefType += ", __Block_byref_id_object_copy_";
5217 ByrefType += utostr(flag);
5218 ByrefType += ", __Block_byref_id_object_dispose_";
5219 ByrefType += utostr(flag);
5220 }
5221
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005222 if (!firstDecl) {
5223 // In multiple __block declarations, and for all but 1st declaration,
5224 // find location of the separating comma. This would be start location
5225 // where new text is to be inserted.
5226 DeclLoc = ND->getLocation();
5227 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5228 const char *commaBuf = startDeclBuf;
5229 while (*commaBuf != ',')
5230 commaBuf--;
5231 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5232 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5233 startBuf = commaBuf;
5234 }
5235
Fariborz Jahanian11671902012-02-07 17:11:38 +00005236 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005237 ByrefType += "};\n";
5238 unsigned nameSize = Name.size();
5239 // for block or function pointer declaration. Name is aleady
5240 // part of the declaration.
5241 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5242 nameSize = 1;
5243 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5244 }
5245 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005246 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005247 SourceLocation startLoc;
5248 Expr *E = ND->getInit();
5249 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5250 startLoc = ECE->getLParenLoc();
5251 else
5252 startLoc = E->getLocStart();
5253 startLoc = SM->getExpansionLoc(startLoc);
5254 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005255 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005256
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005257 const char separator = lastDecl ? ';' : ',';
5258 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5259 const char *separatorBuf = strchr(startInitializerBuf, separator);
5260 assert((*separatorBuf == separator) &&
5261 "RewriteByRefVar: can't find ';' or ','");
5262 SourceLocation separatorLoc =
5263 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5264
5265 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005266 }
5267 return;
5268}
5269
5270void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5271 // Add initializers for any closure decl refs.
5272 GetBlockDeclRefExprs(Exp->getBody());
5273 if (BlockDeclRefs.size()) {
5274 // Unique all "by copy" declarations.
5275 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005276 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005277 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5278 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5279 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5280 }
5281 }
5282 // Unique all "by ref" declarations.
5283 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005284 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005285 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5286 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5287 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5288 }
5289 }
5290 // Find any imported blocks...they will need special attention.
5291 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005292 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005293 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5294 BlockDeclRefs[i]->getType()->isBlockPointerType())
5295 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5296 }
5297}
5298
5299FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5300 IdentifierInfo *ID = &Context->Idents.get(name);
5301 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5302 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00005303 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005304 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005305}
5306
5307Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005308 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005309
Fariborz Jahanian11671902012-02-07 17:11:38 +00005310 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005311
Fariborz Jahanian11671902012-02-07 17:11:38 +00005312 Blocks.push_back(Exp);
5313
5314 CollectBlockDeclRefInfo(Exp);
5315
5316 // Add inner imported variables now used in current block.
5317 int countOfInnerDecls = 0;
5318 if (!InnerBlockDeclRefs.empty()) {
5319 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005320 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005321 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005322 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005323 // We need to save the copied-in variables in nested
5324 // blocks because it is needed at the end for some of the API generations.
5325 // See SynthesizeBlockLiterals routine.
5326 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5327 BlockDeclRefs.push_back(Exp);
5328 BlockByCopyDeclsPtrSet.insert(VD);
5329 BlockByCopyDecls.push_back(VD);
5330 }
John McCall113bee02012-03-10 09:33:50 +00005331 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005332 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5333 BlockDeclRefs.push_back(Exp);
5334 BlockByRefDeclsPtrSet.insert(VD);
5335 BlockByRefDecls.push_back(VD);
5336 }
5337 }
5338 // Find any imported blocks...they will need special attention.
5339 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005340 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005341 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5342 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5343 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5344 }
5345 InnerDeclRefsCount.push_back(countOfInnerDecls);
5346
5347 std::string FuncName;
5348
5349 if (CurFunctionDef)
5350 FuncName = CurFunctionDef->getNameAsString();
5351 else if (CurMethodDef)
5352 BuildUniqueMethodName(FuncName, CurMethodDef);
5353 else if (GlobalVarDecl)
5354 FuncName = std::string(GlobalVarDecl->getNameAsString());
5355
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005356 bool GlobalBlockExpr =
5357 block->getDeclContext()->getRedeclContext()->isFileContext();
5358
5359 if (GlobalBlockExpr && !GlobalVarDecl) {
5360 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5361 GlobalBlockExpr = false;
5362 }
5363
Fariborz Jahanian11671902012-02-07 17:11:38 +00005364 std::string BlockNumber = utostr(Blocks.size()-1);
5365
Fariborz Jahanian11671902012-02-07 17:11:38 +00005366 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5367
5368 // Get a pointer to the function type so we can cast appropriately.
5369 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5370 QualType FType = Context->getPointerType(BFT);
5371
5372 FunctionDecl *FD;
5373 Expr *NewRep;
5374
Benjamin Kramer60509af2013-09-09 14:48:42 +00005375 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005376 std::string Tag;
5377
5378 if (GlobalBlockExpr)
5379 Tag = "__global_";
5380 else
5381 Tag = "__";
5382 Tag += FuncName + "_block_impl_" + BlockNumber;
5383
Fariborz Jahanian11671902012-02-07 17:11:38 +00005384 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005385 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005386 SourceLocation());
5387
5388 SmallVector<Expr*, 4> InitExprs;
5389
5390 // Initialize the block function.
5391 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005392 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5393 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005394 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5395 CK_BitCast, Arg);
5396 InitExprs.push_back(castExpr);
5397
5398 // Initialize the block descriptor.
5399 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5400
5401 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5402 SourceLocation(), SourceLocation(),
5403 &Context->Idents.get(DescData.c_str()),
Craig Topper8ae12032014-05-07 06:21:57 +00005404 Context->VoidPtrTy, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005405 SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005406 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005407 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005408 Context->VoidPtrTy,
5409 VK_LValue,
5410 SourceLocation()),
5411 UO_AddrOf,
5412 Context->getPointerType(Context->VoidPtrTy),
5413 VK_RValue, OK_Ordinary,
5414 SourceLocation());
5415 InitExprs.push_back(DescRefExpr);
5416
5417 // Add initializers for any closure decl refs.
5418 if (BlockDeclRefs.size()) {
5419 Expr *Exp;
5420 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005421 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005422 E = BlockByCopyDecls.end(); I != E; ++I) {
5423 if (isObjCType((*I)->getType())) {
5424 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5425 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005426 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5427 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005428 if (HasLocalVariableExternalStorage(*I)) {
5429 QualType QT = (*I)->getType();
5430 QT = Context->getPointerType(QT);
5431 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5432 OK_Ordinary, SourceLocation());
5433 }
5434 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5435 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005436 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5437 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005438 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5439 CK_BitCast, Arg);
5440 } else {
5441 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005442 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5443 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005444 if (HasLocalVariableExternalStorage(*I)) {
5445 QualType QT = (*I)->getType();
5446 QT = Context->getPointerType(QT);
5447 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5448 OK_Ordinary, SourceLocation());
5449 }
5450
5451 }
5452 InitExprs.push_back(Exp);
5453 }
5454 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005455 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005456 E = BlockByRefDecls.end(); I != E; ++I) {
5457 ValueDecl *ND = (*I);
5458 std::string Name(ND->getNameAsString());
5459 std::string RecName;
5460 RewriteByRefString(RecName, Name, ND, true);
5461 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5462 + sizeof("struct"));
5463 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5464 SourceLocation(), SourceLocation(),
5465 II);
5466 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5467 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5468
5469 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005470 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005471 SourceLocation());
5472 bool isNestedCapturedVar = false;
5473 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00005474 for (const auto &CI : block->captures()) {
5475 const VarDecl *variable = CI.getVariable();
5476 if (variable == ND && CI.isNested()) {
5477 assert (CI.isByRef() &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00005478 "SynthBlockInitExpr - captured block variable is not byref");
5479 isNestedCapturedVar = true;
5480 break;
5481 }
5482 }
5483 // captured nested byref variable has its address passed. Do not take
5484 // its address again.
5485 if (!isNestedCapturedVar)
5486 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5487 Context->getPointerType(Exp->getType()),
5488 VK_RValue, OK_Ordinary, SourceLocation());
5489 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5490 InitExprs.push_back(Exp);
5491 }
5492 }
5493 if (ImportedBlockDecls.size()) {
5494 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5495 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5496 unsigned IntSize =
5497 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5498 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5499 Context->IntTy, SourceLocation());
5500 InitExprs.push_back(FlagExp);
5501 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005502 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005503 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005504
5505 if (GlobalBlockExpr) {
Craig Topper8ae12032014-05-07 06:21:57 +00005506 assert (!GlobalConstructionExp &&
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005507 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5508 GlobalConstructionExp = NewRep;
5509 NewRep = DRE;
5510 }
5511
Fariborz Jahanian11671902012-02-07 17:11:38 +00005512 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5513 Context->getPointerType(NewRep->getType()),
5514 VK_RValue, OK_Ordinary, SourceLocation());
5515 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5516 NewRep);
Fariborz Jahanian937224772014-10-28 23:46:58 +00005517 // Put Paren around the call.
5518 NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5519 NewRep);
5520
Fariborz Jahanian11671902012-02-07 17:11:38 +00005521 BlockDeclRefs.clear();
5522 BlockByRefDecls.clear();
5523 BlockByRefDeclsPtrSet.clear();
5524 BlockByCopyDecls.clear();
5525 BlockByCopyDeclsPtrSet.clear();
5526 ImportedBlockDecls.clear();
5527 return NewRep;
5528}
5529
5530bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5531 if (const ObjCForCollectionStmt * CS =
5532 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5533 return CS->getElement() == DS;
5534 return false;
5535}
5536
5537//===----------------------------------------------------------------------===//
5538// Function Body / Expression rewriting
5539//===----------------------------------------------------------------------===//
5540
5541Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5542 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5543 isa<DoStmt>(S) || isa<ForStmt>(S))
5544 Stmts.push_back(S);
5545 else if (isa<ObjCForCollectionStmt>(S)) {
5546 Stmts.push_back(S);
5547 ObjCBcLabelNo.push_back(++BcLabelCount);
5548 }
5549
5550 // Pseudo-object operations and ivar references need special
5551 // treatment because we're going to recursively rewrite them.
5552 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5553 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5554 return RewritePropertyOrImplicitSetter(PseudoOp);
5555 } else {
5556 return RewritePropertyOrImplicitGetter(PseudoOp);
5557 }
5558 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5559 return RewriteObjCIvarRefExpr(IvarRefExpr);
5560 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005561 else if (isa<OpaqueValueExpr>(S))
5562 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005563
5564 SourceRange OrigStmtRange = S->getSourceRange();
5565
5566 // Perform a bottom up rewrite of all children.
5567 for (Stmt::child_range CI = S->children(); CI; ++CI)
5568 if (*CI) {
5569 Stmt *childStmt = (*CI);
5570 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5571 if (newStmt) {
5572 *CI = newStmt;
5573 }
5574 }
5575
5576 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005577 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005578 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5579 InnerContexts.insert(BE->getBlockDecl());
5580 ImportedLocalExternalDecls.clear();
5581 GetInnerBlockDeclRefExprs(BE->getBody(),
5582 InnerBlockDeclRefs, InnerContexts);
5583 // Rewrite the block body in place.
5584 Stmt *SaveCurrentBody = CurrentBody;
5585 CurrentBody = BE->getBody();
Craig Topper8ae12032014-05-07 06:21:57 +00005586 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005587 // block literal on rhs of a property-dot-sytax assignment
5588 // must be replaced by its synthesize ast so getRewrittenText
5589 // works as expected. In this case, what actually ends up on RHS
5590 // is the blockTranscribed which is the helper function for the
5591 // block literal; as in: self.c = ^() {[ace ARR];};
5592 bool saveDisableReplaceStmt = DisableReplaceStmt;
5593 DisableReplaceStmt = false;
5594 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5595 DisableReplaceStmt = saveDisableReplaceStmt;
5596 CurrentBody = SaveCurrentBody;
Craig Topper8ae12032014-05-07 06:21:57 +00005597 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005598 ImportedLocalExternalDecls.clear();
5599 // Now we snarf the rewritten text and stash it away for later use.
5600 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5601 RewrittenBlockExprs[BE] = Str;
5602
5603 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5604
5605 //blockTranscribed->dump();
5606 ReplaceStmt(S, blockTranscribed);
5607 return blockTranscribed;
5608 }
5609 // Handle specific things.
5610 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5611 return RewriteAtEncode(AtEncode);
5612
5613 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5614 return RewriteAtSelector(AtSelector);
5615
5616 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5617 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005618
5619 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5620 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005621
Patrick Beard0caa3942012-04-19 00:25:12 +00005622 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5623 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005624
5625 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5626 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005627
5628 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5629 dyn_cast<ObjCDictionaryLiteral>(S))
5630 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005631
5632 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5633#if 0
5634 // Before we rewrite it, put the original message expression in a comment.
5635 SourceLocation startLoc = MessExpr->getLocStart();
5636 SourceLocation endLoc = MessExpr->getLocEnd();
5637
5638 const char *startBuf = SM->getCharacterData(startLoc);
5639 const char *endBuf = SM->getCharacterData(endLoc);
5640
5641 std::string messString;
5642 messString += "// ";
5643 messString.append(startBuf, endBuf-startBuf+1);
5644 messString += "\n";
5645
5646 // FIXME: Missing definition of
5647 // InsertText(clang::SourceLocation, char const*, unsigned int).
5648 // InsertText(startLoc, messString.c_str(), messString.size());
5649 // Tried this, but it didn't work either...
5650 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5651#endif
5652 return RewriteMessageExpr(MessExpr);
5653 }
5654
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005655 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5656 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5657 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5658 }
5659
Fariborz Jahanian11671902012-02-07 17:11:38 +00005660 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5661 return RewriteObjCTryStmt(StmtTry);
5662
5663 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5664 return RewriteObjCSynchronizedStmt(StmtTry);
5665
5666 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5667 return RewriteObjCThrowStmt(StmtThrow);
5668
5669 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5670 return RewriteObjCProtocolExpr(ProtocolExp);
5671
5672 if (ObjCForCollectionStmt *StmtForCollection =
5673 dyn_cast<ObjCForCollectionStmt>(S))
5674 return RewriteObjCForCollectionStmt(StmtForCollection,
5675 OrigStmtRange.getEnd());
5676 if (BreakStmt *StmtBreakStmt =
5677 dyn_cast<BreakStmt>(S))
5678 return RewriteBreakStmt(StmtBreakStmt);
5679 if (ContinueStmt *StmtContinueStmt =
5680 dyn_cast<ContinueStmt>(S))
5681 return RewriteContinueStmt(StmtContinueStmt);
5682
5683 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5684 // and cast exprs.
5685 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5686 // FIXME: What we're doing here is modifying the type-specifier that
5687 // precedes the first Decl. In the future the DeclGroup should have
5688 // a separate type-specifier that we can rewrite.
5689 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5690 // the context of an ObjCForCollectionStmt. For example:
5691 // NSArray *someArray;
5692 // for (id <FooProtocol> index in someArray) ;
5693 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5694 // and it depends on the original text locations/positions.
5695 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5696 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5697
5698 // Blocks rewrite rules.
5699 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5700 DI != DE; ++DI) {
5701 Decl *SD = *DI;
5702 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5703 if (isTopLevelBlockPointerType(ND->getType()))
5704 RewriteBlockPointerDecl(ND);
5705 else if (ND->getType()->isFunctionPointerType())
5706 CheckFunctionPointerDecl(ND->getType(), ND);
5707 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5708 if (VD->hasAttr<BlocksAttr>()) {
5709 static unsigned uniqueByrefDeclCount = 0;
5710 assert(!BlockByRefDeclNo.count(ND) &&
5711 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5712 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005713 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005714 }
5715 else
5716 RewriteTypeOfDecl(VD);
5717 }
5718 }
5719 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5720 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5721 RewriteBlockPointerDecl(TD);
5722 else if (TD->getUnderlyingType()->isFunctionPointerType())
5723 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5724 }
5725 }
5726 }
5727
5728 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5729 RewriteObjCQualifiedInterfaceTypes(CE);
5730
5731 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5732 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5733 assert(!Stmts.empty() && "Statement stack is empty");
5734 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5735 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5736 && "Statement stack mismatch");
5737 Stmts.pop_back();
5738 }
5739 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005740 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5741 ValueDecl *VD = DRE->getDecl();
5742 if (VD->hasAttr<BlocksAttr>())
5743 return RewriteBlockDeclRefExpr(DRE);
5744 if (HasLocalVariableExternalStorage(VD))
5745 return RewriteLocalVariableExternalStorage(DRE);
5746 }
5747
5748 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5749 if (CE->getCallee()->getType()->isBlockPointerType()) {
5750 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5751 ReplaceStmt(S, BlockCall);
5752 return BlockCall;
5753 }
5754 }
5755 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5756 RewriteCastExpr(CE);
5757 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005758 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5759 RewriteImplicitCastObjCExpr(ICE);
5760 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005761#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005762
Fariborz Jahanian11671902012-02-07 17:11:38 +00005763 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5764 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5765 ICE->getSubExpr(),
5766 SourceLocation());
5767 // Get the new text.
5768 std::string SStr;
5769 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005770 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005771 const std::string &Str = Buf.str();
5772
5773 printf("CAST = %s\n", &Str[0]);
5774 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5775 delete S;
5776 return Replacement;
5777 }
5778#endif
5779 // Return this stmt unmodified.
5780 return S;
5781}
5782
5783void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005784 for (auto *FD : RD->fields()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005785 if (isTopLevelBlockPointerType(FD->getType()))
5786 RewriteBlockPointerDecl(FD);
5787 if (FD->getType()->isObjCQualifiedIdType() ||
5788 FD->getType()->isObjCQualifiedInterfaceType())
5789 RewriteObjCQualifiedInterfaceTypes(FD);
5790 }
5791}
5792
5793/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5794/// main file of the input.
5795void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5796 switch (D->getKind()) {
5797 case Decl::Function: {
5798 FunctionDecl *FD = cast<FunctionDecl>(D);
5799 if (FD->isOverloadedOperator())
5800 return;
5801
5802 // Since function prototypes don't have ParmDecl's, we check the function
5803 // prototype. This enables us to rewrite function declarations and
5804 // definitions using the same code.
5805 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5806
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005807 if (!FD->isThisDeclarationADefinition())
5808 break;
5809
Fariborz Jahanian11671902012-02-07 17:11:38 +00005810 // FIXME: If this should support Obj-C++, support CXXTryStmt
5811 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5812 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005813 CurrentBody = Body;
5814 Body =
5815 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5816 FD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005817 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005818 if (PropParentMap) {
5819 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005820 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005821 }
5822 // This synthesizes and inserts the block "impl" struct, invoke function,
5823 // and any copy/dispose helper functions.
5824 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005825 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005826 CurFunctionDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005827 }
5828 break;
5829 }
5830 case Decl::ObjCMethod: {
5831 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5832 if (CompoundStmt *Body = MD->getCompoundBody()) {
5833 CurMethodDef = MD;
5834 CurrentBody = Body;
5835 Body =
5836 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5837 MD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005838 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005839 if (PropParentMap) {
5840 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005841 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005842 }
5843 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005844 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005845 CurMethodDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005846 }
5847 break;
5848 }
5849 case Decl::ObjCImplementation: {
5850 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5851 ClassImplementation.push_back(CI);
5852 break;
5853 }
5854 case Decl::ObjCCategoryImpl: {
5855 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5856 CategoryImplementation.push_back(CI);
5857 break;
5858 }
5859 case Decl::Var: {
5860 VarDecl *VD = cast<VarDecl>(D);
5861 RewriteObjCQualifiedInterfaceTypes(VD);
5862 if (isTopLevelBlockPointerType(VD->getType()))
5863 RewriteBlockPointerDecl(VD);
5864 else if (VD->getType()->isFunctionPointerType()) {
5865 CheckFunctionPointerDecl(VD->getType(), VD);
5866 if (VD->getInit()) {
5867 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5868 RewriteCastExpr(CE);
5869 }
5870 }
5871 } else if (VD->getType()->isRecordType()) {
5872 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5873 if (RD->isCompleteDefinition())
5874 RewriteRecordBody(RD);
5875 }
5876 if (VD->getInit()) {
5877 GlobalVarDecl = VD;
5878 CurrentBody = VD->getInit();
5879 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Craig Topper8ae12032014-05-07 06:21:57 +00005880 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005881 if (PropParentMap) {
5882 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005883 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005884 }
5885 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Craig Topper8ae12032014-05-07 06:21:57 +00005886 GlobalVarDecl = nullptr;
5887
Fariborz Jahanian11671902012-02-07 17:11:38 +00005888 // This is needed for blocks.
5889 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5890 RewriteCastExpr(CE);
5891 }
5892 }
5893 break;
5894 }
5895 case Decl::TypeAlias:
5896 case Decl::Typedef: {
5897 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5898 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5899 RewriteBlockPointerDecl(TD);
5900 else if (TD->getUnderlyingType()->isFunctionPointerType())
5901 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005902 else
5903 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005904 }
5905 break;
5906 }
5907 case Decl::CXXRecord:
5908 case Decl::Record: {
5909 RecordDecl *RD = cast<RecordDecl>(D);
5910 if (RD->isCompleteDefinition())
5911 RewriteRecordBody(RD);
5912 break;
5913 }
5914 default:
5915 break;
5916 }
5917 // Nothing yet.
5918}
5919
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005920/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5921/// protocol reference symbols in the for of:
5922/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5923static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5924 ObjCProtocolDecl *PDecl,
5925 std::string &Result) {
5926 // Also output .objc_protorefs$B section and its meta-data.
5927 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005928 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005929 Result += "struct _protocol_t *";
5930 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5931 Result += PDecl->getNameAsString();
5932 Result += " = &";
5933 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5934 Result += ";\n";
5935}
5936
Fariborz Jahanian11671902012-02-07 17:11:38 +00005937void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5938 if (Diags.hasErrorOccurred())
5939 return;
5940
5941 RewriteInclude();
5942
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005943 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005944 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005945 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005946 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005947 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5948 HandleTopLevelSingleDecl(FDecl);
5949 }
5950
Fariborz Jahanian11671902012-02-07 17:11:38 +00005951 // Here's a great place to add any extra declarations that may be needed.
5952 // Write out meta data for each @protocol(<expr>).
Craig Topperc6914d02014-08-25 04:15:02 +00005953 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5954 RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5955 Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005956 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005957
5958 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00005959
5960 if (ClassImplementation.size() || CategoryImplementation.size())
5961 RewriteImplementations();
5962
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00005963 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5964 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5965 // Write struct declaration for the class matching its ivar declarations.
5966 // Note that for modern abi, this is postponed until the end of TU
5967 // because class extensions and the implementation might declare their own
5968 // private ivars.
5969 RewriteInterfaceDecl(CDecl);
5970 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005971
Fariborz Jahanian11671902012-02-07 17:11:38 +00005972 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5973 // we are done.
5974 if (const RewriteBuffer *RewriteBuf =
5975 Rewrite.getRewriteBufferFor(MainFileID)) {
5976 //printf("Changed:\n");
5977 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5978 } else {
5979 llvm::errs() << "No changes\n";
5980 }
5981
5982 if (ClassImplementation.size() || CategoryImplementation.size() ||
5983 ProtocolExprDecls.size()) {
5984 // Rewrite Objective-c meta data*
5985 std::string ResultStr;
5986 RewriteMetaDataIntoBuffer(ResultStr);
5987 // Emit metadata.
5988 *OutFile << ResultStr;
5989 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005990 // Emit ImageInfo;
5991 {
5992 std::string ResultStr;
5993 WriteImageInfo(ResultStr);
5994 *OutFile << ResultStr;
5995 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005996 OutFile->flush();
5997}
5998
5999void RewriteModernObjC::Initialize(ASTContext &context) {
6000 InitializeCommon(context);
6001
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00006002 Preamble += "#ifndef __OBJC2__\n";
6003 Preamble += "#define __OBJC2__\n";
6004 Preamble += "#endif\n";
6005
Fariborz Jahanian11671902012-02-07 17:11:38 +00006006 // declaring objc_selector outside the parameter list removes a silly
6007 // scope related warning...
6008 if (IsHeader)
6009 Preamble = "#pragma once\n";
6010 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00006011 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6012 Preamble += "\n\tstruct objc_object *superClass; ";
6013 // Add a constructor for creating temporary objects.
6014 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6015 Preamble += ": object(o), superClass(s) {} ";
6016 Preamble += "\n};\n";
6017
Fariborz Jahanian11671902012-02-07 17:11:38 +00006018 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006019 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006020 // These are currently generated.
6021 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006022 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006023 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006024 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6025 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006026 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006027 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006028 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6029 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006030 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006031
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006032 // These need be generated for performance. Currently they are not,
6033 // using API calls instead.
6034 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6035 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6036 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6037
Fariborz Jahanian11671902012-02-07 17:11:38 +00006038 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006039 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6040 Preamble += "typedef struct objc_object Protocol;\n";
6041 Preamble += "#define _REWRITER_typedef_Protocol\n";
6042 Preamble += "#endif\n";
6043 if (LangOpts.MicrosoftExt) {
6044 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6045 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006046 }
6047 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006048 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006049
6050 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6051 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6052 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6053 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6054 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6055
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006056 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006057 Preamble += "(const char *);\n";
6058 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6059 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006060 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006061 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00006062 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006063 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00006064 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6065 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006066 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00006067 Preamble += "#ifdef _WIN64\n";
6068 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6069 Preamble += "#else\n";
6070 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6071 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006072 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6073 Preamble += "struct __objcFastEnumerationState {\n\t";
6074 Preamble += "unsigned long state;\n\t";
6075 Preamble += "void **itemsPtr;\n\t";
6076 Preamble += "unsigned long *mutationsPtr;\n\t";
6077 Preamble += "unsigned long extra[5];\n};\n";
6078 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6079 Preamble += "#define __FASTENUMERATIONSTATE\n";
6080 Preamble += "#endif\n";
6081 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6082 Preamble += "struct __NSConstantStringImpl {\n";
6083 Preamble += " int *isa;\n";
6084 Preamble += " int flags;\n";
6085 Preamble += " char *str;\n";
Fariborz Jahaniandb3a5dc2014-04-16 17:03:06 +00006086 Preamble += "#if _WIN64\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00006087 Preamble += " long long length;\n";
6088 Preamble += "#else\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006089 Preamble += " long length;\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00006090 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006091 Preamble += "};\n";
6092 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6093 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6094 Preamble += "#else\n";
6095 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6096 Preamble += "#endif\n";
6097 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6098 Preamble += "#endif\n";
6099 // Blocks preamble.
6100 Preamble += "#ifndef BLOCK_IMPL\n";
6101 Preamble += "#define BLOCK_IMPL\n";
6102 Preamble += "struct __block_impl {\n";
6103 Preamble += " void *isa;\n";
6104 Preamble += " int Flags;\n";
6105 Preamble += " int Reserved;\n";
6106 Preamble += " void *FuncPtr;\n";
6107 Preamble += "};\n";
6108 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6109 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6110 Preamble += "extern \"C\" __declspec(dllexport) "
6111 "void _Block_object_assign(void *, const void *, const int);\n";
6112 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6113 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6114 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6115 Preamble += "#else\n";
6116 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6117 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6118 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6119 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6120 Preamble += "#endif\n";
6121 Preamble += "#endif\n";
6122 if (LangOpts.MicrosoftExt) {
6123 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6124 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6125 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6126 Preamble += "#define __attribute__(X)\n";
6127 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006128 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006129 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006130 Preamble += "#endif\n";
6131 Preamble += "#ifndef __block\n";
6132 Preamble += "#define __block\n";
6133 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006134 }
6135 else {
6136 Preamble += "#define __block\n";
6137 Preamble += "#define __weak\n";
6138 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006139
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006140 // Declarations required for modern objective-c array and dictionary literals.
6141 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006142 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006143 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006144 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006145 Preamble += "\tva_list marker;\n";
6146 Preamble += "\tva_start(marker, count);\n";
6147 Preamble += "\tarr = new void *[count];\n";
6148 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6149 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6150 Preamble += "\tva_end( marker );\n";
6151 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006152 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006153 Preamble += "\tdelete[] arr;\n";
6154 Preamble += " }\n";
6155 Preamble += "};\n";
6156
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006157 // Declaration required for implementation of @autoreleasepool statement.
6158 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6159 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6160 Preamble += "struct __AtAutoreleasePool {\n";
6161 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6162 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6163 Preamble += " void * atautoreleasepoolobj;\n";
6164 Preamble += "};\n";
6165
Fariborz Jahanian11671902012-02-07 17:11:38 +00006166 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6167 // as this avoids warning in any 64bit/32bit compilation model.
6168 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6169}
6170
6171/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6172/// ivar offset.
6173void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6174 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006175 Result += "__OFFSETOFIVAR__(struct ";
6176 Result += ivar->getContainingInterface()->getNameAsString();
6177 if (LangOpts.MicrosoftExt)
6178 Result += "_IMPL";
6179 Result += ", ";
6180 if (ivar->isBitField())
6181 ObjCIvarBitfieldGroupDecl(ivar, Result);
6182 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006183 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006184 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006185}
6186
6187/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6188/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006189/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006190/// char *attributes;
6191/// }
6192
6193/// struct _prop_list_t {
6194/// uint32_t entsize; // sizeof(struct _prop_t)
6195/// uint32_t count_of_properties;
6196/// struct _prop_t prop_list[count_of_properties];
6197/// }
6198
6199/// struct _protocol_t;
6200
6201/// struct _protocol_list_t {
6202/// long protocol_count; // Note, this is 32/64 bit
6203/// struct _protocol_t * protocol_list[protocol_count];
6204/// }
6205
6206/// struct _objc_method {
6207/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006208/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006209/// char *_imp;
6210/// }
6211
6212/// struct _method_list_t {
6213/// uint32_t entsize; // sizeof(struct _objc_method)
6214/// uint32_t method_count;
6215/// struct _objc_method method_list[method_count];
6216/// }
6217
6218/// struct _protocol_t {
6219/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006220/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006221/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006222/// const struct method_list_t *instance_methods;
6223/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006224/// const struct method_list_t *optionalInstanceMethods;
6225/// const struct method_list_t *optionalClassMethods;
6226/// const struct _prop_list_t * properties;
6227/// const uint32_t size; // sizeof(struct _protocol_t)
6228/// const uint32_t flags; // = 0
6229/// const char ** extendedMethodTypes;
6230/// }
6231
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006232/// struct _ivar_t {
6233/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006234/// const char *name;
6235/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006236/// uint32_t alignment;
6237/// uint32_t size;
6238/// }
6239
6240/// struct _ivar_list_t {
6241/// uint32 entsize; // sizeof(struct _ivar_t)
6242/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006243/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006244/// }
6245
6246/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006247/// uint32_t flags;
6248/// uint32_t instanceStart;
6249/// uint32_t instanceSize;
6250/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006251/// const uint8_t *ivarLayout;
6252/// const char *name;
6253/// const struct _method_list_t *baseMethods;
6254/// const struct _protocol_list_t *baseProtocols;
6255/// const struct _ivar_list_t *ivars;
6256/// const uint8_t *weakIvarLayout;
6257/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006258/// }
6259
6260/// struct _class_t {
6261/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006262/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006263/// void *cache;
6264/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006265/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006266/// }
6267
6268/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006269/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006270/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006271/// const struct _method_list_t *instance_methods;
6272/// const struct _method_list_t *class_methods;
6273/// const struct _protocol_list_t *protocols;
6274/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006275/// }
6276
6277/// MessageRefTy - LLVM for:
6278/// struct _message_ref_t {
6279/// IMP messenger;
6280/// SEL name;
6281/// };
6282
6283/// SuperMessageRefTy - LLVM for:
6284/// struct _super_message_ref_t {
6285/// SUPER_IMP messenger;
6286/// SEL name;
6287/// };
6288
Fariborz Jahanian45489622012-03-14 18:09:23 +00006289static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006290 static bool meta_data_declared = false;
6291 if (meta_data_declared)
6292 return;
6293
6294 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006295 Result += "\tconst char *name;\n";
6296 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006297 Result += "};\n";
6298
6299 Result += "\nstruct _protocol_t;\n";
6300
Fariborz Jahanian11671902012-02-07 17:11:38 +00006301 Result += "\nstruct _objc_method {\n";
6302 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006303 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006304 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006305 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006306
6307 Result += "\nstruct _protocol_t {\n";
6308 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006309 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006310 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006311 Result += "\tconst struct method_list_t *instance_methods;\n";
6312 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006313 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6314 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6315 Result += "\tconst struct _prop_list_t * properties;\n";
6316 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6317 Result += "\tconst unsigned int flags; // = 0\n";
6318 Result += "\tconst char ** extendedMethodTypes;\n";
6319 Result += "};\n";
6320
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006321 Result += "\nstruct _ivar_t {\n";
6322 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006323 Result += "\tconst char *name;\n";
6324 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006325 Result += "\tunsigned int alignment;\n";
6326 Result += "\tunsigned int size;\n";
6327 Result += "};\n";
6328
6329 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006330 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006331 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006332 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006333 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6334 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006335 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006336 Result += "\tconst unsigned char *ivarLayout;\n";
6337 Result += "\tconst char *name;\n";
6338 Result += "\tconst struct _method_list_t *baseMethods;\n";
6339 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6340 Result += "\tconst struct _ivar_list_t *ivars;\n";
6341 Result += "\tconst unsigned char *weakIvarLayout;\n";
6342 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006343 Result += "};\n";
6344
6345 Result += "\nstruct _class_t {\n";
6346 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006347 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006348 Result += "\tvoid *cache;\n";
6349 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006350 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006351 Result += "};\n";
6352
6353 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006354 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006355 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006356 Result += "\tconst struct _method_list_t *instance_methods;\n";
6357 Result += "\tconst struct _method_list_t *class_methods;\n";
6358 Result += "\tconst struct _protocol_list_t *protocols;\n";
6359 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006360 Result += "};\n";
6361
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006362 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006363 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006364 meta_data_declared = true;
6365}
6366
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006367static void Write_protocol_list_t_TypeDecl(std::string &Result,
6368 long super_protocol_count) {
6369 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6370 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6371 Result += "\tstruct _protocol_t *super_protocols[";
6372 Result += utostr(super_protocol_count); Result += "];\n";
6373 Result += "}";
6374}
6375
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006376static void Write_method_list_t_TypeDecl(std::string &Result,
6377 unsigned int method_count) {
6378 Result += "struct /*_method_list_t*/"; Result += " {\n";
6379 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6380 Result += "\tunsigned int method_count;\n";
6381 Result += "\tstruct _objc_method method_list[";
6382 Result += utostr(method_count); Result += "];\n";
6383 Result += "}";
6384}
6385
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006386static void Write__prop_list_t_TypeDecl(std::string &Result,
6387 unsigned int property_count) {
6388 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6389 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6390 Result += "\tunsigned int count_of_properties;\n";
6391 Result += "\tstruct _prop_t prop_list[";
6392 Result += utostr(property_count); Result += "];\n";
6393 Result += "}";
6394}
6395
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006396static void Write__ivar_list_t_TypeDecl(std::string &Result,
6397 unsigned int ivar_count) {
6398 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6399 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6400 Result += "\tunsigned int count;\n";
6401 Result += "\tstruct _ivar_t ivar_list[";
6402 Result += utostr(ivar_count); Result += "];\n";
6403 Result += "}";
6404}
6405
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006406static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6407 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6408 StringRef VarName,
6409 StringRef ProtocolName) {
6410 if (SuperProtocols.size() > 0) {
6411 Result += "\nstatic ";
6412 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6413 Result += " "; Result += VarName;
6414 Result += ProtocolName;
6415 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6416 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6417 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6418 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6419 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6420 Result += SuperPD->getNameAsString();
6421 if (i == e-1)
6422 Result += "\n};\n";
6423 else
6424 Result += ",\n";
6425 }
6426 }
6427}
6428
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006429static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6430 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006431 ArrayRef<ObjCMethodDecl *> Methods,
6432 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006433 StringRef TopLevelDeclName,
6434 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006435 if (Methods.size() > 0) {
6436 Result += "\nstatic ";
6437 Write_method_list_t_TypeDecl(Result, Methods.size());
6438 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006439 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006440 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6441 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6442 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6443 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6444 ObjCMethodDecl *MD = Methods[i];
6445 if (i == 0)
6446 Result += "\t{{(struct objc_selector *)\"";
6447 else
6448 Result += "\t{(struct objc_selector *)\"";
6449 Result += (MD)->getSelector().getAsString(); Result += "\"";
6450 Result += ", ";
6451 std::string MethodTypeString;
6452 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6453 Result += "\""; Result += MethodTypeString; Result += "\"";
6454 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006455 if (!MethodImpl)
6456 Result += "0";
6457 else {
6458 Result += "(void *)";
6459 Result += RewriteObj.MethodInternalNames[MD];
6460 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006461 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006462 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006463 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006464 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006465 }
6466 Result += "};\n";
6467 }
6468}
6469
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006470static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006471 ASTContext *Context, std::string &Result,
6472 ArrayRef<ObjCPropertyDecl *> Properties,
6473 const Decl *Container,
6474 StringRef VarName,
6475 StringRef ProtocolName) {
6476 if (Properties.size() > 0) {
6477 Result += "\nstatic ";
6478 Write__prop_list_t_TypeDecl(Result, Properties.size());
6479 Result += " "; Result += VarName;
6480 Result += ProtocolName;
6481 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6482 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6483 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6484 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6485 ObjCPropertyDecl *PropDecl = Properties[i];
6486 if (i == 0)
6487 Result += "\t{{\"";
6488 else
6489 Result += "\t{\"";
6490 Result += PropDecl->getName(); Result += "\",";
6491 std::string PropertyTypeString, QuotePropertyTypeString;
6492 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6493 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6494 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6495 if (i == e-1)
6496 Result += "}}\n";
6497 else
6498 Result += "},\n";
6499 }
6500 Result += "};\n";
6501 }
6502}
6503
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006504// Metadata flags
6505enum MetaDataDlags {
6506 CLS = 0x0,
6507 CLS_META = 0x1,
6508 CLS_ROOT = 0x2,
6509 OBJC2_CLS_HIDDEN = 0x10,
6510 CLS_EXCEPTION = 0x20,
6511
6512 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6513 CLS_HAS_IVAR_RELEASER = 0x40,
6514 /// class was compiled with -fobjc-arr
6515 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6516};
6517
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006518static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6519 unsigned int flags,
6520 const std::string &InstanceStart,
6521 const std::string &InstanceSize,
6522 ArrayRef<ObjCMethodDecl *>baseMethods,
6523 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6524 ArrayRef<ObjCIvarDecl *>ivars,
6525 ArrayRef<ObjCPropertyDecl *>Properties,
6526 StringRef VarName,
6527 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006528 Result += "\nstatic struct _class_ro_t ";
6529 Result += VarName; Result += ClassName;
6530 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6531 Result += "\t";
6532 Result += llvm::utostr(flags); Result += ", ";
6533 Result += InstanceStart; Result += ", ";
6534 Result += InstanceSize; Result += ", \n";
6535 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006536 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6537 if (Triple.getArch() == llvm::Triple::x86_64)
6538 // uint32_t const reserved; // only when building for 64bit targets
6539 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006540 // const uint8_t * const ivarLayout;
6541 Result += "0, \n\t";
6542 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006543 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006544 if (baseMethods.size() > 0) {
6545 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006546 if (metaclass)
6547 Result += "_OBJC_$_CLASS_METHODS_";
6548 else
6549 Result += "_OBJC_$_INSTANCE_METHODS_";
6550 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006551 Result += ",\n\t";
6552 }
6553 else
6554 Result += "0, \n\t";
6555
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006556 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006557 Result += "(const struct _objc_protocol_list *)&";
6558 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6559 Result += ",\n\t";
6560 }
6561 else
6562 Result += "0, \n\t";
6563
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006564 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006565 Result += "(const struct _ivar_list_t *)&";
6566 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6567 Result += ",\n\t";
6568 }
6569 else
6570 Result += "0, \n\t";
6571
6572 // weakIvarLayout
6573 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006574 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006575 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006576 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006577 Result += ",\n";
6578 }
6579 else
6580 Result += "0, \n";
6581
6582 Result += "};\n";
6583}
6584
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006585static void Write_class_t(ASTContext *Context, std::string &Result,
6586 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006587 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6588 bool rootClass = (!CDecl->getSuperClass());
6589 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006590
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006591 if (!rootClass) {
6592 // Find the Root class
6593 RootClass = CDecl->getSuperClass();
6594 while (RootClass->getSuperClass()) {
6595 RootClass = RootClass->getSuperClass();
6596 }
6597 }
6598
6599 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006600 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006601 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006602 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006603 if (CDecl->getImplementation())
6604 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006605 else
6606 Result += "__declspec(dllimport) ";
6607
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006608 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006609 Result += CDecl->getNameAsString();
6610 Result += ";\n";
6611 }
6612 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006613 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006614 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006615 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006616 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006617 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006618 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006619 else
6620 Result += "__declspec(dllimport) ";
6621
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006622 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006623 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006624 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006625 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006626
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006627 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006628 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006629 if (RootClass->getImplementation())
6630 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006631 else
6632 Result += "__declspec(dllimport) ";
6633
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006634 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006635 Result += VarName;
6636 Result += RootClass->getNameAsString();
6637 Result += ";\n";
6638 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006639 }
6640
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006641 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6642 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006643 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6644 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006645 if (metaclass) {
6646 if (!rootClass) {
6647 Result += "0, // &"; Result += VarName;
6648 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006649 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006650 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006651 Result += CDecl->getSuperClass()->getNameAsString();
6652 Result += ",\n\t";
6653 }
6654 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006655 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006656 Result += CDecl->getNameAsString();
6657 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006658 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006659 Result += ",\n\t";
6660 }
6661 }
6662 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006663 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006664 Result += CDecl->getNameAsString();
6665 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006666 if (!rootClass) {
6667 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006668 Result += CDecl->getSuperClass()->getNameAsString();
6669 Result += ",\n\t";
6670 }
6671 else
6672 Result += "0,\n\t";
6673 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006674 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6675 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6676 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006677 Result += "&_OBJC_METACLASS_RO_$_";
6678 else
6679 Result += "&_OBJC_CLASS_RO_$_";
6680 Result += CDecl->getNameAsString();
6681 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006682
6683 // Add static function to initialize some of the meta-data fields.
6684 // avoid doing it twice.
6685 if (metaclass)
6686 return;
6687
6688 const ObjCInterfaceDecl *SuperClass =
6689 rootClass ? CDecl : CDecl->getSuperClass();
6690
6691 Result += "static void OBJC_CLASS_SETUP_$_";
6692 Result += CDecl->getNameAsString();
6693 Result += "(void ) {\n";
6694 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6695 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006696 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006697
6698 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006699 Result += ".superclass = ";
6700 if (rootClass)
6701 Result += "&OBJC_CLASS_$_";
6702 else
6703 Result += "&OBJC_METACLASS_$_";
6704
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006705 Result += SuperClass->getNameAsString(); Result += ";\n";
6706
6707 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6708 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6709
6710 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6711 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6712 Result += CDecl->getNameAsString(); Result += ";\n";
6713
6714 if (!rootClass) {
6715 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6716 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6717 Result += SuperClass->getNameAsString(); Result += ";\n";
6718 }
6719
6720 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6721 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6722 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006723}
6724
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006725static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6726 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006727 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006728 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006729 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6730 ArrayRef<ObjCMethodDecl *> ClassMethods,
6731 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6732 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006733 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006734 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006735 // must declare an extern class object in case this class is not implemented
6736 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006737 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006738 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006739 if (ClassDecl->getImplementation())
6740 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006741 else
6742 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006743
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006744 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006745 Result += "OBJC_CLASS_$_"; Result += ClassName;
6746 Result += ";\n";
6747
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006748 Result += "\nstatic struct _category_t ";
6749 Result += "_OBJC_$_CATEGORY_";
6750 Result += ClassName; Result += "_$_"; Result += CatName;
6751 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6752 Result += "{\n";
6753 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006754 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006755 Result += ",\n";
6756 if (InstanceMethods.size() > 0) {
6757 Result += "\t(const struct _method_list_t *)&";
6758 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6759 Result += ClassName; Result += "_$_"; Result += CatName;
6760 Result += ",\n";
6761 }
6762 else
6763 Result += "\t0,\n";
6764
6765 if (ClassMethods.size() > 0) {
6766 Result += "\t(const struct _method_list_t *)&";
6767 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6768 Result += ClassName; Result += "_$_"; Result += CatName;
6769 Result += ",\n";
6770 }
6771 else
6772 Result += "\t0,\n";
6773
6774 if (RefedProtocols.size() > 0) {
6775 Result += "\t(const struct _protocol_list_t *)&";
6776 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6777 Result += ClassName; Result += "_$_"; Result += CatName;
6778 Result += ",\n";
6779 }
6780 else
6781 Result += "\t0,\n";
6782
6783 if (ClassProperties.size() > 0) {
6784 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6785 Result += ClassName; Result += "_$_"; Result += CatName;
6786 Result += ",\n";
6787 }
6788 else
6789 Result += "\t0,\n";
6790
6791 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006792
6793 // Add static function to initialize the class pointer in the category structure.
6794 Result += "static void OBJC_CATEGORY_SETUP_$_";
6795 Result += ClassDecl->getNameAsString();
6796 Result += "_$_";
6797 Result += CatName;
6798 Result += "(void ) {\n";
6799 Result += "\t_OBJC_$_CATEGORY_";
6800 Result += ClassDecl->getNameAsString();
6801 Result += "_$_";
6802 Result += CatName;
6803 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6804 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006805}
6806
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006807static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6808 ASTContext *Context, std::string &Result,
6809 ArrayRef<ObjCMethodDecl *> Methods,
6810 StringRef VarName,
6811 StringRef ProtocolName) {
6812 if (Methods.size() == 0)
6813 return;
6814
6815 Result += "\nstatic const char *";
6816 Result += VarName; Result += ProtocolName;
6817 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6818 Result += "{\n";
6819 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6820 ObjCMethodDecl *MD = Methods[i];
6821 std::string MethodTypeString, QuoteMethodTypeString;
6822 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6823 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6824 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6825 if (i == e-1)
6826 Result += "\n};\n";
6827 else {
6828 Result += ",\n";
6829 }
6830 }
6831}
6832
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006833static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6834 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006835 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006836 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006837 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006838 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6839 // this is what happens:
6840 /**
6841 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6842 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6843 Class->getVisibility() == HiddenVisibility)
6844 Visibility shoud be: HiddenVisibility;
6845 else
6846 Visibility shoud be: DefaultVisibility;
6847 */
6848
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006849 Result += "\n";
6850 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6851 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006852 if (Context->getLangOpts().MicrosoftExt)
6853 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6854
6855 if (!Context->getLangOpts().MicrosoftExt ||
6856 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006857 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006858 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006859 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006860 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006861 if (Ivars[i]->isBitField())
6862 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6863 else
6864 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006865 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6866 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006867 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6868 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006869 if (Ivars[i]->isBitField()) {
6870 // skip over rest of the ivar bitfields.
6871 SKIP_BITFIELDS(i , e, Ivars);
6872 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006873 }
6874}
6875
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006876static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6877 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006878 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006879 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006880 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006881 if (OriginalIvars.size() > 0) {
6882 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6883 SmallVector<ObjCIvarDecl *, 8> Ivars;
6884 // strip off all but the first ivar bitfield from each group of ivars.
6885 // Such ivars in the ivar list table will be replaced by their grouping struct
6886 // 'ivar'.
6887 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6888 if (OriginalIvars[i]->isBitField()) {
6889 Ivars.push_back(OriginalIvars[i]);
6890 // skip over rest of the ivar bitfields.
6891 SKIP_BITFIELDS(i , e, OriginalIvars);
6892 }
6893 else
6894 Ivars.push_back(OriginalIvars[i]);
6895 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006896
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006897 Result += "\nstatic ";
6898 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6899 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006900 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006901 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6902 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6903 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6904 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6905 ObjCIvarDecl *IvarDecl = Ivars[i];
6906 if (i == 0)
6907 Result += "\t{{";
6908 else
6909 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006910 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006911 if (Ivars[i]->isBitField())
6912 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6913 else
6914 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006915 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006916
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006917 Result += "\"";
6918 if (Ivars[i]->isBitField())
6919 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6920 else
6921 Result += IvarDecl->getName();
6922 Result += "\", ";
6923
6924 QualType IVQT = IvarDecl->getType();
6925 if (IvarDecl->isBitField())
6926 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6927
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006928 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006929 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006930 IvarDecl);
6931 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6932 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6933
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006934 // FIXME. this alignment represents the host alignment and need be changed to
6935 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006936 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006937 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006938 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006939 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00006940 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006941 if (i == e-1)
6942 Result += "}}\n";
6943 else
6944 Result += "},\n";
6945 }
6946 Result += "};\n";
6947 }
6948}
6949
Fariborz Jahanian11671902012-02-07 17:11:38 +00006950/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006951void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6952 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006953
Fariborz Jahanian11671902012-02-07 17:11:38 +00006954 // Do not synthesize the protocol more than once.
6955 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6956 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00006957 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006958
6959 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6960 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006961 // Must write out all protocol definitions in current qualifier list,
6962 // and in their nested qualifiers before writing out current definition.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006963 for (auto *I : PDecl->protocols())
6964 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006965
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006966 // Construct method lists.
6967 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6968 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006969 for (auto *MD : PDecl->instance_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006970 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6971 OptInstanceMethods.push_back(MD);
6972 } else {
6973 InstanceMethods.push_back(MD);
6974 }
6975 }
6976
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006977 for (auto *MD : PDecl->class_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006978 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6979 OptClassMethods.push_back(MD);
6980 } else {
6981 ClassMethods.push_back(MD);
6982 }
6983 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006984 std::vector<ObjCMethodDecl *> AllMethods;
6985 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6986 AllMethods.push_back(InstanceMethods[i]);
6987 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6988 AllMethods.push_back(ClassMethods[i]);
6989 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6990 AllMethods.push_back(OptInstanceMethods[i]);
6991 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6992 AllMethods.push_back(OptClassMethods[i]);
6993
6994 Write__extendedMethodTypes_initializer(*this, Context, Result,
6995 AllMethods,
6996 "_OBJC_PROTOCOL_METHOD_TYPES_",
6997 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006998 // Protocol's super protocol list
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006999 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007000 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7001 "_OBJC_PROTOCOL_REFS_",
7002 PDecl->getNameAsString());
7003
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007004 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007005 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007006 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007007
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007008 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007009 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007010 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007011
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007012 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007013 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007014 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007015
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007016 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007017 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007018 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007019
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007020 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007021 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(PDecl->properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007022 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Craig Topper8ae12032014-05-07 06:21:57 +00007023 /* Container */nullptr,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007024 "_OBJC_PROTOCOL_PROPERTIES_",
7025 PDecl->getNameAsString());
Craig Topper8ae12032014-05-07 06:21:57 +00007026
Fariborz Jahanian48985802012-02-08 00:50:52 +00007027 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007028 Result += "\n";
7029 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007030 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007031 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007032 Result += PDecl->getNameAsString();
Fariborz Jahanian48985802012-02-08 00:50:52 +00007033 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7034 Result += "\t0,\n"; // id is; is null
7035 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007036 if (SuperProtocols.size() > 0) {
7037 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7038 Result += PDecl->getNameAsString(); Result += ",\n";
7039 }
7040 else
7041 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007042 if (InstanceMethods.size() > 0) {
7043 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7044 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007045 }
7046 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007047 Result += "\t0,\n";
7048
7049 if (ClassMethods.size() > 0) {
7050 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7051 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007052 }
7053 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007054 Result += "\t0,\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007055
Fariborz Jahanian48985802012-02-08 00:50:52 +00007056 if (OptInstanceMethods.size() > 0) {
7057 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7058 Result += PDecl->getNameAsString(); Result += ",\n";
7059 }
7060 else
7061 Result += "\t0,\n";
7062
7063 if (OptClassMethods.size() > 0) {
7064 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7065 Result += PDecl->getNameAsString(); Result += ",\n";
7066 }
7067 else
7068 Result += "\t0,\n";
7069
7070 if (ProtocolProperties.size() > 0) {
7071 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7072 Result += PDecl->getNameAsString(); Result += ",\n";
7073 }
7074 else
7075 Result += "\t0,\n";
7076
7077 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7078 Result += "\t0,\n";
7079
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007080 if (AllMethods.size() > 0) {
7081 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7082 Result += PDecl->getNameAsString();
7083 Result += "\n};\n";
7084 }
7085 else
7086 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007087
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007088 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007089 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007090 Result += "struct _protocol_t *";
7091 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7092 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7093 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007094
Fariborz Jahanian11671902012-02-07 17:11:38 +00007095 // Mark this protocol as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00007096 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007097 llvm_unreachable("protocol already synthesized");
7098
7099}
7100
7101void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7102 const ObjCList<ObjCProtocolDecl> &Protocols,
7103 StringRef prefix, StringRef ClassName,
7104 std::string &Result) {
7105 if (Protocols.empty()) return;
7106
7107 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007108 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007109
7110 // Output the top lovel protocol meta-data for the class.
7111 /* struct _objc_protocol_list {
7112 struct _objc_protocol_list *next;
7113 int protocol_count;
7114 struct _objc_protocol *class_protocols[];
7115 }
7116 */
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007117 Result += "\n";
7118 if (LangOpts.MicrosoftExt)
7119 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7120 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007121 Result += "\tstruct _objc_protocol_list *next;\n";
7122 Result += "\tint protocol_count;\n";
7123 Result += "\tstruct _objc_protocol *class_protocols[";
7124 Result += utostr(Protocols.size());
7125 Result += "];\n} _OBJC_";
7126 Result += prefix;
7127 Result += "_PROTOCOLS_";
7128 Result += ClassName;
7129 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7130 "{\n\t0, ";
7131 Result += utostr(Protocols.size());
7132 Result += "\n";
7133
7134 Result += "\t,{&_OBJC_PROTOCOL_";
7135 Result += Protocols[0]->getNameAsString();
7136 Result += " \n";
7137
7138 for (unsigned i = 1; i != Protocols.size(); i++) {
7139 Result += "\t ,&_OBJC_PROTOCOL_";
7140 Result += Protocols[i]->getNameAsString();
7141 Result += "\n";
7142 }
7143 Result += "\t }\n};\n";
7144}
7145
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007146/// hasObjCExceptionAttribute - Return true if this class or any super
7147/// class has the __objc_exception__ attribute.
7148/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7149static bool hasObjCExceptionAttribute(ASTContext &Context,
7150 const ObjCInterfaceDecl *OID) {
7151 if (OID->hasAttr<ObjCExceptionAttr>())
7152 return true;
7153 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7154 return hasObjCExceptionAttribute(Context, Super);
7155 return false;
7156}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007157
Fariborz Jahanian11671902012-02-07 17:11:38 +00007158void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7159 std::string &Result) {
7160 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7161
7162 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007163 if (CDecl->isImplicitInterfaceDecl())
7164 assert(false &&
7165 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007166
Fariborz Jahanian45489622012-03-14 18:09:23 +00007167 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007168 SmallVector<ObjCIvarDecl *, 8> IVars;
7169
7170 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7171 IVD; IVD = IVD->getNextIvar()) {
7172 // Ignore unnamed bit-fields.
7173 if (!IVD->getDeclName())
7174 continue;
7175 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007176 }
7177
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007178 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007179 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007180 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007181
7182 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007183 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007184
7185 // If any of our property implementations have associated getters or
7186 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007187 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007188 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007189 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007190 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007191 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007192 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007193 if (!PD)
7194 continue;
7195 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007196 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007197 InstanceMethods.push_back(Getter);
7198 if (PD->isReadOnly())
7199 continue;
7200 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007201 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007202 InstanceMethods.push_back(Setter);
7203 }
7204
7205 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7206 "_OBJC_$_INSTANCE_METHODS_",
7207 IDecl->getNameAsString(), true);
7208
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007209 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007210
7211 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7212 "_OBJC_$_CLASS_METHODS_",
7213 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007214
7215 // Protocols referenced in class declaration?
7216 // Protocol's super protocol list
7217 std::vector<ObjCProtocolDecl *> RefedProtocols;
7218 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7219 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7220 E = Protocols.end();
7221 I != E; ++I) {
7222 RefedProtocols.push_back(*I);
7223 // Must write out all protocol definitions in current qualifier list,
7224 // and in their nested qualifiers before writing out current definition.
7225 RewriteObjCProtocolMetaData(*I, Result);
7226 }
7227
7228 Write_protocol_list_initializer(Context, Result,
7229 RefedProtocols,
7230 "_OBJC_CLASS_PROTOCOLS_$_",
7231 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007232
7233 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007234 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007235 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007236 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007237 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007238 CDecl->getNameAsString());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007239
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007240
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007241 // Data for initializing _class_ro_t metaclass meta-data
7242 uint32_t flags = CLS_META;
7243 std::string InstanceSize;
7244 std::string InstanceStart;
7245
7246
7247 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7248 if (classIsHidden)
7249 flags |= OBJC2_CLS_HIDDEN;
7250
7251 if (!CDecl->getSuperClass())
7252 // class is root
7253 flags |= CLS_ROOT;
7254 InstanceSize = "sizeof(struct _class_t)";
7255 InstanceStart = InstanceSize;
7256 Write__class_ro_t_initializer(Context, Result, flags,
7257 InstanceStart, InstanceSize,
7258 ClassMethods,
Craig Topper8ae12032014-05-07 06:21:57 +00007259 nullptr,
7260 nullptr,
7261 nullptr,
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007262 "_OBJC_METACLASS_RO_$_",
7263 CDecl->getNameAsString());
7264
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007265 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007266 flags = CLS;
7267 if (classIsHidden)
7268 flags |= OBJC2_CLS_HIDDEN;
7269
7270 if (hasObjCExceptionAttribute(*Context, CDecl))
7271 flags |= CLS_EXCEPTION;
7272
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007273 if (!CDecl->getSuperClass())
7274 // class is root
7275 flags |= CLS_ROOT;
7276
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007277 InstanceSize.clear();
7278 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007279 if (!ObjCSynthesizedStructs.count(CDecl)) {
7280 InstanceSize = "0";
7281 InstanceStart = "0";
7282 }
7283 else {
7284 InstanceSize = "sizeof(struct ";
7285 InstanceSize += CDecl->getNameAsString();
7286 InstanceSize += "_IMPL)";
7287
7288 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7289 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007290 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007291 }
7292 else
7293 InstanceStart = InstanceSize;
7294 }
7295 Write__class_ro_t_initializer(Context, Result, flags,
7296 InstanceStart, InstanceSize,
7297 InstanceMethods,
7298 RefedProtocols,
7299 IVars,
7300 ClassProperties,
7301 "_OBJC_CLASS_RO_$_",
7302 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007303
7304 Write_class_t(Context, Result,
7305 "OBJC_METACLASS_$_",
7306 CDecl, /*metaclass*/true);
7307
7308 Write_class_t(Context, Result,
7309 "OBJC_CLASS_$_",
7310 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007311
7312 if (ImplementationIsNonLazy(IDecl))
7313 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007314
Fariborz Jahanian11671902012-02-07 17:11:38 +00007315}
7316
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007317void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7318 int ClsDefCount = ClassImplementation.size();
7319 if (!ClsDefCount)
7320 return;
7321 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7322 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7323 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7324 for (int i = 0; i < ClsDefCount; i++) {
7325 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7326 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7327 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7328 Result += CDecl->getName(); Result += ",\n";
7329 }
7330 Result += "};\n";
7331}
7332
Fariborz Jahanian11671902012-02-07 17:11:38 +00007333void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7334 int ClsDefCount = ClassImplementation.size();
7335 int CatDefCount = CategoryImplementation.size();
7336
7337 // For each implemented class, write out all its meta data.
7338 for (int i = 0; i < ClsDefCount; i++)
7339 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7340
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007341 RewriteClassSetupInitHook(Result);
7342
Fariborz Jahanian11671902012-02-07 17:11:38 +00007343 // For each implemented category, write out all its meta data.
7344 for (int i = 0; i < CatDefCount; i++)
7345 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7346
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007347 RewriteCategorySetupInitHook(Result);
7348
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007349 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007350 if (LangOpts.MicrosoftExt)
7351 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007352 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7353 Result += llvm::utostr(ClsDefCount); Result += "]";
7354 Result +=
7355 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7356 "regular,no_dead_strip\")))= {\n";
7357 for (int i = 0; i < ClsDefCount; i++) {
7358 Result += "\t&OBJC_CLASS_$_";
7359 Result += ClassImplementation[i]->getNameAsString();
7360 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007361 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007362 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007363
7364 if (!DefinedNonLazyClasses.empty()) {
7365 if (LangOpts.MicrosoftExt)
7366 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7367 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7368 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7369 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7370 Result += ",\n";
7371 }
7372 Result += "};\n";
7373 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007374 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007375
7376 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007377 if (LangOpts.MicrosoftExt)
7378 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007379 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7380 Result += llvm::utostr(CatDefCount); Result += "]";
7381 Result +=
7382 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7383 "regular,no_dead_strip\")))= {\n";
7384 for (int i = 0; i < CatDefCount; i++) {
7385 Result += "\t&_OBJC_$_CATEGORY_";
7386 Result +=
7387 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7388 Result += "_$_";
7389 Result += CategoryImplementation[i]->getNameAsString();
7390 Result += ",\n";
7391 }
7392 Result += "};\n";
7393 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007394
7395 if (!DefinedNonLazyCategories.empty()) {
7396 if (LangOpts.MicrosoftExt)
7397 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7398 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7399 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7400 Result += "\t&_OBJC_$_CATEGORY_";
7401 Result +=
7402 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7403 Result += "_$_";
7404 Result += DefinedNonLazyCategories[i]->getNameAsString();
7405 Result += ",\n";
7406 }
7407 Result += "};\n";
7408 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007409}
7410
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007411void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7412 if (LangOpts.MicrosoftExt)
7413 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7414
7415 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7416 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007417 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007418}
7419
Fariborz Jahanian11671902012-02-07 17:11:38 +00007420/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7421/// implementation.
7422void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7423 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007424 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007425 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7426 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007427 ObjCCategoryDecl *CDecl
7428 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007429
7430 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007431 FullCategoryName += "_$_";
7432 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007433
7434 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007435 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007436
7437 // If any of our property implementations have associated getters or
7438 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007439 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007440 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007441 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007442 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007443 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007444 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007445 if (!PD)
7446 continue;
7447 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7448 InstanceMethods.push_back(Getter);
7449 if (PD->isReadOnly())
7450 continue;
7451 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7452 InstanceMethods.push_back(Setter);
7453 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007454
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007455 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7456 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7457 FullCategoryName, true);
7458
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007459 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007460
7461 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7462 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7463 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007464
7465 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007466 // Protocol's super protocol list
Aaron Ballman19a41762014-03-14 12:55:57 +00007467 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7468 for (auto *I : CDecl->protocols())
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007469 // Must write out all protocol definitions in current qualifier list,
7470 // and in their nested qualifiers before writing out current definition.
Aaron Ballman19a41762014-03-14 12:55:57 +00007471 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007472
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007473 Write_protocol_list_initializer(Context, Result,
7474 RefedProtocols,
7475 "_OBJC_CATEGORY_PROTOCOLS_$_",
7476 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007477
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007478 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007479 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007480 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007481 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007482 "_OBJC_$_PROP_LIST_",
7483 FullCategoryName);
7484
7485 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007486 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007487 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007488 InstanceMethods,
7489 ClassMethods,
7490 RefedProtocols,
7491 ClassProperties);
7492
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007493 // Determine if this category is also "non-lazy".
7494 if (ImplementationIsNonLazy(IDecl))
7495 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007496
7497}
7498
7499void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7500 int CatDefCount = CategoryImplementation.size();
7501 if (!CatDefCount)
7502 return;
7503 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7504 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7505 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7506 for (int i = 0; i < CatDefCount; i++) {
7507 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7508 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7509 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7510 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7511 Result += ClassDecl->getName();
7512 Result += "_$_";
7513 Result += CatDecl->getName();
7514 Result += ",\n";
7515 }
7516 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007517}
7518
7519// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7520/// class methods.
7521template<typename MethodIterator>
7522void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7523 MethodIterator MethodEnd,
7524 bool IsInstanceMethod,
7525 StringRef prefix,
7526 StringRef ClassName,
7527 std::string &Result) {
7528 if (MethodBegin == MethodEnd) return;
7529
7530 if (!objc_impl_method) {
7531 /* struct _objc_method {
7532 SEL _cmd;
7533 char *method_types;
7534 void *_imp;
7535 }
7536 */
7537 Result += "\nstruct _objc_method {\n";
7538 Result += "\tSEL _cmd;\n";
7539 Result += "\tchar *method_types;\n";
7540 Result += "\tvoid *_imp;\n";
7541 Result += "};\n";
7542
7543 objc_impl_method = true;
7544 }
7545
7546 // Build _objc_method_list for class's methods if needed
7547
7548 /* struct {
7549 struct _objc_method_list *next_method;
7550 int method_count;
7551 struct _objc_method method_list[];
7552 }
7553 */
7554 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007555 Result += "\n";
7556 if (LangOpts.MicrosoftExt) {
7557 if (IsInstanceMethod)
7558 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7559 else
7560 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7561 }
7562 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007563 Result += "\tstruct _objc_method_list *next_method;\n";
7564 Result += "\tint method_count;\n";
7565 Result += "\tstruct _objc_method method_list[";
7566 Result += utostr(NumMethods);
7567 Result += "];\n} _OBJC_";
7568 Result += prefix;
7569 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7570 Result += "_METHODS_";
7571 Result += ClassName;
7572 Result += " __attribute__ ((used, section (\"__OBJC, __";
7573 Result += IsInstanceMethod ? "inst" : "cls";
7574 Result += "_meth\")))= ";
7575 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7576
7577 Result += "\t,{{(SEL)\"";
7578 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7579 std::string MethodTypeString;
7580 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7581 Result += "\", \"";
7582 Result += MethodTypeString;
7583 Result += "\", (void *)";
7584 Result += MethodInternalNames[*MethodBegin];
7585 Result += "}\n";
7586 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7587 Result += "\t ,{(SEL)\"";
7588 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7589 std::string MethodTypeString;
7590 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7591 Result += "\", \"";
7592 Result += MethodTypeString;
7593 Result += "\", (void *)";
7594 Result += MethodInternalNames[*MethodBegin];
7595 Result += "}\n";
7596 }
7597 Result += "\t }\n};\n";
7598}
7599
7600Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7601 SourceRange OldRange = IV->getSourceRange();
7602 Expr *BaseExpr = IV->getBase();
7603
7604 // Rewrite the base, but without actually doing replaces.
7605 {
7606 DisableReplaceStmtScope S(*this);
7607 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7608 IV->setBase(BaseExpr);
7609 }
7610
7611 ObjCIvarDecl *D = IV->getDecl();
7612
7613 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007614
Fariborz Jahanian11671902012-02-07 17:11:38 +00007615 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7616 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007617 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007618 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7619 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00007620 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007621 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7622 clsDeclared);
7623 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7624
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007625 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007626 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007627 if (D->isBitField())
7628 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7629 else
7630 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007631
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007632 ReferencedIvars[clsDeclared].insert(D);
7633
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007634 // cast offset to "char *".
7635 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7636 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007637 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007638 BaseExpr);
7639 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7640 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Craig Topper8ae12032014-05-07 06:21:57 +00007641 Context->UnsignedLongTy, nullptr,
7642 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007643 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7644 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007645 SourceLocation());
7646 BinaryOperator *addExpr =
7647 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7648 Context->getPointerType(Context->CharTy),
Lang Hames5de91cc2012-10-02 04:45:10 +00007649 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007650 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007651 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7652 SourceLocation(),
7653 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007654 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007655 if (D->isBitField())
7656 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007657
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007658 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007659 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007660 RD = RD->getDefinition();
7661 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007662 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007663 ObjCContainerDecl *CDecl =
7664 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7665 // ivar in class extensions requires special treatment.
7666 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7667 CDecl = CatDecl->getClassInterface();
7668 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007669 RecName += "_IMPL";
7670 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7671 SourceLocation(), SourceLocation(),
7672 &Context->Idents.get(RecName.c_str()));
7673 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7674 unsigned UnsignedIntSize =
7675 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7676 Expr *Zero = IntegerLiteral::Create(*Context,
7677 llvm::APInt(UnsignedIntSize, 0),
7678 Context->UnsignedIntTy, SourceLocation());
7679 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7680 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7681 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +00007682 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007683 SourceLocation(),
7684 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007685 IvarT, nullptr,
7686 /*BitWidth=*/nullptr,
7687 /*Mutable=*/true, ICIS_NoInit);
7688 MemberExpr *ME = new (Context)
7689 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
7690 FD->getType(), VK_LValue, OK_Ordinary);
7691 IvarT = Context->getDecltypeType(ME, ME->getType());
7692 }
7693 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007694 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007695 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007696
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007697 castExpr = NoTypeInfoCStyleCastExpr(Context,
7698 castT,
7699 CK_BitCast,
7700 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007701
7702
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007703 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007704 VK_LValue, OK_Ordinary,
7705 SourceLocation());
7706 PE = new (Context) ParenExpr(OldRange.getBegin(),
7707 OldRange.getEnd(),
7708 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007709
7710 if (D->isBitField()) {
Craig Topper8ae12032014-05-07 06:21:57 +00007711 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007712 SourceLocation(),
7713 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007714 D->getType(), nullptr,
7715 /*BitWidth=*/D->getBitWidth(),
7716 /*Mutable=*/true, ICIS_NoInit);
7717 MemberExpr *ME = new (Context)
7718 MemberExpr(PE, /*isArrow*/ false, SourceLocation(), FD,
7719 SourceLocation(), FD->getType(), VK_LValue, OK_Ordinary);
7720 Replacement = ME;
7721
7722 }
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007723 else
7724 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007725 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007726
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007727 ReplaceStmtWithRange(IV, Replacement, OldRange);
7728 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007729}
Alp Toker0621cb22014-07-16 16:48:33 +00007730
7731#endif