blob: e0320ba3a23de0f6f3180ff781f8fc59e3623d5d [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"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000030#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/Support/raw_ostream.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000032
33using namespace clang;
34using llvm::utostr;
35
36namespace {
37 class RewriteModernObjC : public ASTConsumer {
38 protected:
39
40 enum {
41 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
42 block, ... */
43 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
44 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
45 __block variable */
46 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
47 helpers */
48 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
49 support routines */
50 BLOCK_BYREF_CURRENT_MAX = 256
51 };
52
53 enum {
54 BLOCK_NEEDS_FREE = (1 << 24),
55 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
56 BLOCK_HAS_CXX_OBJ = (1 << 26),
57 BLOCK_IS_GC = (1 << 27),
58 BLOCK_IS_GLOBAL = (1 << 28),
59 BLOCK_HAS_DESCRIPTOR = (1 << 29)
60 };
Fariborz Jahanian11671902012-02-07 17:11:38 +000061
62 Rewriter Rewrite;
63 DiagnosticsEngine &Diags;
64 const LangOptions &LangOpts;
65 ASTContext *Context;
66 SourceManager *SM;
67 TranslationUnitDecl *TUDecl;
68 FileID MainFileID;
69 const char *MainFileStart, *MainFileEnd;
70 Stmt *CurrentBody;
71 ParentMap *PropParentMap; // created lazily.
72 std::string InFileName;
73 raw_ostream* OutFile;
74 std::string Preamble;
75
76 TypeDecl *ProtocolTypeDecl;
77 VarDecl *GlobalVarDecl;
Fariborz Jahaniane0050702012-03-23 00:00:49 +000078 Expr *GlobalConstructionExp;
Fariborz Jahanian11671902012-02-07 17:11:38 +000079 unsigned RewriteFailedDiag;
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +000080 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian11671902012-02-07 17:11:38 +000081 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
85
86 // ObjC foreach break/continue generation support.
87 int BcLabelCount;
88
89 unsigned TryFinallyContainsReturnDiag;
90 // Needed for super.
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
94
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000105 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000106 FunctionDecl *CurFunctionDef;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000107
108 /* Misc. containers needed for meta-data rewrite. */
109 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
110 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
112 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000114 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000115 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000116 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
117 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
118
119 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000120 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000121
Fariborz Jahanian11671902012-02-07 17:11:38 +0000122 SmallVector<Stmt *, 32> Stmts;
123 SmallVector<int, 8> ObjCBcLabelNo;
124 // Remember all the @protocol(<expr>) expressions.
125 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
126
127 llvm::DenseSet<uint64_t> CopyDestroyCache;
128
129 // Block expressions.
130 SmallVector<BlockExpr *, 32> Blocks;
131 SmallVector<int, 32> InnerDeclRefsCount;
John McCall113bee02012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000133
John McCall113bee02012-03-10 09:33:50 +0000134 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000135
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000136
Fariborz Jahanian11671902012-02-07 17:11:38 +0000137 // Block related declarations.
138 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
139 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
140 SmallVector<ValueDecl *, 8> BlockByRefDecls;
141 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
142 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
143 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
144 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
145
146 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000147 llvm::DenseMap<ObjCInterfaceDecl *,
148 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
149
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000150 // ivar bitfield grouping containers
151 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
152 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
153 // This container maps an <class, group number for ivar> tuple to the type
154 // of the struct where the bitfield belongs.
155 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000156 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000157
Fariborz Jahanian11671902012-02-07 17:11:38 +0000158 // This maps an original source AST to it's rewritten form. This allows
159 // us to avoid rewriting the same node twice (which is very uncommon).
160 // This is needed to support some of the exotic property rewriting.
161 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
162
163 // Needed for header files being rewritten
164 bool IsHeader;
165 bool SilenceRewriteMacroWarning;
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000166 bool GenerateLineInfo;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000167 bool objc_impl_method;
168
169 bool DisableReplaceStmt;
170 class DisableReplaceStmtScope {
171 RewriteModernObjC &R;
172 bool SavedValue;
173
174 public:
175 DisableReplaceStmtScope(RewriteModernObjC &R)
176 : R(R), SavedValue(R.DisableReplaceStmt) {
177 R.DisableReplaceStmt = true;
178 }
179 ~DisableReplaceStmtScope() {
180 R.DisableReplaceStmt = SavedValue;
181 }
182 };
183 void InitializeCommon(ASTContext &context);
184
185 public:
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +0000186 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000187 // Top Level Driver code.
188 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
189 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
190 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
191 if (!Class->isThisDeclarationADefinition()) {
192 RewriteForwardClassDecl(D);
193 break;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000194 } else {
195 // Keep track of all interface declarations seen.
Fariborz Jahanian0ed6cb72012-02-24 21:42:38 +0000196 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000197 break;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000198 }
199 }
200
201 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
202 if (!Proto->isThisDeclarationADefinition()) {
203 RewriteForwardProtocolDecl(D);
204 break;
205 }
206 }
207
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000208 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
209 // Under modern abi, we cannot translate body of the function
210 // yet until all class extensions and its implementation is seen.
211 // This is because they may introduce new bitfields which must go
212 // into their grouping struct.
213 if (FDecl->isThisDeclarationADefinition() &&
214 // Not c functions defined inside an objc container.
215 !FDecl->isTopLevelDeclInObjCContainer()) {
216 FunctionDefinitionsSeen.push_back(FDecl);
217 break;
218 }
219 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000220 HandleTopLevelSingleDecl(*I);
221 }
222 return true;
223 }
Fariborz Jahaniand2940622013-10-07 19:54:22 +0000224
225 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
226 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
227 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
228 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
229 RewriteBlockPointerDecl(TD);
230 else if (TD->getUnderlyingType()->isFunctionPointerType())
231 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
232 else
233 RewriteObjCQualifiedInterfaceTypes(TD);
234 }
235 }
236 return;
237 }
238
Fariborz Jahanian11671902012-02-07 17:11:38 +0000239 void HandleTopLevelSingleDecl(Decl *D);
240 void HandleDeclInMainFile(Decl *D);
241 RewriteModernObjC(std::string inFile, raw_ostream *OS,
242 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000243 bool silenceMacroWarn, bool LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000244
245 ~RewriteModernObjC() {}
246
247 virtual void HandleTranslationUnit(ASTContext &C);
248
249 void ReplaceStmt(Stmt *Old, Stmt *New) {
250 Stmt *ReplacingStmt = ReplacedNodes[Old];
251
252 if (ReplacingStmt)
253 return; // We can't rewrite the same node twice.
254
255 if (DisableReplaceStmt)
256 return;
257
258 // If replacement succeeded or warning disabled return with no warning.
259 if (!Rewrite.ReplaceStmt(Old, New)) {
260 ReplacedNodes[Old] = New;
261 return;
262 }
263 if (SilenceRewriteMacroWarning)
264 return;
265 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
266 << Old->getSourceRange();
267 }
268
269 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
270 if (DisableReplaceStmt)
271 return;
272
273 // Measure the old text.
274 int Size = Rewrite.getRangeSize(SrcRange);
275 if (Size == -1) {
276 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
277 << Old->getSourceRange();
278 return;
279 }
280 // Get the new text.
281 std::string SStr;
282 llvm::raw_string_ostream S(SStr);
Richard Smith235341b2012-08-16 03:56:14 +0000283 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +0000284 const std::string &Str = S.str();
285
286 // If replacement succeeded or warning disabled return with no warning.
287 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
288 ReplacedNodes[Old] = New;
289 return;
290 }
291 if (SilenceRewriteMacroWarning)
292 return;
293 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
294 << Old->getSourceRange();
295 }
296
297 void InsertText(SourceLocation Loc, StringRef Str,
298 bool InsertAfter = true) {
299 // If insertion succeeded or warning disabled return with no warning.
300 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
301 SilenceRewriteMacroWarning)
302 return;
303
304 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
305 }
306
307 void ReplaceText(SourceLocation Start, unsigned OrigLength,
308 StringRef Str) {
309 // If removal succeeded or warning disabled return with no warning.
310 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
311 SilenceRewriteMacroWarning)
312 return;
313
314 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
315 }
316
317 // Syntactic Rewriting.
318 void RewriteRecordBody(RecordDecl *RD);
319 void RewriteInclude();
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +0000320 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +0000321 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
322 std::string &LineString);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000323 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000324 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000325 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
326 const std::string &typedefString);
327 void RewriteImplementations();
328 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
329 ObjCImplementationDecl *IMD,
330 ObjCCategoryImplDecl *CID);
331 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
332 void RewriteImplementationDecl(Decl *Dcl);
333 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
334 ObjCMethodDecl *MDecl, std::string &ResultStr);
335 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
336 const FunctionType *&FPRetType);
337 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
338 ValueDecl *VD, bool def=false);
339 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
340 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
341 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000342 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000343 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
344 void RewriteProperty(ObjCPropertyDecl *prop);
345 void RewriteFunctionDecl(FunctionDecl *FD);
346 void RewriteBlockPointerType(std::string& Str, QualType Type);
347 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianca357d92012-04-19 00:50:01 +0000348 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000349 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
350 void RewriteTypeOfDecl(VarDecl *VD);
351 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000352
353 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000354
355 // Expression Rewriting.
356 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
357 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
358 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
359 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
360 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
361 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
362 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +0000363 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beard0caa3942012-04-19 00:25:12 +0000364 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +0000365 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000366 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000367 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000368 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +0000369 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000370 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
371 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
372 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
373 SourceLocation OrigEnd);
374 Stmt *RewriteBreakStmt(BreakStmt *S);
375 Stmt *RewriteContinueStmt(ContinueStmt *S);
376 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +0000377 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000378 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000379
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000380 // Computes ivar bitfield group no.
381 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
382 // Names field decl. for ivar bitfield group.
383 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
384 // Names struct type for ivar bitfield group.
385 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
386 // Names symbol for ivar bitfield group field offset.
387 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
388 // Given an ivar bitfield, it builds (or finds) its group record type.
389 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
390 QualType SynthesizeBitfieldGroupStructType(
391 ObjCIvarDecl *IV,
392 SmallVectorImpl<ObjCIvarDecl *> &IVars);
393
Fariborz Jahanian11671902012-02-07 17:11:38 +0000394 // Block rewriting.
395 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
396
397 // Block specific rewrite rules.
398 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian847713a2012-04-24 19:38:45 +0000399 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCall113bee02012-03-10 09:33:50 +0000400 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000401 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
402 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
403
404 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
405 std::string &Result);
406
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000407 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanian144b7222012-05-01 17:46:45 +0000408 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000409 bool &IsNamedDefinition);
410 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
411 std::string &Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000412
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +0000413 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
414
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000415 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
416 std::string &Result);
417
Fariborz Jahanian11671902012-02-07 17:11:38 +0000418 virtual void Initialize(ASTContext &context);
419
Benjamin Kramer474261a2012-06-02 10:20:41 +0000420 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian11671902012-02-07 17:11:38 +0000421 // rewriting routines on the new ASTs.
422 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
423 Expr **args, unsigned nargs,
424 SourceLocation StartLoc=SourceLocation(),
425 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000426
427 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000428 QualType returnType,
429 SmallVectorImpl<QualType> &ArgTypes,
430 SmallVectorImpl<Expr*> &MsgExprs,
431 ObjCMethodDecl *Method);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000432
433 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
434 SourceLocation StartLoc=SourceLocation(),
435 SourceLocation EndLoc=SourceLocation());
436
437 void SynthCountByEnumWithState(std::string &buf);
438 void SynthMsgSendFunctionDecl();
439 void SynthMsgSendSuperFunctionDecl();
440 void SynthMsgSendStretFunctionDecl();
441 void SynthMsgSendFpretFunctionDecl();
442 void SynthMsgSendSuperStretFunctionDecl();
443 void SynthGetClassFunctionDecl();
444 void SynthGetMetaClassFunctionDecl();
445 void SynthGetSuperClassFunctionDecl();
446 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000447 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000448
449 // Rewriting metadata
450 template<typename MethodIterator>
451 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
452 MethodIterator MethodEnd,
453 bool IsInstanceMethod,
454 StringRef prefix,
455 StringRef ClassName,
456 std::string &Result);
Fariborz Jahaniane18961b2012-02-08 19:53:58 +0000457 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
458 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000459 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian11671902012-02-07 17:11:38 +0000460 const ObjCList<ObjCProtocolDecl> &Prots,
461 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000462 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000463 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000464 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +0000465
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000466 void RewriteMetaDataIntoBuffer(std::string &Result);
467 void WriteImageInfo(std::string &Result);
468 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000469 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000470 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000471
472 // Rewriting ivar
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000473 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000474 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000475 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000476
477
478 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
479 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
480 StringRef funcName, std::string Tag);
481 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
482 StringRef funcName, std::string Tag);
483 std::string SynthesizeBlockImpl(BlockExpr *CE,
484 std::string Tag, std::string Desc);
485 std::string SynthesizeBlockDescriptor(std::string DescTag,
486 std::string ImplTag,
487 int i, StringRef funcName,
488 unsigned hasCopy);
489 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
490 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
491 StringRef FunName);
492 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
493 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000494 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000495
496 // Misc. helper routines.
497 QualType getProtocolType();
498 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000499 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
500 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
501 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
502
503 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
504 void CollectBlockDeclRefInfo(BlockExpr *Exp);
505 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000506 void GetInnerBlockDeclRefExprs(Stmt *S,
507 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000508 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
509
510 // We avoid calling Type::isBlockPointerType(), since it operates on the
511 // canonical type. We only care if the top-level type is a closure pointer.
512 bool isTopLevelBlockPointerType(QualType T) {
513 return isa<BlockPointerType>(T);
514 }
515
516 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
517 /// to a function pointer type and upon success, returns true; false
518 /// otherwise.
519 bool convertBlockPointerToFunctionPointer(QualType &T) {
520 if (isTopLevelBlockPointerType(T)) {
521 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
522 T = Context->getPointerType(BPT->getPointeeType());
523 return true;
524 }
525 return false;
526 }
527
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +0000528 bool convertObjCTypeToCStyleType(QualType &T);
529
Fariborz Jahanian11671902012-02-07 17:11:38 +0000530 bool needToScanForQualifiers(QualType T);
531 QualType getSuperStructType();
532 QualType getConstantStringStructType();
533 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
534 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
535
536 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000537 if (T->isObjCQualifiedIdType()) {
538 bool isConst = T.isConstQualified();
539 T = isConst ? Context->getObjCIdType().withConst()
540 : Context->getObjCIdType();
541 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000542 else if (T->isObjCQualifiedClassType())
543 T = Context->getObjCClassType();
544 else if (T->isObjCObjectPointerType() &&
545 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
546 if (const ObjCObjectPointerType * OBJPT =
547 T->getAsObjCInterfacePointerType()) {
548 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
549 T = QualType(IFaceT, 0);
550 T = Context->getPointerType(T);
551 }
552 }
553 }
554
555 // FIXME: This predicate seems like it would be useful to add to ASTContext.
556 bool isObjCType(QualType T) {
557 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
558 return false;
559
560 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
561
562 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
563 OCT == Context->getCanonicalType(Context->getObjCClassType()))
564 return true;
565
566 if (const PointerType *PT = OCT->getAs<PointerType>()) {
567 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
568 PT->getPointeeType()->isObjCQualifiedIdType())
569 return true;
570 }
571 return false;
572 }
573 bool PointerTypeTakesAnyBlockArguments(QualType QT);
574 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
575 void GetExtentOfArgList(const char *Name, const char *&LParen,
576 const char *&RParen);
577
578 void QuoteDoublequotes(std::string &From, std::string &To) {
579 for (unsigned i = 0; i < From.length(); i++) {
580 if (From[i] == '"')
581 To += "\\\"";
582 else
583 To += From[i];
584 }
585 }
586
587 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000588 ArrayRef<QualType> args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000589 bool variadic = false) {
590 if (result == Context->getObjCInstanceType())
591 result = Context->getObjCIdType();
592 FunctionProtoType::ExtProtoInfo fpi;
593 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000594 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000595 }
596
597 // Helper function: create a CStyleCastExpr with trivial type source info.
598 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
599 CastKind Kind, Expr *E) {
600 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
601 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
602 SourceLocation(), SourceLocation());
603 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000604
605 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
606 IdentifierInfo* II = &Context->Idents.get("load");
607 Selector LoadSel = Context->Selectors.getSelector(0, &II);
608 return OD->getClassMethod(LoadSel) != 0;
609 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000610
611 StringLiteral *getStringLiteral(StringRef Str) {
612 QualType StrType = Context->getConstantArrayType(
613 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
614 0);
615 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
616 /*Pascal=*/false, StrType, SourceLocation());
617 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000618 };
619
620}
621
622void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
623 NamedDecl *D) {
624 if (const FunctionProtoType *fproto
625 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000626 for (FunctionProtoType::param_type_iterator I = fproto->param_type_begin(),
627 E = fproto->param_type_end();
628 I && (I != E); ++I)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000629 if (isTopLevelBlockPointerType(*I)) {
630 // All the args are checked/rewritten. Don't call twice!
631 RewriteBlockPointerDecl(D);
632 break;
633 }
634 }
635}
636
637void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
638 const PointerType *PT = funcType->getAs<PointerType>();
639 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
640 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
641}
642
643static bool IsHeaderFile(const std::string &Filename) {
644 std::string::size_type DotPos = Filename.rfind('.');
645
646 if (DotPos == std::string::npos) {
647 // no file extension
648 return false;
649 }
650
651 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
652 // C header: .h
653 // C++ header: .hh or .H;
654 return Ext == "h" || Ext == "hh" || Ext == "H";
655}
656
657RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
658 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000659 bool silenceMacroWarn,
660 bool LineInfo)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000661 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000662 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000663 IsHeader = IsHeaderFile(inFile);
664 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
665 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +0000666 // FIXME. This should be an error. But if block is not called, it is OK. And it
667 // may break including some headers.
668 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
669 "rewriting block literal declared in global scope is not implemented");
670
Fariborz Jahanian11671902012-02-07 17:11:38 +0000671 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
672 DiagnosticsEngine::Warning,
673 "rewriter doesn't support user-specified control flow semantics "
674 "for @try/@finally (code may not execute properly)");
675}
676
677ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
678 raw_ostream* OS,
679 DiagnosticsEngine &Diags,
680 const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000681 bool SilenceRewriteMacroWarning,
682 bool LineInfo) {
683 return new RewriteModernObjC(InFile, OS, Diags, LOpts,
684 SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000685}
686
687void RewriteModernObjC::InitializeCommon(ASTContext &context) {
688 Context = &context;
689 SM = &Context->getSourceManager();
690 TUDecl = Context->getTranslationUnitDecl();
691 MsgSendFunctionDecl = 0;
692 MsgSendSuperFunctionDecl = 0;
693 MsgSendStretFunctionDecl = 0;
694 MsgSendSuperStretFunctionDecl = 0;
695 MsgSendFpretFunctionDecl = 0;
696 GetClassFunctionDecl = 0;
697 GetMetaClassFunctionDecl = 0;
698 GetSuperClassFunctionDecl = 0;
699 SelGetUidFunctionDecl = 0;
700 CFStringFunctionDecl = 0;
701 ConstantStringClassReference = 0;
702 NSStringRecord = 0;
703 CurMethodDef = 0;
704 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000705 GlobalVarDecl = 0;
Fariborz Jahaniane0050702012-03-23 00:00:49 +0000706 GlobalConstructionExp = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000707 SuperStructDecl = 0;
708 ProtocolTypeDecl = 0;
709 ConstantStringDecl = 0;
710 BcLabelCount = 0;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000711 SuperConstructorFunctionDecl = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000712 NumObjCStringLiterals = 0;
713 PropParentMap = 0;
714 CurrentBody = 0;
715 DisableReplaceStmt = false;
716 objc_impl_method = false;
717
718 // Get the ID and start/end of the main file.
719 MainFileID = SM->getMainFileID();
720 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
721 MainFileStart = MainBuf->getBufferStart();
722 MainFileEnd = MainBuf->getBufferEnd();
723
David Blaikiebbafb8a2012-03-11 07:00:24 +0000724 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000725}
726
727//===----------------------------------------------------------------------===//
728// Top Level Driver Code
729//===----------------------------------------------------------------------===//
730
731void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
732 if (Diags.hasErrorOccurred())
733 return;
734
735 // Two cases: either the decl could be in the main file, or it could be in a
736 // #included file. If the former, rewrite it now. If the later, check to see
737 // if we rewrote the #include/#import.
738 SourceLocation Loc = D->getLocation();
739 Loc = SM->getExpansionLoc(Loc);
740
741 // If this is for a builtin, ignore it.
742 if (Loc.isInvalid()) return;
743
744 // Look for built-in declarations that we need to refer during the rewrite.
745 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
746 RewriteFunctionDecl(FD);
747 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
748 // declared in <Foundation/NSString.h>
749 if (FVD->getName() == "_NSConstantStringClassReference") {
750 ConstantStringClassReference = FVD;
751 return;
752 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000753 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
754 RewriteCategoryDecl(CD);
755 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
756 if (PD->isThisDeclarationADefinition())
757 RewriteProtocolDecl(PD);
758 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanianf264d5d2012-04-04 17:16:15 +0000759 // FIXME. This will not work in all situations and leaving it out
760 // is harmless.
761 // RewriteLinkageSpec(LSD);
762
Fariborz Jahanian11671902012-02-07 17:11:38 +0000763 // Recurse into linkage specifications
764 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
765 DIEnd = LSD->decls_end();
766 DI != DIEnd; ) {
767 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
768 if (!IFace->isThisDeclarationADefinition()) {
769 SmallVector<Decl *, 8> DG;
770 SourceLocation StartLoc = IFace->getLocStart();
771 do {
772 if (isa<ObjCInterfaceDecl>(*DI) &&
773 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
774 StartLoc == (*DI)->getLocStart())
775 DG.push_back(*DI);
776 else
777 break;
778
779 ++DI;
780 } while (DI != DIEnd);
781 RewriteForwardClassDecl(DG);
782 continue;
783 }
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000784 else {
785 // Keep track of all interface declarations seen.
786 ObjCInterfacesSeen.push_back(IFace);
787 ++DI;
788 continue;
789 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000790 }
791
792 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
793 if (!Proto->isThisDeclarationADefinition()) {
794 SmallVector<Decl *, 8> DG;
795 SourceLocation StartLoc = Proto->getLocStart();
796 do {
797 if (isa<ObjCProtocolDecl>(*DI) &&
798 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
799 StartLoc == (*DI)->getLocStart())
800 DG.push_back(*DI);
801 else
802 break;
803
804 ++DI;
805 } while (DI != DIEnd);
806 RewriteForwardProtocolDecl(DG);
807 continue;
808 }
809 }
810
811 HandleTopLevelSingleDecl(*DI);
812 ++DI;
813 }
814 }
815 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000816 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian11671902012-02-07 17:11:38 +0000817 return HandleDeclInMainFile(D);
818}
819
820//===----------------------------------------------------------------------===//
821// Syntactic (non-AST) Rewriting Code
822//===----------------------------------------------------------------------===//
823
824void RewriteModernObjC::RewriteInclude() {
825 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
826 StringRef MainBuf = SM->getBufferData(MainFileID);
827 const char *MainBufStart = MainBuf.begin();
828 const char *MainBufEnd = MainBuf.end();
829 size_t ImportLen = strlen("import");
830
831 // Loop over the whole file, looking for includes.
832 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
833 if (*BufPtr == '#') {
834 if (++BufPtr == MainBufEnd)
835 return;
836 while (*BufPtr == ' ' || *BufPtr == '\t')
837 if (++BufPtr == MainBufEnd)
838 return;
839 if (!strncmp(BufPtr, "import", ImportLen)) {
840 // replace import with include
841 SourceLocation ImportLoc =
842 LocStart.getLocWithOffset(BufPtr-MainBufStart);
843 ReplaceText(ImportLoc, ImportLen, "include");
844 BufPtr += ImportLen;
845 }
846 }
847 }
848}
849
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000850static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
851 ObjCIvarDecl *IvarDecl, std::string &Result) {
852 Result += "OBJC_IVAR_$_";
853 Result += IDecl->getName();
854 Result += "$";
855 Result += IvarDecl->getName();
856}
857
858std::string
859RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
860 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
861
862 // Build name of symbol holding ivar offset.
863 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000864 if (D->isBitField())
865 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
866 else
867 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000868
869
870 std::string S = "(*(";
871 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000872 if (D->isBitField())
873 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000874
875 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
876 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
877 RD = RD->getDefinition();
878 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
879 // decltype(((Foo_IMPL*)0)->bar) *
880 ObjCContainerDecl *CDecl =
881 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
882 // ivar in class extensions requires special treatment.
883 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
884 CDecl = CatDecl->getClassInterface();
885 std::string RecName = CDecl->getName();
886 RecName += "_IMPL";
887 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
888 SourceLocation(), SourceLocation(),
889 &Context->Idents.get(RecName.c_str()));
890 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
891 unsigned UnsignedIntSize =
892 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
893 Expr *Zero = IntegerLiteral::Create(*Context,
894 llvm::APInt(UnsignedIntSize, 0),
895 Context->UnsignedIntTy, SourceLocation());
896 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
897 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
898 Zero);
899 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
900 SourceLocation(),
901 &Context->Idents.get(D->getNameAsString()),
902 IvarT, 0,
903 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +0000904 ICIS_NoInit);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000905 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
906 FD->getType(), VK_LValue,
907 OK_Ordinary);
908 IvarT = Context->getDecltypeType(ME, ME->getType());
909 }
910 }
911 convertObjCTypeToCStyleType(IvarT);
912 QualType castT = Context->getPointerType(IvarT);
913 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
914 S += TypeString;
915 S += ")";
916
917 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
918 S += "((char *)self + ";
919 S += IvarOffsetName;
920 S += "))";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000921 if (D->isBitField()) {
922 S += ".";
923 S += D->getNameAsString();
924 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000925 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000926 return S;
927}
928
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000929/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
930/// been found in the class implementation. In this case, it must be synthesized.
931static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
932 ObjCPropertyDecl *PD,
933 bool getter) {
934 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
935 : !IMP->getInstanceMethod(PD->getSetterName());
936
937}
938
Fariborz Jahanian11671902012-02-07 17:11:38 +0000939void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
940 ObjCImplementationDecl *IMD,
941 ObjCCategoryImplDecl *CID) {
942 static bool objcGetPropertyDefined = false;
943 static bool objcSetPropertyDefined = false;
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000944 SourceLocation startGetterSetterLoc;
945
946 if (PID->getLocStart().isValid()) {
947 SourceLocation startLoc = PID->getLocStart();
948 InsertText(startLoc, "// ");
949 const char *startBuf = SM->getCharacterData(startLoc);
950 assert((*startBuf == '@') && "bogus @synthesize location");
951 const char *semiBuf = strchr(startBuf, ';');
952 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
953 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
954 }
955 else
956 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000957
958 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
959 return; // FIXME: is this correct?
960
961 // Generate the 'getter' function.
962 ObjCPropertyDecl *PD = PID->getPropertyDecl();
963 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose755a2ff2013-03-15 21:41:35 +0000964 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000965
Bill Wendling44426052012-12-20 19:22:21 +0000966 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000967 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendling44426052012-12-20 19:22:21 +0000968 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
969 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +0000970 ObjCPropertyDecl::OBJC_PR_copy));
971 std::string Getr;
972 if (GenGetProperty && !objcGetPropertyDefined) {
973 objcGetPropertyDefined = true;
974 // FIXME. Is this attribute correct in all cases?
975 Getr = "\nextern \"C\" __declspec(dllimport) "
976 "id objc_getProperty(id, SEL, long, bool);\n";
977 }
978 RewriteObjCMethodDecl(OID->getContainingInterface(),
979 PD->getGetterMethodDecl(), Getr);
980 Getr += "{ ";
981 // Synthesize an explicit cast to gain access to the ivar.
982 // See objc-act.c:objc_synthesize_new_getter() for details.
983 if (GenGetProperty) {
984 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
985 Getr += "typedef ";
986 const FunctionType *FPRetType = 0;
Alp Toker314cc812014-01-25 16:55:45 +0000987 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000988 FPRetType);
989 Getr += " _TYPE";
990 if (FPRetType) {
991 Getr += ")"; // close the precedence "scope" for "*".
992
993 // Now, emit the argument types (if any).
994 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
995 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000996 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000997 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000998 std::string ParamStr =
999 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001000 Getr += ParamStr;
1001 }
1002 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001003 if (FT->getNumParams())
1004 Getr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001005 Getr += "...";
1006 }
1007 Getr += ")";
1008 } else
1009 Getr += "()";
1010 }
1011 Getr += ";\n";
1012 Getr += "return (_TYPE)";
1013 Getr += "objc_getProperty(self, _cmd, ";
1014 RewriteIvarOffsetComputation(OID, Getr);
1015 Getr += ", 1)";
1016 }
1017 else
1018 Getr += "return " + getIvarAccessString(OID);
1019 Getr += "; }";
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001020 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001021 }
1022
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001023 if (PD->isReadOnly() ||
1024 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001025 return;
1026
1027 // Generate the 'setter' function.
1028 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +00001029 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +00001030 ObjCPropertyDecl::OBJC_PR_copy);
1031 if (GenSetProperty && !objcSetPropertyDefined) {
1032 objcSetPropertyDefined = true;
1033 // FIXME. Is this attribute correct in all cases?
1034 Setr = "\nextern \"C\" __declspec(dllimport) "
1035 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1036 }
1037
1038 RewriteObjCMethodDecl(OID->getContainingInterface(),
1039 PD->getSetterMethodDecl(), Setr);
1040 Setr += "{ ";
1041 // Synthesize an explicit cast to initialize the ivar.
1042 // See objc-act.c:objc_synthesize_new_setter() for details.
1043 if (GenSetProperty) {
1044 Setr += "objc_setProperty (self, _cmd, ";
1045 RewriteIvarOffsetComputation(OID, Setr);
1046 Setr += ", (id)";
1047 Setr += PD->getName();
1048 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +00001049 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001050 Setr += "0, ";
1051 else
1052 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +00001053 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001054 Setr += "1)";
1055 else
1056 Setr += "0)";
1057 }
1058 else {
1059 Setr += getIvarAccessString(OID) + " = ";
1060 Setr += PD->getName();
1061 }
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001062 Setr += "; }\n";
1063 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001064}
1065
1066static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1067 std::string &typedefString) {
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001068 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001069 typedefString += ForwardDecl->getNameAsString();
1070 typedefString += "\n";
1071 typedefString += "#define _REWRITER_typedef_";
1072 typedefString += ForwardDecl->getNameAsString();
1073 typedefString += "\n";
1074 typedefString += "typedef struct objc_object ";
1075 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001076 // typedef struct { } _objc_exc_Classname;
1077 typedefString += ";\ntypedef struct {} _objc_exc_";
1078 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001079 typedefString += ";\n#endif\n";
1080}
1081
1082void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1083 const std::string &typedefString) {
1084 SourceLocation startLoc = ClassDecl->getLocStart();
1085 const char *startBuf = SM->getCharacterData(startLoc);
1086 const char *semiPtr = strchr(startBuf, ';');
1087 // Replace the @class with typedefs corresponding to the classes.
1088 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1089}
1090
1091void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1092 std::string typedefString;
1093 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001094 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1095 if (I == D.begin()) {
1096 // Translate to typedef's that forward reference structs with the same name
1097 // as the class. As a convenience, we include the original declaration
1098 // as a comment.
1099 typedefString += "// @class ";
1100 typedefString += ForwardDecl->getNameAsString();
1101 typedefString += ";";
1102 }
1103 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001104 }
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001105 else
1106 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001107 }
1108 DeclGroupRef::iterator I = D.begin();
1109 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1110}
1111
1112void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper5603df42013-07-05 19:34:19 +00001113 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001114 std::string typedefString;
1115 for (unsigned i = 0; i < D.size(); i++) {
1116 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1117 if (i == 0) {
1118 typedefString += "// @class ";
1119 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001120 typedefString += ";";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001121 }
1122 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1123 }
1124 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1125}
1126
1127void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1128 // When method is a synthesized one, such as a getter/setter there is
1129 // nothing to rewrite.
1130 if (Method->isImplicit())
1131 return;
1132 SourceLocation LocStart = Method->getLocStart();
1133 SourceLocation LocEnd = Method->getLocEnd();
1134
1135 if (SM->getExpansionLineNumber(LocEnd) >
1136 SM->getExpansionLineNumber(LocStart)) {
1137 InsertText(LocStart, "#if 0\n");
1138 ReplaceText(LocEnd, 1, ";\n#endif\n");
1139 } else {
1140 InsertText(LocStart, "// ");
1141 }
1142}
1143
1144void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1145 SourceLocation Loc = prop->getAtLoc();
1146
1147 ReplaceText(Loc, 0, "// ");
1148 // FIXME: handle properties that are declared across multiple lines.
1149}
1150
1151void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1152 SourceLocation LocStart = CatDecl->getLocStart();
1153
1154 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001155 if (CatDecl->getIvarRBraceLoc().isValid()) {
1156 ReplaceText(LocStart, 1, "/** ");
1157 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1158 }
1159 else {
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001160 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001161 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +00001162
Fariborz Jahanian11671902012-02-07 17:11:38 +00001163 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1164 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001165 RewriteProperty(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001166
1167 for (ObjCCategoryDecl::instmeth_iterator
1168 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1169 I != E; ++I)
1170 RewriteMethodDeclaration(*I);
1171 for (ObjCCategoryDecl::classmeth_iterator
1172 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1173 I != E; ++I)
1174 RewriteMethodDeclaration(*I);
1175
1176 // Lastly, comment out the @end.
1177 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001178 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001179}
1180
1181void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1182 SourceLocation LocStart = PDecl->getLocStart();
1183 assert(PDecl->isThisDeclarationADefinition());
1184
1185 // FIXME: handle protocol headers that are declared across multiple lines.
1186 ReplaceText(LocStart, 0, "// ");
1187
1188 for (ObjCProtocolDecl::instmeth_iterator
1189 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1190 I != E; ++I)
1191 RewriteMethodDeclaration(*I);
1192 for (ObjCProtocolDecl::classmeth_iterator
1193 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1194 I != E; ++I)
1195 RewriteMethodDeclaration(*I);
1196
1197 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1198 E = PDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001199 RewriteProperty(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001200
1201 // Lastly, comment out the @end.
1202 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001203 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001204
1205 // Must comment out @optional/@required
1206 const char *startBuf = SM->getCharacterData(LocStart);
1207 const char *endBuf = SM->getCharacterData(LocEnd);
1208 for (const char *p = startBuf; p < endBuf; p++) {
1209 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1210 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1211 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1212
1213 }
1214 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1215 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1216 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1217
1218 }
1219 }
1220}
1221
1222void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1223 SourceLocation LocStart = (*D.begin())->getLocStart();
1224 if (LocStart.isInvalid())
1225 llvm_unreachable("Invalid SourceLocation");
1226 // FIXME: handle forward protocol that are declared across multiple lines.
1227 ReplaceText(LocStart, 0, "// ");
1228}
1229
1230void
Craig Topper5603df42013-07-05 19:34:19 +00001231RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001232 SourceLocation LocStart = DG[0]->getLocStart();
1233 if (LocStart.isInvalid())
1234 llvm_unreachable("Invalid SourceLocation");
1235 // FIXME: handle forward protocol that are declared across multiple lines.
1236 ReplaceText(LocStart, 0, "// ");
1237}
1238
Fariborz Jahanian08ed8922012-04-03 17:35:38 +00001239void
1240RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1241 SourceLocation LocStart = LSD->getExternLoc();
1242 if (LocStart.isInvalid())
1243 llvm_unreachable("Invalid extern SourceLocation");
1244
1245 ReplaceText(LocStart, 0, "// ");
1246 if (!LSD->hasBraces())
1247 return;
1248 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1249 SourceLocation LocRBrace = LSD->getRBraceLoc();
1250 if (LocRBrace.isInvalid())
1251 llvm_unreachable("Invalid rbrace SourceLocation");
1252 ReplaceText(LocRBrace, 0, "// ");
1253}
1254
Fariborz Jahanian11671902012-02-07 17:11:38 +00001255void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1256 const FunctionType *&FPRetType) {
1257 if (T->isObjCQualifiedIdType())
1258 ResultStr += "id";
1259 else if (T->isFunctionPointerType() ||
1260 T->isBlockPointerType()) {
1261 // needs special handling, since pointer-to-functions have special
1262 // syntax (where a decaration models use).
1263 QualType retType = T;
1264 QualType PointeeTy;
1265 if (const PointerType* PT = retType->getAs<PointerType>())
1266 PointeeTy = PT->getPointeeType();
1267 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1268 PointeeTy = BPT->getPointeeType();
1269 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001270 ResultStr +=
1271 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001272 ResultStr += "(*";
1273 }
1274 } else
1275 ResultStr += T.getAsString(Context->getPrintingPolicy());
1276}
1277
1278void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1279 ObjCMethodDecl *OMD,
1280 std::string &ResultStr) {
1281 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1282 const FunctionType *FPRetType = 0;
1283 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001284 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001285 ResultStr += " ";
1286
1287 // Unique method name
1288 std::string NameStr;
1289
1290 if (OMD->isInstanceMethod())
1291 NameStr += "_I_";
1292 else
1293 NameStr += "_C_";
1294
1295 NameStr += IDecl->getNameAsString();
1296 NameStr += "_";
1297
1298 if (ObjCCategoryImplDecl *CID =
1299 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1300 NameStr += CID->getNameAsString();
1301 NameStr += "_";
1302 }
1303 // Append selector names, replacing ':' with '_'
1304 {
1305 std::string selString = OMD->getSelector().getAsString();
1306 int len = selString.size();
1307 for (int i = 0; i < len; i++)
1308 if (selString[i] == ':')
1309 selString[i] = '_';
1310 NameStr += selString;
1311 }
1312 // Remember this name for metadata emission
1313 MethodInternalNames[OMD] = NameStr;
1314 ResultStr += NameStr;
1315
1316 // Rewrite arguments
1317 ResultStr += "(";
1318
1319 // invisible arguments
1320 if (OMD->isInstanceMethod()) {
1321 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1322 selfTy = Context->getPointerType(selfTy);
1323 if (!LangOpts.MicrosoftExt) {
1324 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1325 ResultStr += "struct ";
1326 }
1327 // When rewriting for Microsoft, explicitly omit the structure name.
1328 ResultStr += IDecl->getNameAsString();
1329 ResultStr += " *";
1330 }
1331 else
1332 ResultStr += Context->getObjCClassType().getAsString(
1333 Context->getPrintingPolicy());
1334
1335 ResultStr += " self, ";
1336 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1337 ResultStr += " _cmd";
1338
1339 // Method arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00001340 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001341 ResultStr += ", ";
1342 if (PDecl->getType()->isObjCQualifiedIdType()) {
1343 ResultStr += "id ";
1344 ResultStr += PDecl->getNameAsString();
1345 } else {
1346 std::string Name = PDecl->getNameAsString();
1347 QualType QT = PDecl->getType();
1348 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001349 (void)convertBlockPointerToFunctionPointer(QT);
1350 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001351 ResultStr += Name;
1352 }
1353 }
1354 if (OMD->isVariadic())
1355 ResultStr += ", ...";
1356 ResultStr += ") ";
1357
1358 if (FPRetType) {
1359 ResultStr += ")"; // close the precedence "scope" for "*".
1360
1361 // Now, emit the argument types (if any).
1362 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1363 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001364 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001365 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001366 std::string ParamStr =
1367 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001368 ResultStr += ParamStr;
1369 }
1370 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001371 if (FT->getNumParams())
1372 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001373 ResultStr += "...";
1374 }
1375 ResultStr += ")";
1376 } else {
1377 ResultStr += "()";
1378 }
1379 }
1380}
1381void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1382 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1383 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1384
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001385 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001386 if (IMD->getIvarRBraceLoc().isValid()) {
1387 ReplaceText(IMD->getLocStart(), 1, "/** ");
1388 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001389 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001390 else {
1391 InsertText(IMD->getLocStart(), "// ");
1392 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001393 }
1394 else
1395 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001396
1397 for (ObjCCategoryImplDecl::instmeth_iterator
1398 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1399 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1400 I != E; ++I) {
1401 std::string ResultStr;
1402 ObjCMethodDecl *OMD = *I;
1403 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1404 SourceLocation LocStart = OMD->getLocStart();
1405 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1406
1407 const char *startBuf = SM->getCharacterData(LocStart);
1408 const char *endBuf = SM->getCharacterData(LocEnd);
1409 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1410 }
1411
1412 for (ObjCCategoryImplDecl::classmeth_iterator
1413 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1414 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1415 I != E; ++I) {
1416 std::string ResultStr;
1417 ObjCMethodDecl *OMD = *I;
1418 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1419 SourceLocation LocStart = OMD->getLocStart();
1420 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1421
1422 const char *startBuf = SM->getCharacterData(LocStart);
1423 const char *endBuf = SM->getCharacterData(LocEnd);
1424 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1425 }
1426 for (ObjCCategoryImplDecl::propimpl_iterator
1427 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1428 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1429 I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001430 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001431 }
1432
1433 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1434}
1435
1436void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001437 // Do not synthesize more than once.
1438 if (ObjCSynthesizedStructs.count(ClassDecl))
1439 return;
1440 // Make sure super class's are written before current class is written.
1441 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1442 while (SuperClass) {
1443 RewriteInterfaceDecl(SuperClass);
1444 SuperClass = SuperClass->getSuperClass();
1445 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001446 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001447 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001448 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001449 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001450 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1451
Fariborz Jahanianff513382012-02-15 22:01:47 +00001452 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001453 // Mark this typedef as having been written into its c++ equivalent.
1454 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanianff513382012-02-15 22:01:47 +00001455
1456 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00001457 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001458 RewriteProperty(*I);
Fariborz Jahanianff513382012-02-15 22:01:47 +00001459 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian11671902012-02-07 17:11:38 +00001460 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanianff513382012-02-15 22:01:47 +00001461 I != E; ++I)
1462 RewriteMethodDeclaration(*I);
1463 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian11671902012-02-07 17:11:38 +00001464 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanianff513382012-02-15 22:01:47 +00001465 I != E; ++I)
1466 RewriteMethodDeclaration(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001467
Fariborz Jahanianff513382012-02-15 22:01:47 +00001468 // Lastly, comment out the @end.
1469 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001470 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001471 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001472}
1473
1474Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1475 SourceRange OldRange = PseudoOp->getSourceRange();
1476
1477 // We just magically know some things about the structure of this
1478 // expression.
1479 ObjCMessageExpr *OldMsg =
1480 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1481 PseudoOp->getNumSemanticExprs() - 1));
1482
1483 // Because the rewriter doesn't allow us to rewrite rewritten code,
1484 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001485 Expr *Base;
1486 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001487 {
1488 DisableReplaceStmtScope S(*this);
1489
1490 // Rebuild the base expression if we have one.
1491 Base = 0;
1492 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1493 Base = OldMsg->getInstanceReceiver();
1494 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1495 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1496 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001497
1498 unsigned numArgs = OldMsg->getNumArgs();
1499 for (unsigned i = 0; i < numArgs; i++) {
1500 Expr *Arg = OldMsg->getArg(i);
1501 if (isa<OpaqueValueExpr>(Arg))
1502 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1503 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1504 Args.push_back(Arg);
1505 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001506 }
1507
1508 // TODO: avoid this copy.
1509 SmallVector<SourceLocation, 1> SelLocs;
1510 OldMsg->getSelectorLocs(SelLocs);
1511
1512 ObjCMessageExpr *NewMsg = 0;
1513 switch (OldMsg->getReceiverKind()) {
1514 case ObjCMessageExpr::Class:
1515 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1516 OldMsg->getValueKind(),
1517 OldMsg->getLeftLoc(),
1518 OldMsg->getClassReceiverTypeInfo(),
1519 OldMsg->getSelector(),
1520 SelLocs,
1521 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001522 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001523 OldMsg->getRightLoc(),
1524 OldMsg->isImplicit());
1525 break;
1526
1527 case ObjCMessageExpr::Instance:
1528 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1529 OldMsg->getValueKind(),
1530 OldMsg->getLeftLoc(),
1531 Base,
1532 OldMsg->getSelector(),
1533 SelLocs,
1534 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001535 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001536 OldMsg->getRightLoc(),
1537 OldMsg->isImplicit());
1538 break;
1539
1540 case ObjCMessageExpr::SuperClass:
1541 case ObjCMessageExpr::SuperInstance:
1542 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1543 OldMsg->getValueKind(),
1544 OldMsg->getLeftLoc(),
1545 OldMsg->getSuperLoc(),
1546 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1547 OldMsg->getSuperType(),
1548 OldMsg->getSelector(),
1549 SelLocs,
1550 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001551 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001552 OldMsg->getRightLoc(),
1553 OldMsg->isImplicit());
1554 break;
1555 }
1556
1557 Stmt *Replacement = SynthMessageExpr(NewMsg);
1558 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1559 return Replacement;
1560}
1561
1562Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1563 SourceRange OldRange = PseudoOp->getSourceRange();
1564
1565 // We just magically know some things about the structure of this
1566 // expression.
1567 ObjCMessageExpr *OldMsg =
1568 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1569
1570 // Because the rewriter doesn't allow us to rewrite rewritten code,
1571 // we need to suppress rewriting the sub-statements.
1572 Expr *Base = 0;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001573 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001574 {
1575 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001576 // Rebuild the base expression if we have one.
1577 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1578 Base = OldMsg->getInstanceReceiver();
1579 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1580 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1581 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001582 unsigned numArgs = OldMsg->getNumArgs();
1583 for (unsigned i = 0; i < numArgs; i++) {
1584 Expr *Arg = OldMsg->getArg(i);
1585 if (isa<OpaqueValueExpr>(Arg))
1586 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1587 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1588 Args.push_back(Arg);
1589 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001590 }
1591
1592 // Intentionally empty.
1593 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001594
1595 ObjCMessageExpr *NewMsg = 0;
1596 switch (OldMsg->getReceiverKind()) {
1597 case ObjCMessageExpr::Class:
1598 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1599 OldMsg->getValueKind(),
1600 OldMsg->getLeftLoc(),
1601 OldMsg->getClassReceiverTypeInfo(),
1602 OldMsg->getSelector(),
1603 SelLocs,
1604 OldMsg->getMethodDecl(),
1605 Args,
1606 OldMsg->getRightLoc(),
1607 OldMsg->isImplicit());
1608 break;
1609
1610 case ObjCMessageExpr::Instance:
1611 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1612 OldMsg->getValueKind(),
1613 OldMsg->getLeftLoc(),
1614 Base,
1615 OldMsg->getSelector(),
1616 SelLocs,
1617 OldMsg->getMethodDecl(),
1618 Args,
1619 OldMsg->getRightLoc(),
1620 OldMsg->isImplicit());
1621 break;
1622
1623 case ObjCMessageExpr::SuperClass:
1624 case ObjCMessageExpr::SuperInstance:
1625 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1626 OldMsg->getValueKind(),
1627 OldMsg->getLeftLoc(),
1628 OldMsg->getSuperLoc(),
1629 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1630 OldMsg->getSuperType(),
1631 OldMsg->getSelector(),
1632 SelLocs,
1633 OldMsg->getMethodDecl(),
1634 Args,
1635 OldMsg->getRightLoc(),
1636 OldMsg->isImplicit());
1637 break;
1638 }
1639
1640 Stmt *Replacement = SynthMessageExpr(NewMsg);
1641 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1642 return Replacement;
1643}
1644
1645/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001646/// ((NSUInteger (*)
1647/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001648/// (void *)objc_msgSend)((id)l_collection,
1649/// sel_registerName(
1650/// "countByEnumeratingWithState:objects:count:"),
1651/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001652/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001653///
1654void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001655 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1656 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001657 buf += "\n\t\t";
1658 buf += "((id)l_collection,\n\t\t";
1659 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1660 buf += "\n\t\t";
1661 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001662 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001663}
1664
1665/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1666/// statement to exit to its outer synthesized loop.
1667///
1668Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1669 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1670 return S;
1671 // replace break with goto __break_label
1672 std::string buf;
1673
1674 SourceLocation startLoc = S->getLocStart();
1675 buf = "goto __break_label_";
1676 buf += utostr(ObjCBcLabelNo.back());
1677 ReplaceText(startLoc, strlen("break"), buf);
1678
1679 return 0;
1680}
1681
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001682void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1683 SourceLocation Loc,
1684 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001685 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001686 LineString += "\n#line ";
1687 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1688 LineString += utostr(PLoc.getLine());
1689 LineString += " \"";
1690 LineString += Lexer::Stringify(PLoc.getFilename());
1691 LineString += "\"\n";
1692 }
1693}
1694
Fariborz Jahanian11671902012-02-07 17:11:38 +00001695/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1696/// statement to continue with its inner synthesized loop.
1697///
1698Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1699 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1700 return S;
1701 // replace continue with goto __continue_label
1702 std::string buf;
1703
1704 SourceLocation startLoc = S->getLocStart();
1705 buf = "goto __continue_label_";
1706 buf += utostr(ObjCBcLabelNo.back());
1707 ReplaceText(startLoc, strlen("continue"), buf);
1708
1709 return 0;
1710}
1711
1712/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1713/// It rewrites:
1714/// for ( type elem in collection) { stmts; }
1715
1716/// Into:
1717/// {
1718/// type elem;
1719/// struct __objcFastEnumerationState enumState = { 0 };
1720/// id __rw_items[16];
1721/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001722/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001723/// objects:__rw_items count:16];
1724/// if (limit) {
1725/// unsigned long startMutations = *enumState.mutationsPtr;
1726/// do {
1727/// unsigned long counter = 0;
1728/// do {
1729/// if (startMutations != *enumState.mutationsPtr)
1730/// objc_enumerationMutation(l_collection);
1731/// elem = (type)enumState.itemsPtr[counter++];
1732/// stmts;
1733/// __continue_label: ;
1734/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001735/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1736/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001737/// elem = nil;
1738/// __break_label: ;
1739/// }
1740/// else
1741/// elem = nil;
1742/// }
1743///
1744Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1745 SourceLocation OrigEnd) {
1746 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1747 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1748 "ObjCForCollectionStmt Statement stack mismatch");
1749 assert(!ObjCBcLabelNo.empty() &&
1750 "ObjCForCollectionStmt - Label No stack empty");
1751
1752 SourceLocation startLoc = S->getLocStart();
1753 const char *startBuf = SM->getCharacterData(startLoc);
1754 StringRef elementName;
1755 std::string elementTypeAsString;
1756 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001757 // line directive first.
1758 SourceLocation ForEachLoc = S->getForLoc();
1759 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1760 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001761 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1762 // type elem;
1763 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1764 QualType ElementType = cast<ValueDecl>(D)->getType();
1765 if (ElementType->isObjCQualifiedIdType() ||
1766 ElementType->isObjCQualifiedInterfaceType())
1767 // Simply use 'id' for all qualified types.
1768 elementTypeAsString = "id";
1769 else
1770 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1771 buf += elementTypeAsString;
1772 buf += " ";
1773 elementName = D->getName();
1774 buf += elementName;
1775 buf += ";\n\t";
1776 }
1777 else {
1778 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1779 elementName = DR->getDecl()->getName();
1780 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1781 if (VD->getType()->isObjCQualifiedIdType() ||
1782 VD->getType()->isObjCQualifiedInterfaceType())
1783 // Simply use 'id' for all qualified types.
1784 elementTypeAsString = "id";
1785 else
1786 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1787 }
1788
1789 // struct __objcFastEnumerationState enumState = { 0 };
1790 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1791 // id __rw_items[16];
1792 buf += "id __rw_items[16];\n\t";
1793 // id l_collection = (id)
1794 buf += "id l_collection = (id)";
1795 // Find start location of 'collection' the hard way!
1796 const char *startCollectionBuf = startBuf;
1797 startCollectionBuf += 3; // skip 'for'
1798 startCollectionBuf = strchr(startCollectionBuf, '(');
1799 startCollectionBuf++; // skip '('
1800 // find 'in' and skip it.
1801 while (*startCollectionBuf != ' ' ||
1802 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1803 (*(startCollectionBuf+3) != ' ' &&
1804 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1805 startCollectionBuf++;
1806 startCollectionBuf += 3;
1807
1808 // Replace: "for (type element in" with string constructed thus far.
1809 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1810 // Replace ')' in for '(' type elem in collection ')' with ';'
1811 SourceLocation rightParenLoc = S->getRParenLoc();
1812 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1813 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1814 buf = ";\n\t";
1815
1816 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1817 // objects:__rw_items count:16];
1818 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001819 // NSUInteger limit =
1820 // ((NSUInteger (*)
1821 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001822 // (void *)objc_msgSend)((id)l_collection,
1823 // sel_registerName(
1824 // "countByEnumeratingWithState:objects:count:"),
1825 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001826 // (id *)__rw_items, (NSUInteger)16);
1827 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001828 SynthCountByEnumWithState(buf);
1829 buf += ";\n\t";
1830 /// if (limit) {
1831 /// unsigned long startMutations = *enumState.mutationsPtr;
1832 /// do {
1833 /// unsigned long counter = 0;
1834 /// do {
1835 /// if (startMutations != *enumState.mutationsPtr)
1836 /// objc_enumerationMutation(l_collection);
1837 /// elem = (type)enumState.itemsPtr[counter++];
1838 buf += "if (limit) {\n\t";
1839 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1840 buf += "do {\n\t\t";
1841 buf += "unsigned long counter = 0;\n\t\t";
1842 buf += "do {\n\t\t\t";
1843 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1844 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1845 buf += elementName;
1846 buf += " = (";
1847 buf += elementTypeAsString;
1848 buf += ")enumState.itemsPtr[counter++];";
1849 // Replace ')' in for '(' type elem in collection ')' with all of these.
1850 ReplaceText(lparenLoc, 1, buf);
1851
1852 /// __continue_label: ;
1853 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001854 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1855 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001856 /// elem = nil;
1857 /// __break_label: ;
1858 /// }
1859 /// else
1860 /// elem = nil;
1861 /// }
1862 ///
1863 buf = ";\n\t";
1864 buf += "__continue_label_";
1865 buf += utostr(ObjCBcLabelNo.back());
1866 buf += ": ;";
1867 buf += "\n\t\t";
1868 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001869 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001870 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001871 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001872 buf += elementName;
1873 buf += " = ((";
1874 buf += elementTypeAsString;
1875 buf += ")0);\n\t";
1876 buf += "__break_label_";
1877 buf += utostr(ObjCBcLabelNo.back());
1878 buf += ": ;\n\t";
1879 buf += "}\n\t";
1880 buf += "else\n\t\t";
1881 buf += elementName;
1882 buf += " = ((";
1883 buf += elementTypeAsString;
1884 buf += ")0);\n\t";
1885 buf += "}\n";
1886
1887 // Insert all these *after* the statement body.
1888 // FIXME: If this should support Obj-C++, support CXXTryStmt
1889 if (isa<CompoundStmt>(S->getBody())) {
1890 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1891 InsertText(endBodyLoc, buf);
1892 } else {
1893 /* Need to treat single statements specially. For example:
1894 *
1895 * for (A *a in b) if (stuff()) break;
1896 * for (A *a in b) xxxyy;
1897 *
1898 * The following code simply scans ahead to the semi to find the actual end.
1899 */
1900 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1901 const char *semiBuf = strchr(stmtBuf, ';');
1902 assert(semiBuf && "Can't find ';'");
1903 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1904 InsertText(endBodyLoc, buf);
1905 }
1906 Stmts.pop_back();
1907 ObjCBcLabelNo.pop_back();
1908 return 0;
1909}
1910
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001911static void Write_RethrowObject(std::string &buf) {
1912 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1913 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1914 buf += "\tid rethrow;\n";
1915 buf += "\t} _fin_force_rethow(_rethrow);";
1916}
1917
Fariborz Jahanian11671902012-02-07 17:11:38 +00001918/// RewriteObjCSynchronizedStmt -
1919/// This routine rewrites @synchronized(expr) stmt;
1920/// into:
1921/// objc_sync_enter(expr);
1922/// @try stmt @finally { objc_sync_exit(expr); }
1923///
1924Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1925 // Get the start location and compute the semi location.
1926 SourceLocation startLoc = S->getLocStart();
1927 const char *startBuf = SM->getCharacterData(startLoc);
1928
1929 assert((*startBuf == '@') && "bogus @synchronized location");
1930
1931 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001932 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1933 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001934 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001935
Fariborz Jahanian11671902012-02-07 17:11:38 +00001936 const char *lparenBuf = startBuf;
1937 while (*lparenBuf != '(') lparenBuf++;
1938 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001939
1940 buf = "; objc_sync_enter(_sync_obj);\n";
1941 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1942 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1943 buf += "\n\tid sync_exit;";
1944 buf += "\n\t} _sync_exit(_sync_obj);\n";
1945
1946 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1947 // the sync expression is typically a message expression that's already
1948 // been rewritten! (which implies the SourceLocation's are invalid).
1949 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1950 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1951 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1952 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1953
1954 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1955 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1956 assert (*LBraceLocBuf == '{');
1957 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001958
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001959 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001960 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1961 "bogus @synchronized block");
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001962
1963 buf = "} catch (id e) {_rethrow = e;}\n";
1964 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001965 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001966 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001967
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001968 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001969
Fariborz Jahanian11671902012-02-07 17:11:38 +00001970 return 0;
1971}
1972
1973void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1974{
1975 // Perform a bottom up traversal of all children.
1976 for (Stmt::child_range CI = S->children(); CI; ++CI)
1977 if (*CI)
1978 WarnAboutReturnGotoStmts(*CI);
1979
1980 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1981 Diags.Report(Context->getFullLoc(S->getLocStart()),
1982 TryFinallyContainsReturnDiag);
1983 }
1984 return;
1985}
1986
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001987Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1988 SourceLocation startLoc = S->getAtLoc();
1989 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001990 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1991 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001992
1993 return 0;
1994}
1995
Fariborz Jahanian11671902012-02-07 17:11:38 +00001996Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001997 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001998 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001999 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002000 SourceLocation TryLocation = S->getAtTryLoc();
2001 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002002
2003 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002004 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002005 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002006 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002007 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002008 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002009 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002010 // Get the start location and compute the semi location.
2011 SourceLocation startLoc = S->getLocStart();
2012 const char *startBuf = SM->getCharacterData(startLoc);
2013
2014 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002015 if (finalStmt)
2016 ReplaceText(startLoc, 1, buf);
2017 else
2018 // @try -> try
2019 ReplaceText(startLoc, 1, "");
2020
Fariborz Jahanian11671902012-02-07 17:11:38 +00002021 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
2022 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002023 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002024
Fariborz Jahanian11671902012-02-07 17:11:38 +00002025 startLoc = Catch->getLocStart();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002026 bool AtRemoved = false;
2027 if (catchDecl) {
2028 QualType t = catchDecl->getType();
2029 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2030 // Should be a pointer to a class.
2031 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2032 if (IDecl) {
2033 std::string Result;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002034 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2035
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002036 startBuf = SM->getCharacterData(startLoc);
2037 assert((*startBuf == '@') && "bogus @catch location");
2038 SourceLocation rParenLoc = Catch->getRParenLoc();
2039 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2040
2041 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002042 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002043 Result += " *_"; Result += catchDecl->getNameAsString();
2044 Result += ")";
2045 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2046 // Foo *e = (Foo *)_e;
2047 Result.clear();
2048 Result = "{ ";
2049 Result += IDecl->getNameAsString();
2050 Result += " *"; Result += catchDecl->getNameAsString();
2051 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2052 Result += "_"; Result += catchDecl->getNameAsString();
2053
2054 Result += "; ";
2055 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2056 ReplaceText(lBraceLoc, 1, Result);
2057 AtRemoved = true;
2058 }
2059 }
2060 }
2061 if (!AtRemoved)
2062 // @catch -> catch
2063 ReplaceText(startLoc, 1, "");
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002064
Fariborz Jahanian11671902012-02-07 17:11:38 +00002065 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002066 if (finalStmt) {
2067 buf.clear();
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002068 SourceLocation FinallyLoc = finalStmt->getLocStart();
2069
2070 if (noCatch) {
2071 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2072 buf += "catch (id e) {_rethrow = e;}\n";
2073 }
2074 else {
2075 buf += "}\n";
2076 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2077 buf += "catch (id e) {_rethrow = e;}\n";
2078 }
2079
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002080 SourceLocation startFinalLoc = finalStmt->getLocStart();
2081 ReplaceText(startFinalLoc, 8, buf);
2082 Stmt *body = finalStmt->getFinallyBody();
2083 SourceLocation startFinalBodyLoc = body->getLocStart();
2084 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002085 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002086 ReplaceText(startFinalBodyLoc, 1, buf);
2087
2088 SourceLocation endFinalBodyLoc = body->getLocEnd();
2089 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002090 // Now check for any return/continue/go statements within the @try.
2091 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002092 }
2093
Fariborz Jahanian11671902012-02-07 17:11:38 +00002094 return 0;
2095}
2096
2097// This can't be done with ReplaceStmt(S, ThrowExpr), since
2098// the throw expression is typically a message expression that's already
2099// been rewritten! (which implies the SourceLocation's are invalid).
2100Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2101 // Get the start location and compute the semi location.
2102 SourceLocation startLoc = S->getLocStart();
2103 const char *startBuf = SM->getCharacterData(startLoc);
2104
2105 assert((*startBuf == '@') && "bogus @throw location");
2106
2107 std::string buf;
2108 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2109 if (S->getThrowExpr())
2110 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002111 else
2112 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002113
2114 // handle "@ throw" correctly.
2115 const char *wBuf = strchr(startBuf, 'w');
2116 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2117 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2118
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002119 SourceLocation endLoc = S->getLocEnd();
2120 const char *endBuf = SM->getCharacterData(endLoc);
2121 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002122 assert((*semiBuf == ';') && "@throw: can't find ';'");
2123 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002124 if (S->getThrowExpr())
2125 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002126 return 0;
2127}
2128
2129Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2130 // Create a new string expression.
Fariborz Jahanian11671902012-02-07 17:11:38 +00002131 std::string StrEncoding;
2132 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002133 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002134 ReplaceStmt(Exp, Replacement);
2135
2136 // Replace this subexpr in the parent.
2137 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2138 return Replacement;
2139}
2140
2141Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2142 if (!SelGetUidFunctionDecl)
2143 SynthSelGetUidFunctionDecl();
2144 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2145 // Create a call to sel_registerName("selName").
2146 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002147 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002148 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2149 &SelExprs[0], SelExprs.size());
2150 ReplaceStmt(Exp, SelExp);
2151 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2152 return SelExp;
2153}
2154
2155CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2156 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2157 SourceLocation EndLoc) {
2158 // Get the type, we will need to reference it in a couple spots.
2159 QualType msgSendType = FD->getType();
2160
2161 // Create a reference to the objc_msgSend() declaration.
2162 DeclRefExpr *DRE =
John McCall113bee02012-03-10 09:33:50 +00002163 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002164
2165 // Now, we cast the reference to a pointer to the objc_msgSend type.
2166 QualType pToFunc = Context->getPointerType(msgSendType);
2167 ImplicitCastExpr *ICE =
2168 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2169 DRE, 0, VK_RValue);
2170
2171 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2172
2173 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002174 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian11671902012-02-07 17:11:38 +00002175 FT->getCallResultType(*Context),
2176 VK_RValue, EndLoc);
2177 return Exp;
2178}
2179
2180static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2181 const char *&startRef, const char *&endRef) {
2182 while (startBuf < endBuf) {
2183 if (*startBuf == '<')
2184 startRef = startBuf; // mark the start.
2185 if (*startBuf == '>') {
2186 if (startRef && *startRef == '<') {
2187 endRef = startBuf; // mark the end.
2188 return true;
2189 }
2190 return false;
2191 }
2192 startBuf++;
2193 }
2194 return false;
2195}
2196
2197static void scanToNextArgument(const char *&argRef) {
2198 int angle = 0;
2199 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2200 if (*argRef == '<')
2201 angle++;
2202 else if (*argRef == '>')
2203 angle--;
2204 argRef++;
2205 }
2206 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2207}
2208
2209bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2210 if (T->isObjCQualifiedIdType())
2211 return true;
2212 if (const PointerType *PT = T->getAs<PointerType>()) {
2213 if (PT->getPointeeType()->isObjCQualifiedIdType())
2214 return true;
2215 }
2216 if (T->isObjCObjectPointerType()) {
2217 T = T->getPointeeType();
2218 return T->isObjCQualifiedInterfaceType();
2219 }
2220 if (T->isArrayType()) {
2221 QualType ElemTy = Context->getBaseElementType(T);
2222 return needToScanForQualifiers(ElemTy);
2223 }
2224 return false;
2225}
2226
2227void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2228 QualType Type = E->getType();
2229 if (needToScanForQualifiers(Type)) {
2230 SourceLocation Loc, EndLoc;
2231
2232 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2233 Loc = ECE->getLParenLoc();
2234 EndLoc = ECE->getRParenLoc();
2235 } else {
2236 Loc = E->getLocStart();
2237 EndLoc = E->getLocEnd();
2238 }
2239 // This will defend against trying to rewrite synthesized expressions.
2240 if (Loc.isInvalid() || EndLoc.isInvalid())
2241 return;
2242
2243 const char *startBuf = SM->getCharacterData(Loc);
2244 const char *endBuf = SM->getCharacterData(EndLoc);
2245 const char *startRef = 0, *endRef = 0;
2246 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2247 // Get the locations of the startRef, endRef.
2248 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2249 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2250 // Comment out the protocol references.
2251 InsertText(LessLoc, "/*");
2252 InsertText(GreaterLoc, "*/");
2253 }
2254 }
2255}
2256
2257void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2258 SourceLocation Loc;
2259 QualType Type;
2260 const FunctionProtoType *proto = 0;
2261 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2262 Loc = VD->getLocation();
2263 Type = VD->getType();
2264 }
2265 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2266 Loc = FD->getLocation();
2267 // Check for ObjC 'id' and class types that have been adorned with protocol
2268 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2269 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2270 assert(funcType && "missing function type");
2271 proto = dyn_cast<FunctionProtoType>(funcType);
2272 if (!proto)
2273 return;
Alp Toker314cc812014-01-25 16:55:45 +00002274 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002275 }
2276 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2277 Loc = FD->getLocation();
2278 Type = FD->getType();
2279 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002280 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2281 Loc = TD->getLocation();
2282 Type = TD->getUnderlyingType();
2283 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002284 else
2285 return;
2286
2287 if (needToScanForQualifiers(Type)) {
2288 // Since types are unique, we need to scan the buffer.
2289
2290 const char *endBuf = SM->getCharacterData(Loc);
2291 const char *startBuf = endBuf;
2292 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2293 startBuf--; // scan backward (from the decl location) for return type.
2294 const char *startRef = 0, *endRef = 0;
2295 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2296 // Get the locations of the startRef, endRef.
2297 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2298 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2299 // Comment out the protocol references.
2300 InsertText(LessLoc, "/*");
2301 InsertText(GreaterLoc, "*/");
2302 }
2303 }
2304 if (!proto)
2305 return; // most likely, was a variable
2306 // Now check arguments.
2307 const char *startBuf = SM->getCharacterData(Loc);
2308 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002309 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2310 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002311 // Since types are unique, we need to scan the buffer.
2312
2313 const char *endBuf = startBuf;
2314 // scan forward (from the decl location) for argument types.
2315 scanToNextArgument(endBuf);
2316 const char *startRef = 0, *endRef = 0;
2317 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2318 // Get the locations of the startRef, endRef.
2319 SourceLocation LessLoc =
2320 Loc.getLocWithOffset(startRef-startFuncBuf);
2321 SourceLocation GreaterLoc =
2322 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2323 // Comment out the protocol references.
2324 InsertText(LessLoc, "/*");
2325 InsertText(GreaterLoc, "*/");
2326 }
2327 startBuf = ++endBuf;
2328 }
2329 else {
2330 // If the function name is derived from a macro expansion, then the
2331 // argument buffer will not follow the name. Need to speak with Chris.
2332 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2333 startBuf++; // scan forward (from the decl location) for argument types.
2334 startBuf++;
2335 }
2336 }
2337}
2338
2339void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2340 QualType QT = ND->getType();
2341 const Type* TypePtr = QT->getAs<Type>();
2342 if (!isa<TypeOfExprType>(TypePtr))
2343 return;
2344 while (isa<TypeOfExprType>(TypePtr)) {
2345 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2346 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2347 TypePtr = QT->getAs<Type>();
2348 }
2349 // FIXME. This will not work for multiple declarators; as in:
2350 // __typeof__(a) b,c,d;
2351 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2352 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2353 const char *startBuf = SM->getCharacterData(DeclLoc);
2354 if (ND->getInit()) {
2355 std::string Name(ND->getNameAsString());
2356 TypeAsString += " " + Name + " = ";
2357 Expr *E = ND->getInit();
2358 SourceLocation startLoc;
2359 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2360 startLoc = ECE->getLParenLoc();
2361 else
2362 startLoc = E->getLocStart();
2363 startLoc = SM->getExpansionLoc(startLoc);
2364 const char *endBuf = SM->getCharacterData(startLoc);
2365 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2366 }
2367 else {
2368 SourceLocation X = ND->getLocEnd();
2369 X = SM->getExpansionLoc(X);
2370 const char *endBuf = SM->getCharacterData(X);
2371 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2372 }
2373}
2374
2375// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2376void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2377 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2378 SmallVector<QualType, 16> ArgTys;
2379 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2380 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002381 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002382 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002383 SourceLocation(),
2384 SourceLocation(),
2385 SelGetUidIdent, getFuncType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002386 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002387}
2388
2389void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2390 // declared in <objc/objc.h>
2391 if (FD->getIdentifier() &&
2392 FD->getName() == "sel_registerName") {
2393 SelGetUidFunctionDecl = FD;
2394 return;
2395 }
2396 RewriteObjCQualifiedInterfaceTypes(FD);
2397}
2398
2399void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2400 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2401 const char *argPtr = TypeString.c_str();
2402 if (!strchr(argPtr, '^')) {
2403 Str += TypeString;
2404 return;
2405 }
2406 while (*argPtr) {
2407 Str += (*argPtr == '^' ? '*' : *argPtr);
2408 argPtr++;
2409 }
2410}
2411
2412// FIXME. Consolidate this routine with RewriteBlockPointerType.
2413void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2414 ValueDecl *VD) {
2415 QualType Type = VD->getType();
2416 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2417 const char *argPtr = TypeString.c_str();
2418 int paren = 0;
2419 while (*argPtr) {
2420 switch (*argPtr) {
2421 case '(':
2422 Str += *argPtr;
2423 paren++;
2424 break;
2425 case ')':
2426 Str += *argPtr;
2427 paren--;
2428 break;
2429 case '^':
2430 Str += '*';
2431 if (paren == 1)
2432 Str += VD->getNameAsString();
2433 break;
2434 default:
2435 Str += *argPtr;
2436 break;
2437 }
2438 argPtr++;
2439 }
2440}
2441
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002442void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2443 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2444 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2445 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2446 if (!proto)
2447 return;
Alp Toker314cc812014-01-25 16:55:45 +00002448 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002449 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2450 FdStr += " ";
2451 FdStr += FD->getName();
2452 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002453 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002454 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002455 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002456 RewriteBlockPointerType(FdStr, ArgType);
2457 if (i+1 < numArgs)
2458 FdStr += ", ";
2459 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002460 if (FD->isVariadic()) {
2461 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2462 }
2463 else
2464 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002465 InsertText(FunLocStart, FdStr);
2466}
2467
Benjamin Kramer60509af2013-09-09 14:48:42 +00002468// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2469void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2470 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002471 return;
2472 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2473 SmallVector<QualType, 16> ArgTys;
2474 QualType argT = Context->getObjCIdType();
2475 assert(!argT.isNull() && "Can't find 'id' type");
2476 ArgTys.push_back(argT);
2477 ArgTys.push_back(argT);
2478 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002479 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002480 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002481 SourceLocation(),
2482 SourceLocation(),
2483 msgSendIdent, msgSendType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002484 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002485}
2486
2487// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2488void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2489 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2490 SmallVector<QualType, 16> ArgTys;
2491 QualType argT = Context->getObjCIdType();
2492 assert(!argT.isNull() && "Can't find 'id' type");
2493 ArgTys.push_back(argT);
2494 argT = Context->getObjCSelType();
2495 assert(!argT.isNull() && "Can't find 'SEL' type");
2496 ArgTys.push_back(argT);
2497 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002498 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002499 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002500 SourceLocation(),
2501 SourceLocation(),
2502 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002503 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002504}
2505
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002506// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002507void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2508 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002509 SmallVector<QualType, 2> ArgTys;
2510 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002511 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002512 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002513 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002514 SourceLocation(),
2515 SourceLocation(),
2516 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002517 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002518}
2519
2520// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2521void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2522 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2523 SmallVector<QualType, 16> ArgTys;
2524 QualType argT = Context->getObjCIdType();
2525 assert(!argT.isNull() && "Can't find 'id' type");
2526 ArgTys.push_back(argT);
2527 argT = Context->getObjCSelType();
2528 assert(!argT.isNull() && "Can't find 'SEL' type");
2529 ArgTys.push_back(argT);
2530 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002531 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002532 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002533 SourceLocation(),
2534 SourceLocation(),
2535 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002536 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002537}
2538
2539// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002540// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002541void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2542 IdentifierInfo *msgSendIdent =
2543 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002544 SmallVector<QualType, 2> ArgTys;
2545 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002546 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002547 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002548 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2549 SourceLocation(),
2550 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002551 msgSendIdent,
2552 msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002553 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002554}
2555
2556// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2557void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2558 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2559 SmallVector<QualType, 16> ArgTys;
2560 QualType argT = Context->getObjCIdType();
2561 assert(!argT.isNull() && "Can't find 'id' type");
2562 ArgTys.push_back(argT);
2563 argT = Context->getObjCSelType();
2564 assert(!argT.isNull() && "Can't find 'SEL' type");
2565 ArgTys.push_back(argT);
2566 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002567 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002568 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002569 SourceLocation(),
2570 SourceLocation(),
2571 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002572 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002573}
2574
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002575// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002576void RewriteModernObjC::SynthGetClassFunctionDecl() {
2577 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2578 SmallVector<QualType, 16> ArgTys;
2579 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002580 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002581 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002582 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002583 SourceLocation(),
2584 SourceLocation(),
2585 getClassIdent, getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002586 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002587}
2588
2589// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2590void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2591 IdentifierInfo *getSuperClassIdent =
2592 &Context->Idents.get("class_getSuperclass");
2593 SmallVector<QualType, 16> ArgTys;
2594 ArgTys.push_back(Context->getObjCClassType());
2595 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002596 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002597 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2598 SourceLocation(),
2599 SourceLocation(),
2600 getSuperClassIdent,
2601 getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002602 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002603}
2604
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002605// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002606void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2607 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2608 SmallVector<QualType, 16> ArgTys;
2609 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002610 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002611 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002612 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002613 SourceLocation(),
2614 SourceLocation(),
2615 getClassIdent, getClassType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002616 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002617}
2618
2619Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2620 QualType strType = getConstantStringStructType();
2621
2622 std::string S = "__NSConstantStringImpl_";
2623
2624 std::string tmpName = InFileName;
2625 unsigned i;
2626 for (i=0; i < tmpName.length(); i++) {
2627 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002628 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002629 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002630 tmpName[i] = '_';
2631 }
2632 S += tmpName;
2633 S += "_";
2634 S += utostr(NumObjCStringLiterals++);
2635
2636 Preamble += "static __NSConstantStringImpl " + S;
2637 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2638 Preamble += "0x000007c8,"; // utf8_str
2639 // The pretty printer for StringLiteral handles escape characters properly.
2640 std::string prettyBufS;
2641 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smith235341b2012-08-16 03:56:14 +00002642 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002643 Preamble += prettyBuf.str();
2644 Preamble += ",";
2645 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2646
2647 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2648 SourceLocation(), &Context->Idents.get(S),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002649 strType, 0, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002650 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002651 SourceLocation());
2652 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2653 Context->getPointerType(DRE->getType()),
2654 VK_RValue, OK_Ordinary,
2655 SourceLocation());
2656 // cast to NSConstantString *
2657 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2658 CK_CPointerToObjCPointerCast, Unop);
2659 ReplaceStmt(Exp, cast);
2660 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2661 return cast;
2662}
2663
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002664Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2665 unsigned IntSize =
2666 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2667
2668 Expr *FlagExp = IntegerLiteral::Create(*Context,
2669 llvm::APInt(IntSize, Exp->getValue()),
2670 Context->IntTy, Exp->getLocation());
2671 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2672 CK_BitCast, FlagExp);
2673 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2674 cast);
2675 ReplaceStmt(Exp, PE);
2676 return PE;
2677}
2678
Patrick Beard0caa3942012-04-19 00:25:12 +00002679Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002680 // synthesize declaration of helper functions needed in this routine.
2681 if (!SelGetUidFunctionDecl)
2682 SynthSelGetUidFunctionDecl();
2683 // use objc_msgSend() for all.
2684 if (!MsgSendFunctionDecl)
2685 SynthMsgSendFunctionDecl();
2686 if (!GetClassFunctionDecl)
2687 SynthGetClassFunctionDecl();
2688
2689 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2690 SourceLocation StartLoc = Exp->getLocStart();
2691 SourceLocation EndLoc = Exp->getLocEnd();
2692
2693 // Synthesize a call to objc_msgSend().
2694 SmallVector<Expr*, 4> MsgExprs;
2695 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002696
Patrick Beard0caa3942012-04-19 00:25:12 +00002697 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2698 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2699 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002700
Patrick Beard0caa3942012-04-19 00:25:12 +00002701 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002702 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002703 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2704 &ClsExprs[0],
2705 ClsExprs.size(),
2706 StartLoc, EndLoc);
2707 MsgExprs.push_back(Cls);
2708
Patrick Beard0caa3942012-04-19 00:25:12 +00002709 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002710 // it will be the 2nd argument.
2711 SmallVector<Expr*, 4> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002712 SelExprs.push_back(
2713 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002714 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2715 &SelExprs[0], SelExprs.size(),
2716 StartLoc, EndLoc);
2717 MsgExprs.push_back(SelExp);
2718
Patrick Beard0caa3942012-04-19 00:25:12 +00002719 // User provided sub-expression is the 3rd, and last, argument.
2720 Expr *subExpr = Exp->getSubExpr();
2721 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002722 QualType type = ICE->getType();
2723 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2724 CastKind CK = CK_BitCast;
2725 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2726 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002727 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002728 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002729 MsgExprs.push_back(subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002730
2731 SmallVector<QualType, 4> ArgTypes;
2732 ArgTypes.push_back(Context->getObjCIdType());
2733 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002734 for (const auto PI : BoxingMethod->parameters())
2735 ArgTypes.push_back(PI->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002736
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002737 QualType returnType = Exp->getType();
2738 // Get the type, we will need to reference it in a couple spots.
2739 QualType msgSendType = MsgSendFlavor->getType();
2740
2741 // Create a reference to the objc_msgSend() declaration.
2742 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2743 VK_LValue, SourceLocation());
2744
2745 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002746 Context->getPointerType(Context->VoidTy),
2747 CK_BitCast, DRE);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002748
2749 // Now do the "normal" pointer to function cast.
2750 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002751 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002752 castType = Context->getPointerType(castType);
2753 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2754 cast);
2755
2756 // Don't forget the parens to enforce the proper binding.
2757 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2758
2759 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002760 CallExpr *CE = new (Context)
2761 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002762 ReplaceStmt(Exp, CE);
2763 return CE;
2764}
2765
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002766Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2767 // synthesize declaration of helper functions needed in this routine.
2768 if (!SelGetUidFunctionDecl)
2769 SynthSelGetUidFunctionDecl();
2770 // use objc_msgSend() for all.
2771 if (!MsgSendFunctionDecl)
2772 SynthMsgSendFunctionDecl();
2773 if (!GetClassFunctionDecl)
2774 SynthGetClassFunctionDecl();
2775
2776 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2777 SourceLocation StartLoc = Exp->getLocStart();
2778 SourceLocation EndLoc = Exp->getLocEnd();
2779
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002780 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002781 QualType IntQT = Context->IntTy;
2782 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002783 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002784 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002785 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2786 DeclRefExpr *NSArrayDRE =
2787 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2788 SourceLocation());
2789
2790 SmallVector<Expr*, 16> InitExprs;
2791 unsigned NumElements = Exp->getNumElements();
2792 unsigned UnsignedIntSize =
2793 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2794 Expr *count = IntegerLiteral::Create(*Context,
2795 llvm::APInt(UnsignedIntSize, NumElements),
2796 Context->UnsignedIntTy, SourceLocation());
2797 InitExprs.push_back(count);
2798 for (unsigned i = 0; i < NumElements; i++)
2799 InitExprs.push_back(Exp->getElement(i));
2800 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002801 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002802 NSArrayFType, VK_LValue, SourceLocation());
2803
2804 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2805 SourceLocation(),
2806 &Context->Idents.get("arr"),
2807 Context->getPointerType(Context->VoidPtrTy), 0,
2808 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002809 ICIS_NoInit);
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002810 MemberExpr *ArrayLiteralME =
2811 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2812 SourceLocation(),
2813 ARRFD->getType(), VK_LValue,
2814 OK_Ordinary);
2815 QualType ConstIdT = Context->getObjCIdType().withConst();
2816 CStyleCastExpr * ArrayLiteralObjects =
2817 NoTypeInfoCStyleCastExpr(Context,
2818 Context->getPointerType(ConstIdT),
2819 CK_BitCast,
2820 ArrayLiteralME);
2821
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002822 // Synthesize a call to objc_msgSend().
2823 SmallVector<Expr*, 32> MsgExprs;
2824 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002825 QualType expType = Exp->getType();
2826
2827 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2828 ObjCInterfaceDecl *Class =
2829 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2830
2831 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002832 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002833 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2834 &ClsExprs[0],
2835 ClsExprs.size(),
2836 StartLoc, EndLoc);
2837 MsgExprs.push_back(Cls);
2838
2839 // Create a call to sel_registerName("arrayWithObjects:count:").
2840 // it will be the 2nd argument.
2841 SmallVector<Expr*, 4> SelExprs;
2842 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002843 SelExprs.push_back(
2844 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002845 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2846 &SelExprs[0], SelExprs.size(),
2847 StartLoc, EndLoc);
2848 MsgExprs.push_back(SelExp);
2849
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002850 // (const id [])objects
2851 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002852
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002853 // (NSUInteger)cnt
2854 Expr *cnt = IntegerLiteral::Create(*Context,
2855 llvm::APInt(UnsignedIntSize, NumElements),
2856 Context->UnsignedIntTy, SourceLocation());
2857 MsgExprs.push_back(cnt);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002858
2859
2860 SmallVector<QualType, 4> ArgTypes;
2861 ArgTypes.push_back(Context->getObjCIdType());
2862 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002863 for (const auto *PI : ArrayMethod->params())
2864 ArgTypes.push_back(PI->getType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002865
2866 QualType returnType = Exp->getType();
2867 // Get the type, we will need to reference it in a couple spots.
2868 QualType msgSendType = MsgSendFlavor->getType();
2869
2870 // Create a reference to the objc_msgSend() declaration.
2871 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2872 VK_LValue, SourceLocation());
2873
2874 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2875 Context->getPointerType(Context->VoidTy),
2876 CK_BitCast, DRE);
2877
2878 // Now do the "normal" pointer to function cast.
2879 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002880 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002881 castType = Context->getPointerType(castType);
2882 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2883 cast);
2884
2885 // Don't forget the parens to enforce the proper binding.
2886 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2887
2888 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002889 CallExpr *CE = new (Context)
2890 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002891 ReplaceStmt(Exp, CE);
2892 return CE;
2893}
2894
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002895Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2896 // synthesize declaration of helper functions needed in this routine.
2897 if (!SelGetUidFunctionDecl)
2898 SynthSelGetUidFunctionDecl();
2899 // use objc_msgSend() for all.
2900 if (!MsgSendFunctionDecl)
2901 SynthMsgSendFunctionDecl();
2902 if (!GetClassFunctionDecl)
2903 SynthGetClassFunctionDecl();
2904
2905 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2906 SourceLocation StartLoc = Exp->getLocStart();
2907 SourceLocation EndLoc = Exp->getLocEnd();
2908
2909 // Build the expression: __NSContainer_literal(int, ...).arr
2910 QualType IntQT = Context->IntTy;
2911 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002912 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002913 std::string NSDictFName("__NSContainer_literal");
2914 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2915 DeclRefExpr *NSDictDRE =
2916 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2917 SourceLocation());
2918
2919 SmallVector<Expr*, 16> KeyExprs;
2920 SmallVector<Expr*, 16> ValueExprs;
2921
2922 unsigned NumElements = Exp->getNumElements();
2923 unsigned UnsignedIntSize =
2924 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2925 Expr *count = IntegerLiteral::Create(*Context,
2926 llvm::APInt(UnsignedIntSize, NumElements),
2927 Context->UnsignedIntTy, SourceLocation());
2928 KeyExprs.push_back(count);
2929 ValueExprs.push_back(count);
2930 for (unsigned i = 0; i < NumElements; i++) {
2931 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2932 KeyExprs.push_back(Element.Key);
2933 ValueExprs.push_back(Element.Value);
2934 }
2935
2936 // (const id [])objects
2937 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002938 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002939 NSDictFType, VK_LValue, SourceLocation());
2940
2941 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2942 SourceLocation(),
2943 &Context->Idents.get("arr"),
2944 Context->getPointerType(Context->VoidPtrTy), 0,
2945 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002946 ICIS_NoInit);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002947 MemberExpr *DictLiteralValueME =
2948 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2949 SourceLocation(),
2950 ARRFD->getType(), VK_LValue,
2951 OK_Ordinary);
2952 QualType ConstIdT = Context->getObjCIdType().withConst();
2953 CStyleCastExpr * DictValueObjects =
2954 NoTypeInfoCStyleCastExpr(Context,
2955 Context->getPointerType(ConstIdT),
2956 CK_BitCast,
2957 DictLiteralValueME);
2958 // (const id <NSCopying> [])keys
2959 Expr *NSKeyCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002960 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002961 NSDictFType, VK_LValue, SourceLocation());
2962
2963 MemberExpr *DictLiteralKeyME =
2964 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2965 SourceLocation(),
2966 ARRFD->getType(), VK_LValue,
2967 OK_Ordinary);
2968
2969 CStyleCastExpr * DictKeyObjects =
2970 NoTypeInfoCStyleCastExpr(Context,
2971 Context->getPointerType(ConstIdT),
2972 CK_BitCast,
2973 DictLiteralKeyME);
2974
2975
2976
2977 // Synthesize a call to objc_msgSend().
2978 SmallVector<Expr*, 32> MsgExprs;
2979 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002980 QualType expType = Exp->getType();
2981
2982 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2983 ObjCInterfaceDecl *Class =
2984 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2985
2986 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002987 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002988 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2989 &ClsExprs[0],
2990 ClsExprs.size(),
2991 StartLoc, EndLoc);
2992 MsgExprs.push_back(Cls);
2993
2994 // Create a call to sel_registerName("arrayWithObjects:count:").
2995 // it will be the 2nd argument.
2996 SmallVector<Expr*, 4> SelExprs;
2997 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002998 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002999 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3000 &SelExprs[0], SelExprs.size(),
3001 StartLoc, EndLoc);
3002 MsgExprs.push_back(SelExp);
3003
3004 // (const id [])objects
3005 MsgExprs.push_back(DictValueObjects);
3006
3007 // (const id <NSCopying> [])keys
3008 MsgExprs.push_back(DictKeyObjects);
3009
3010 // (NSUInteger)cnt
3011 Expr *cnt = IntegerLiteral::Create(*Context,
3012 llvm::APInt(UnsignedIntSize, NumElements),
3013 Context->UnsignedIntTy, SourceLocation());
3014 MsgExprs.push_back(cnt);
3015
3016
3017 SmallVector<QualType, 8> ArgTypes;
3018 ArgTypes.push_back(Context->getObjCIdType());
3019 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00003020 for (const auto *PI : DictMethod->params()) {
3021 QualType T = PI->getType();
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003022 if (const PointerType* PT = T->getAs<PointerType>()) {
3023 QualType PointeeTy = PT->getPointeeType();
3024 convertToUnqualifiedObjCType(PointeeTy);
3025 T = Context->getPointerType(PointeeTy);
3026 }
3027 ArgTypes.push_back(T);
3028 }
3029
3030 QualType returnType = Exp->getType();
3031 // Get the type, we will need to reference it in a couple spots.
3032 QualType msgSendType = MsgSendFlavor->getType();
3033
3034 // Create a reference to the objc_msgSend() declaration.
3035 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3036 VK_LValue, SourceLocation());
3037
3038 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3039 Context->getPointerType(Context->VoidTy),
3040 CK_BitCast, DRE);
3041
3042 // Now do the "normal" pointer to function cast.
3043 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003044 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003045 castType = Context->getPointerType(castType);
3046 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3047 cast);
3048
3049 // Don't forget the parens to enforce the proper binding.
3050 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3051
3052 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003053 CallExpr *CE = new (Context)
3054 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003055 ReplaceStmt(Exp, CE);
3056 return CE;
3057}
3058
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003059// struct __rw_objc_super {
3060// struct objc_object *object; struct objc_object *superClass;
3061// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00003062QualType RewriteModernObjC::getSuperStructType() {
3063 if (!SuperStructDecl) {
3064 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3065 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003066 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003067 QualType FieldTypes[2];
3068
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003069 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003070 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003071 // struct objc_object *superClass;
3072 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003073
3074 // Create fields
3075 for (unsigned i = 0; i < 2; ++i) {
3076 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3077 SourceLocation(),
3078 SourceLocation(), 0,
3079 FieldTypes[i], 0,
3080 /*BitWidth=*/0,
3081 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003082 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003083 }
3084
3085 SuperStructDecl->completeDefinition();
3086 }
3087 return Context->getTagDeclType(SuperStructDecl);
3088}
3089
3090QualType RewriteModernObjC::getConstantStringStructType() {
3091 if (!ConstantStringDecl) {
3092 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3093 SourceLocation(), SourceLocation(),
3094 &Context->Idents.get("__NSConstantStringImpl"));
3095 QualType FieldTypes[4];
3096
3097 // struct objc_object *receiver;
3098 FieldTypes[0] = Context->getObjCIdType();
3099 // int flags;
3100 FieldTypes[1] = Context->IntTy;
3101 // char *str;
3102 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3103 // long length;
3104 FieldTypes[3] = Context->LongTy;
3105
3106 // Create fields
3107 for (unsigned i = 0; i < 4; ++i) {
3108 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3109 ConstantStringDecl,
3110 SourceLocation(),
3111 SourceLocation(), 0,
3112 FieldTypes[i], 0,
3113 /*BitWidth=*/0,
3114 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003115 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003116 }
3117
3118 ConstantStringDecl->completeDefinition();
3119 }
3120 return Context->getTagDeclType(ConstantStringDecl);
3121}
3122
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003123/// getFunctionSourceLocation - returns start location of a function
3124/// definition. Complication arises when function has declared as
3125/// extern "C" or extern "C" {...}
3126static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3127 FunctionDecl *FD) {
3128 if (FD->isExternC() && !FD->isMain()) {
3129 const DeclContext *DC = FD->getDeclContext();
3130 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3131 // if it is extern "C" {...}, return function decl's own location.
3132 if (!LSD->getRBraceLoc().isValid())
3133 return LSD->getExternLoc();
3134 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003135 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003136 R.RewriteBlockLiteralFunctionDecl(FD);
3137 return FD->getTypeSpecStartLoc();
3138}
3139
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003140void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3141
3142 SourceLocation Location = D->getLocation();
3143
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003144 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003145 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003146 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3147 LineString += utostr(PLoc.getLine());
3148 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003149 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003150 if (isa<ObjCMethodDecl>(D))
3151 LineString += "\"";
3152 else LineString += "\"\n";
3153
3154 Location = D->getLocStart();
3155 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3156 if (FD->isExternC() && !FD->isMain()) {
3157 const DeclContext *DC = FD->getDeclContext();
3158 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3159 // if it is extern "C" {...}, return function decl's own location.
3160 if (!LSD->getRBraceLoc().isValid())
3161 Location = LSD->getExternLoc();
3162 }
3163 }
3164 InsertText(Location, LineString);
3165 }
3166}
3167
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003168/// SynthMsgSendStretCallExpr - This routine translates message expression
3169/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3170/// nil check on receiver must be performed before calling objc_msgSend_stret.
3171/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3172/// msgSendType - function type of objc_msgSend_stret(...)
3173/// returnType - Result type of the method being synthesized.
3174/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3175/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3176/// starting with receiver.
3177/// Method - Method being rewritten.
3178Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003179 QualType returnType,
3180 SmallVectorImpl<QualType> &ArgTypes,
3181 SmallVectorImpl<Expr*> &MsgExprs,
3182 ObjCMethodDecl *Method) {
3183 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003184 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3185 Method ? Method->isVariadic()
3186 : false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003187 castType = Context->getPointerType(castType);
3188
3189 // build type for containing the objc_msgSend_stret object.
3190 static unsigned stretCount=0;
3191 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003192 std::string str =
3193 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003194 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003195 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003196 str += " {\n\t";
3197 str += name;
3198 str += "(id receiver, SEL sel";
3199 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003200 std::string ArgName = "arg"; ArgName += utostr(i);
3201 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3202 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003203 }
3204 // could be vararg.
3205 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003206 std::string ArgName = "arg"; ArgName += utostr(i);
3207 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3208 Context->getPrintingPolicy());
3209 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003210 }
3211
3212 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003213 str += "\t unsigned size = sizeof(";
3214 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3215
3216 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3217
3218 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3219 str += ")(void *)objc_msgSend)(receiver, sel";
3220 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3221 str += ", arg"; str += utostr(i);
3222 }
3223 // could be vararg.
3224 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3225 str += ", arg"; str += utostr(i);
3226 }
3227 str+= ");\n";
3228
3229 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003230 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3231 str += "\t else\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003232
3233
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003234 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3235 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3236 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3237 str += ", arg"; str += utostr(i);
3238 }
3239 // could be vararg.
3240 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3241 str += ", arg"; str += utostr(i);
3242 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003243 str += ");\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003244
3245
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003246 str += "\t}\n";
3247 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3248 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003249 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003250 SourceLocation FunLocStart;
3251 if (CurFunctionDef)
3252 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3253 else {
3254 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3255 FunLocStart = CurMethodDef->getLocStart();
3256 }
3257
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003258 InsertText(FunLocStart, str);
3259 ++stretCount;
3260
3261 // AST for __Stretn(receiver, args).s;
3262 IdentifierInfo *ID = &Context->Idents.get(name);
3263 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00003264 SourceLocation(), ID, castType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003265 SC_Extern, false, false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003266 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3267 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003268 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003269 castType, VK_LValue, SourceLocation());
3270
3271 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3272 SourceLocation(),
3273 &Context->Idents.get("s"),
3274 returnType, 0,
3275 /*BitWidth=*/0, /*Mutable=*/true,
3276 ICIS_NoInit);
3277 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3278 FieldD->getType(), VK_LValue,
3279 OK_Ordinary);
3280
3281 return ME;
3282}
3283
Fariborz Jahanian11671902012-02-07 17:11:38 +00003284Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3285 SourceLocation StartLoc,
3286 SourceLocation EndLoc) {
3287 if (!SelGetUidFunctionDecl)
3288 SynthSelGetUidFunctionDecl();
3289 if (!MsgSendFunctionDecl)
3290 SynthMsgSendFunctionDecl();
3291 if (!MsgSendSuperFunctionDecl)
3292 SynthMsgSendSuperFunctionDecl();
3293 if (!MsgSendStretFunctionDecl)
3294 SynthMsgSendStretFunctionDecl();
3295 if (!MsgSendSuperStretFunctionDecl)
3296 SynthMsgSendSuperStretFunctionDecl();
3297 if (!MsgSendFpretFunctionDecl)
3298 SynthMsgSendFpretFunctionDecl();
3299 if (!GetClassFunctionDecl)
3300 SynthGetClassFunctionDecl();
3301 if (!GetSuperClassFunctionDecl)
3302 SynthGetSuperClassFunctionDecl();
3303 if (!GetMetaClassFunctionDecl)
3304 SynthGetMetaClassFunctionDecl();
3305
3306 // default to objc_msgSend().
3307 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3308 // May need to use objc_msgSend_stret() as well.
3309 FunctionDecl *MsgSendStretFlavor = 0;
3310 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003311 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003312 if (resultType->isRecordType())
3313 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3314 else if (resultType->isRealFloatingType())
3315 MsgSendFlavor = MsgSendFpretFunctionDecl;
3316 }
3317
3318 // Synthesize a call to objc_msgSend().
3319 SmallVector<Expr*, 8> MsgExprs;
3320 switch (Exp->getReceiverKind()) {
3321 case ObjCMessageExpr::SuperClass: {
3322 MsgSendFlavor = MsgSendSuperFunctionDecl;
3323 if (MsgSendStretFlavor)
3324 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3325 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3326
3327 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3328
3329 SmallVector<Expr*, 4> InitExprs;
3330
3331 // set the receiver to self, the first argument to all methods.
3332 InitExprs.push_back(
3333 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3334 CK_BitCast,
3335 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003336 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003337 Context->getObjCIdType(),
3338 VK_RValue,
3339 SourceLocation()))
3340 ); // set the 'receiver'.
3341
3342 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3343 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003344 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003345 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003346 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3347 &ClsExprs[0],
3348 ClsExprs.size(),
3349 StartLoc,
3350 EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003351 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003352 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003353 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3354 &ClsExprs[0], ClsExprs.size(),
3355 StartLoc, EndLoc);
3356
3357 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3358 // To turn off a warning, type-cast to 'id'
3359 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3360 NoTypeInfoCStyleCastExpr(Context,
3361 Context->getObjCIdType(),
3362 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003363 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003364 QualType superType = getSuperStructType();
3365 Expr *SuperRep;
3366
3367 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003368 SynthSuperConstructorFunctionDecl();
3369 // Simulate a constructor call...
3370 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003371 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003372 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003373 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003374 superType, VK_LValue,
3375 SourceLocation());
3376 // The code for super is a little tricky to prevent collision with
3377 // the structure definition in the header. The rewriter has it's own
3378 // internal definition (__rw_objc_super) that is uses. This is why
3379 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003380 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003381 //
3382 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3383 Context->getPointerType(SuperRep->getType()),
3384 VK_RValue, OK_Ordinary,
3385 SourceLocation());
3386 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3387 Context->getPointerType(superType),
3388 CK_BitCast, SuperRep);
3389 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003390 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003391 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003392 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003393 SourceLocation());
3394 TypeSourceInfo *superTInfo
3395 = Context->getTrivialTypeSourceInfo(superType);
3396 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3397 superType, VK_LValue,
3398 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003399 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003400 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3401 Context->getPointerType(SuperRep->getType()),
3402 VK_RValue, OK_Ordinary,
3403 SourceLocation());
3404 }
3405 MsgExprs.push_back(SuperRep);
3406 break;
3407 }
3408
3409 case ObjCMessageExpr::Class: {
3410 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003411 ObjCInterfaceDecl *Class
3412 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3413 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003414 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003415 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3416 &ClsExprs[0],
3417 ClsExprs.size(),
3418 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003419 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3420 Context->getObjCIdType(),
3421 CK_BitCast, Cls);
3422 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003423 break;
3424 }
3425
3426 case ObjCMessageExpr::SuperInstance:{
3427 MsgSendFlavor = MsgSendSuperFunctionDecl;
3428 if (MsgSendStretFlavor)
3429 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3430 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3431 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3432 SmallVector<Expr*, 4> InitExprs;
3433
3434 InitExprs.push_back(
3435 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3436 CK_BitCast,
3437 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003438 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003439 Context->getObjCIdType(),
3440 VK_RValue, SourceLocation()))
3441 ); // set the 'receiver'.
3442
3443 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3444 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003445 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003446 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003447 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3448 &ClsExprs[0],
3449 ClsExprs.size(),
3450 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003451 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003452 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003453 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3454 &ClsExprs[0], ClsExprs.size(),
3455 StartLoc, EndLoc);
3456
3457 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3458 // To turn off a warning, type-cast to 'id'
3459 InitExprs.push_back(
3460 // set 'super class', using class_getSuperclass().
3461 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3462 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003463 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003464 QualType superType = getSuperStructType();
3465 Expr *SuperRep;
3466
3467 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003468 SynthSuperConstructorFunctionDecl();
3469 // Simulate a constructor call...
3470 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003471 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003472 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003473 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003474 superType, VK_LValue, SourceLocation());
3475 // The code for super is a little tricky to prevent collision with
3476 // the structure definition in the header. The rewriter has it's own
3477 // internal definition (__rw_objc_super) that is uses. This is why
3478 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003479 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003480 //
3481 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3482 Context->getPointerType(SuperRep->getType()),
3483 VK_RValue, OK_Ordinary,
3484 SourceLocation());
3485 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3486 Context->getPointerType(superType),
3487 CK_BitCast, SuperRep);
3488 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003489 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003490 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003491 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003492 SourceLocation());
3493 TypeSourceInfo *superTInfo
3494 = Context->getTrivialTypeSourceInfo(superType);
3495 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3496 superType, VK_RValue, ILE,
3497 false);
3498 }
3499 MsgExprs.push_back(SuperRep);
3500 break;
3501 }
3502
3503 case ObjCMessageExpr::Instance: {
3504 // Remove all type-casts because it may contain objc-style types; e.g.
3505 // Foo<Proto> *.
3506 Expr *recExpr = Exp->getInstanceReceiver();
3507 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3508 recExpr = CE->getSubExpr();
3509 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3510 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3511 ? CK_BlockPointerToObjCPointerCast
3512 : CK_CPointerToObjCPointerCast;
3513
3514 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3515 CK, recExpr);
3516 MsgExprs.push_back(recExpr);
3517 break;
3518 }
3519 }
3520
3521 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3522 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003523 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003524 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3525 &SelExprs[0], SelExprs.size(),
3526 StartLoc,
3527 EndLoc);
3528 MsgExprs.push_back(SelExp);
3529
3530 // Now push any user supplied arguments.
3531 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3532 Expr *userExpr = Exp->getArg(i);
3533 // Make all implicit casts explicit...ICE comes in handy:-)
3534 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3535 // Reuse the ICE type, it is exactly what the doctor ordered.
3536 QualType type = ICE->getType();
3537 if (needToScanForQualifiers(type))
3538 type = Context->getObjCIdType();
3539 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3540 (void)convertBlockPointerToFunctionPointer(type);
3541 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3542 CastKind CK;
3543 if (SubExpr->getType()->isIntegralType(*Context) &&
3544 type->isBooleanType()) {
3545 CK = CK_IntegralToBoolean;
3546 } else if (type->isObjCObjectPointerType()) {
3547 if (SubExpr->getType()->isBlockPointerType()) {
3548 CK = CK_BlockPointerToObjCPointerCast;
3549 } else if (SubExpr->getType()->isPointerType()) {
3550 CK = CK_CPointerToObjCPointerCast;
3551 } else {
3552 CK = CK_BitCast;
3553 }
3554 } else {
3555 CK = CK_BitCast;
3556 }
3557
3558 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3559 }
3560 // Make id<P...> cast into an 'id' cast.
3561 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3562 if (CE->getType()->isObjCQualifiedIdType()) {
3563 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3564 userExpr = CE->getSubExpr();
3565 CastKind CK;
3566 if (userExpr->getType()->isIntegralType(*Context)) {
3567 CK = CK_IntegralToPointer;
3568 } else if (userExpr->getType()->isBlockPointerType()) {
3569 CK = CK_BlockPointerToObjCPointerCast;
3570 } else if (userExpr->getType()->isPointerType()) {
3571 CK = CK_CPointerToObjCPointerCast;
3572 } else {
3573 CK = CK_BitCast;
3574 }
3575 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3576 CK, userExpr);
3577 }
3578 }
3579 MsgExprs.push_back(userExpr);
3580 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3581 // out the argument in the original expression (since we aren't deleting
3582 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3583 //Exp->setArg(i, 0);
3584 }
3585 // Generate the funky cast.
3586 CastExpr *cast;
3587 SmallVector<QualType, 8> ArgTypes;
3588 QualType returnType;
3589
3590 // Push 'id' and 'SEL', the 2 implicit arguments.
3591 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3592 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3593 else
3594 ArgTypes.push_back(Context->getObjCIdType());
3595 ArgTypes.push_back(Context->getObjCSelType());
3596 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3597 // Push any user argument types.
Aaron Ballman43b68be2014-03-07 17:50:17 +00003598 for (const auto *PI : OMD->params()) {
3599 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian11671902012-02-07 17:11:38 +00003600 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00003601 : PI->getType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003602 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3603 (void)convertBlockPointerToFunctionPointer(t);
3604 ArgTypes.push_back(t);
3605 }
3606 returnType = Exp->getType();
3607 convertToUnqualifiedObjCType(returnType);
3608 (void)convertBlockPointerToFunctionPointer(returnType);
3609 } else {
3610 returnType = Context->getObjCIdType();
3611 }
3612 // Get the type, we will need to reference it in a couple spots.
3613 QualType msgSendType = MsgSendFlavor->getType();
3614
3615 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003616 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003617 VK_LValue, SourceLocation());
3618
3619 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3620 // If we don't do this cast, we get the following bizarre warning/note:
3621 // xx.m:13: warning: function called through a non-compatible type
3622 // xx.m:13: note: if this code is reached, the program will abort
3623 cast = NoTypeInfoCStyleCastExpr(Context,
3624 Context->getPointerType(Context->VoidTy),
3625 CK_BitCast, DRE);
3626
3627 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003628 // If we don't have a method decl, force a variadic cast.
3629 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003630 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003631 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003632 castType = Context->getPointerType(castType);
3633 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3634 cast);
3635
3636 // Don't forget the parens to enforce the proper binding.
3637 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3638
3639 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003640 CallExpr *CE = new (Context)
3641 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003642 Stmt *ReplacingStmt = CE;
3643 if (MsgSendStretFlavor) {
3644 // We have the method which returns a struct/union. Must also generate
3645 // call to objc_msgSend_stret and hang both varieties on a conditional
3646 // expression which dictate which one to envoke depending on size of
3647 // method's return type.
3648
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003649 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3650 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003651 ArgTypes, MsgExprs,
3652 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003653 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003654 }
3655 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3656 return ReplacingStmt;
3657}
3658
3659Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3660 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3661 Exp->getLocEnd());
3662
3663 // Now do the actual rewrite.
3664 ReplaceStmt(Exp, ReplacingStmt);
3665
3666 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3667 return ReplacingStmt;
3668}
3669
3670// typedef struct objc_object Protocol;
3671QualType RewriteModernObjC::getProtocolType() {
3672 if (!ProtocolTypeDecl) {
3673 TypeSourceInfo *TInfo
3674 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3675 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3676 SourceLocation(), SourceLocation(),
3677 &Context->Idents.get("Protocol"),
3678 TInfo);
3679 }
3680 return Context->getTypeDeclType(ProtocolTypeDecl);
3681}
3682
3683/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3684/// a synthesized/forward data reference (to the protocol's metadata).
3685/// The forward references (and metadata) are generated in
3686/// RewriteModernObjC::HandleTranslationUnit().
3687Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003688 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3689 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003690 IdentifierInfo *ID = &Context->Idents.get(Name);
3691 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3692 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003693 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003694 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3695 VK_LValue, SourceLocation());
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003696 CastExpr *castExpr =
3697 NoTypeInfoCStyleCastExpr(
3698 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003699 ReplaceStmt(Exp, castExpr);
3700 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3701 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3702 return castExpr;
3703
3704}
3705
3706bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3707 const char *endBuf) {
3708 while (startBuf < endBuf) {
3709 if (*startBuf == '#') {
3710 // Skip whitespace.
3711 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3712 ;
3713 if (!strncmp(startBuf, "if", strlen("if")) ||
3714 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3715 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3716 !strncmp(startBuf, "define", strlen("define")) ||
3717 !strncmp(startBuf, "undef", strlen("undef")) ||
3718 !strncmp(startBuf, "else", strlen("else")) ||
3719 !strncmp(startBuf, "elif", strlen("elif")) ||
3720 !strncmp(startBuf, "endif", strlen("endif")) ||
3721 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3722 !strncmp(startBuf, "include", strlen("include")) ||
3723 !strncmp(startBuf, "import", strlen("import")) ||
3724 !strncmp(startBuf, "include_next", strlen("include_next")))
3725 return true;
3726 }
3727 startBuf++;
3728 }
3729 return false;
3730}
3731
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003732/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3733/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003734bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003735 TagDecl *Tag,
3736 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003737 if (!IDecl)
3738 return false;
3739 SourceLocation TagLocation;
3740 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3741 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003742 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003743 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003744 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003745 TagLocation = RD->getLocation();
3746 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003747 IDecl->getLocation(), TagLocation);
3748 }
3749 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3750 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3751 return false;
3752 IsNamedDefinition = true;
3753 TagLocation = ED->getLocation();
3754 return Context->getSourceManager().isBeforeInTranslationUnit(
3755 IDecl->getLocation(), TagLocation);
3756
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003757 }
3758 return false;
3759}
3760
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003761/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003762/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003763bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3764 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003765 if (isa<TypedefType>(Type)) {
3766 Result += "\t";
3767 return false;
3768 }
3769
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003770 if (Type->isArrayType()) {
3771 QualType ElemTy = Context->getBaseElementType(Type);
3772 return RewriteObjCFieldDeclType(ElemTy, Result);
3773 }
3774 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003775 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3776 if (RD->isCompleteDefinition()) {
3777 if (RD->isStruct())
3778 Result += "\n\tstruct ";
3779 else if (RD->isUnion())
3780 Result += "\n\tunion ";
3781 else
3782 assert(false && "class not allowed as an ivar type");
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003783
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003784 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003785 if (GlobalDefinedTags.count(RD)) {
3786 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003787 Result += " ";
3788 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003789 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003790 Result += " {\n";
3791 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003792 e = RD->field_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00003793 FieldDecl *FD = *i;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003794 RewriteObjCFieldDecl(FD, Result);
3795 }
3796 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003797 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003798 }
3799 }
3800 else if (Type->isEnumeralType()) {
3801 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3802 if (ED->isCompleteDefinition()) {
3803 Result += "\n\tenum ";
3804 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003805 if (GlobalDefinedTags.count(ED)) {
3806 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003807 Result += " ";
3808 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003809 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003810
3811 Result += " {\n";
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003812 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003813 Result += "\t"; Result += EC->getName(); Result += " = ";
3814 llvm::APSInt Val = EC->getInitVal();
3815 Result += Val.toString(10);
3816 Result += ",\n";
3817 }
3818 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003819 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003820 }
3821 }
3822
3823 Result += "\t";
3824 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003825 return false;
3826}
3827
3828
3829/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3830/// It handles elaborated types, as well as enum types in the process.
3831void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3832 std::string &Result) {
3833 QualType Type = fieldDecl->getType();
3834 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003835
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003836 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3837 if (!EleboratedType)
3838 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003839 Result += Name;
3840 if (fieldDecl->isBitField()) {
3841 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3842 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003843 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003844 const ArrayType *AT = Context->getAsArrayType(Type);
3845 do {
3846 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003847 Result += "[";
3848 llvm::APInt Dim = CAT->getSize();
3849 Result += utostr(Dim.getZExtValue());
3850 Result += "]";
3851 }
Eli Friedman07bab732012-12-13 01:43:21 +00003852 AT = Context->getAsArrayType(AT->getElementType());
3853 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003854 }
3855
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003856 Result += ";\n";
3857}
3858
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003859/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3860/// named aggregate types into the input buffer.
3861void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3862 std::string &Result) {
3863 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003864 if (isa<TypedefType>(Type))
3865 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003866 if (Type->isArrayType())
3867 Type = Context->getBaseElementType(Type);
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003868 ObjCContainerDecl *IDecl =
3869 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003870
3871 TagDecl *TD = 0;
3872 if (Type->isRecordType()) {
3873 TD = Type->getAs<RecordType>()->getDecl();
3874 }
3875 else if (Type->isEnumeralType()) {
3876 TD = Type->getAs<EnumType>()->getDecl();
3877 }
3878
3879 if (TD) {
3880 if (GlobalDefinedTags.count(TD))
3881 return;
3882
3883 bool IsNamedDefinition = false;
3884 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3885 RewriteObjCFieldDeclType(Type, Result);
3886 Result += ";";
3887 }
3888 if (IsNamedDefinition)
3889 GlobalDefinedTags.insert(TD);
3890 }
3891
3892}
3893
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003894unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3895 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3896 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3897 return IvarGroupNumber[IV];
3898 }
3899 unsigned GroupNo = 0;
3900 SmallVector<const ObjCIvarDecl *, 8> IVars;
3901 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3902 IVD; IVD = IVD->getNextIvar())
3903 IVars.push_back(IVD);
3904
3905 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3906 if (IVars[i]->isBitField()) {
3907 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3908 while (i < e && IVars[i]->isBitField())
3909 IvarGroupNumber[IVars[i++]] = GroupNo;
3910 if (i < e)
3911 --i;
3912 }
3913
3914 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3915 return IvarGroupNumber[IV];
3916}
3917
3918QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3919 ObjCIvarDecl *IV,
3920 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3921 std::string StructTagName;
3922 ObjCIvarBitfieldGroupType(IV, StructTagName);
3923 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3924 Context->getTranslationUnitDecl(),
3925 SourceLocation(), SourceLocation(),
3926 &Context->Idents.get(StructTagName));
3927 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3928 ObjCIvarDecl *Ivar = IVars[i];
3929 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3930 &Context->Idents.get(Ivar->getName()),
3931 Ivar->getType(),
3932 0, /*Expr *BW */Ivar->getBitWidth(), false,
3933 ICIS_NoInit));
3934 }
3935 RD->completeDefinition();
3936 return Context->getTagDeclType(RD);
3937}
3938
3939QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3940 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3941 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3942 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3943 if (GroupRecordType.count(tuple))
3944 return GroupRecordType[tuple];
3945
3946 SmallVector<ObjCIvarDecl *, 8> IVars;
3947 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3948 IVD; IVD = IVD->getNextIvar()) {
3949 if (IVD->isBitField())
3950 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3951 else {
3952 if (!IVars.empty()) {
3953 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3954 // Generate the struct type for this group of bitfield ivars.
3955 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3956 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3957 IVars.clear();
3958 }
3959 }
3960 }
3961 if (!IVars.empty()) {
3962 // Do the last one.
3963 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3964 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3965 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3966 }
3967 QualType RetQT = GroupRecordType[tuple];
3968 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3969
3970 return RetQT;
3971}
3972
3973/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3974/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3975void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3976 std::string &Result) {
3977 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3978 Result += CDecl->getName();
3979 Result += "__GRBF_";
3980 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3981 Result += utostr(GroupNo);
3982 return;
3983}
3984
3985/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3986/// Name of the struct would be: classname__T_n where n is the group number for
3987/// this ivar.
3988void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3989 std::string &Result) {
3990 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3991 Result += CDecl->getName();
3992 Result += "__T_";
3993 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3994 Result += utostr(GroupNo);
3995 return;
3996}
3997
3998/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3999/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
4000/// this ivar.
4001void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
4002 std::string &Result) {
4003 Result += "OBJC_IVAR_$_";
4004 ObjCIvarBitfieldGroupDecl(IV, Result);
4005}
4006
4007#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
4008 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
4009 ++IX; \
4010 if (IX < ENDIX) \
4011 --IX; \
4012}
4013
Fariborz Jahanian11671902012-02-07 17:11:38 +00004014/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
4015/// an objective-c class with ivars.
4016void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
4017 std::string &Result) {
4018 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
4019 assert(CDecl->getName() != "" &&
4020 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004021 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004022 SmallVector<ObjCIvarDecl *, 8> IVars;
4023 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00004024 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004025 IVars.push_back(IVD);
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00004026
Fariborz Jahanian11671902012-02-07 17:11:38 +00004027 SourceLocation LocStart = CDecl->getLocStart();
4028 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004029
Fariborz Jahanian11671902012-02-07 17:11:38 +00004030 const char *startBuf = SM->getCharacterData(LocStart);
4031 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004032
Fariborz Jahanian11671902012-02-07 17:11:38 +00004033 // If no ivars and no root or if its root, directly or indirectly,
4034 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004035 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00004036 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4037 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4038 ReplaceText(LocStart, endBuf-startBuf, Result);
4039 return;
4040 }
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004041
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004042 // Insert named struct/union definitions inside class to
4043 // outer scope. This follows semantics of locally defined
4044 // struct/unions in objective-c classes.
4045 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4046 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004047
4048 // Insert named structs which are syntheized to group ivar bitfields
4049 // to outer scope as well.
4050 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4051 if (IVars[i]->isBitField()) {
4052 ObjCIvarDecl *IV = IVars[i];
4053 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4054 RewriteObjCFieldDeclType(QT, Result);
4055 Result += ";";
4056 // skip over ivar bitfields in this group.
4057 SKIP_BITFIELDS(i , e, IVars);
4058 }
4059
Fariborz Jahanian11671902012-02-07 17:11:38 +00004060 Result += "\nstruct ";
4061 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004062 Result += "_IMPL {\n";
4063
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004064 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004065 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4066 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4067 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004068 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004069
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004070 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4071 if (IVars[i]->isBitField()) {
4072 ObjCIvarDecl *IV = IVars[i];
4073 Result += "\tstruct ";
4074 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4075 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4076 // skip over ivar bitfields in this group.
4077 SKIP_BITFIELDS(i , e, IVars);
4078 }
4079 else
4080 RewriteObjCFieldDecl(IVars[i], Result);
4081 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00004082
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004083 Result += "};\n";
4084 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4085 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004086 // Mark this struct as having been generated.
4087 if (!ObjCSynthesizedStructs.insert(CDecl))
4088 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004089}
4090
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004091/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4092/// have been referenced in an ivar access expression.
4093void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4094 std::string &Result) {
4095 // write out ivar offset symbols which have been referenced in an ivar
4096 // access expression.
4097 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4098 if (Ivars.empty())
4099 return;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004100
4101 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004102 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4103 e = Ivars.end(); i != e; i++) {
4104 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004105 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4106 unsigned GroupNo = 0;
4107 if (IvarDecl->isBitField()) {
4108 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4109 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4110 continue;
4111 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004112 Result += "\n";
4113 if (LangOpts.MicrosoftExt)
4114 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004115 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004116 if (LangOpts.MicrosoftExt &&
4117 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004118 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4119 Result += "__declspec(dllimport) ";
4120
Fariborz Jahanian38c59102012-03-27 16:21:30 +00004121 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004122 if (IvarDecl->isBitField()) {
4123 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4124 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4125 }
4126 else
4127 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00004128 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004129 }
4130}
4131
Fariborz Jahanian11671902012-02-07 17:11:38 +00004132//===----------------------------------------------------------------------===//
4133// Meta Data Emission
4134//===----------------------------------------------------------------------===//
4135
4136
4137/// RewriteImplementations - This routine rewrites all method implementations
4138/// and emits meta-data.
4139
4140void RewriteModernObjC::RewriteImplementations() {
4141 int ClsDefCount = ClassImplementation.size();
4142 int CatDefCount = CategoryImplementation.size();
4143
4144 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004145 for (int i = 0; i < ClsDefCount; i++) {
4146 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4147 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4148 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004149 assert(false &&
4150 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004151 RewriteImplementationDecl(OIMP);
4152 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004153
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004154 for (int i = 0; i < CatDefCount; i++) {
4155 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4156 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4157 if (CDecl->isImplicitInterfaceDecl())
4158 assert(false &&
4159 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004160 RewriteImplementationDecl(CIMP);
4161 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004162}
4163
4164void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4165 const std::string &Name,
4166 ValueDecl *VD, bool def) {
4167 assert(BlockByRefDeclNo.count(VD) &&
4168 "RewriteByRefString: ByRef decl missing");
4169 if (def)
4170 ResultStr += "struct ";
4171 ResultStr += "__Block_byref_" + Name +
4172 "_" + utostr(BlockByRefDeclNo[VD]) ;
4173}
4174
4175static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4176 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4177 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4178 return false;
4179}
4180
4181std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4182 StringRef funcName,
4183 std::string Tag) {
4184 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004185 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004186 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004187 SourceLocation BlockLoc = CE->getExprLoc();
4188 std::string S;
4189 ConvertSourceLocationToLineDirective(BlockLoc, S);
4190
4191 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4192 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004193
4194 BlockDecl *BD = CE->getBlockDecl();
4195
4196 if (isa<FunctionNoProtoType>(AFT)) {
4197 // No user-supplied arguments. Still need to pass in a pointer to the
4198 // block (to reference imported block decl refs).
4199 S += "(" + StructRef + " *__cself)";
4200 } else if (BD->param_empty()) {
4201 S += "(" + StructRef + " *__cself)";
4202 } else {
4203 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4204 assert(FT && "SynthesizeBlockFunc: No function proto");
4205 S += '(';
4206 // first add the implicit argument.
4207 S += StructRef + " *__cself, ";
4208 std::string ParamStr;
4209 for (BlockDecl::param_iterator AI = BD->param_begin(),
4210 E = BD->param_end(); AI != E; ++AI) {
4211 if (AI != BD->param_begin()) S += ", ";
4212 ParamStr = (*AI)->getNameAsString();
4213 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004214 (void)convertBlockPointerToFunctionPointer(QT);
4215 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004216 S += ParamStr;
4217 }
4218 if (FT->isVariadic()) {
4219 if (!BD->param_empty()) S += ", ";
4220 S += "...";
4221 }
4222 S += ')';
4223 }
4224 S += " {\n";
4225
4226 // Create local declarations to avoid rewriting all closure decl ref exprs.
4227 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004228 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004229 E = BlockByRefDecls.end(); I != E; ++I) {
4230 S += " ";
4231 std::string Name = (*I)->getNameAsString();
4232 std::string TypeString;
4233 RewriteByRefString(TypeString, Name, (*I));
4234 TypeString += " *";
4235 Name = TypeString + Name;
4236 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4237 }
4238 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004239 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004240 E = BlockByCopyDecls.end(); I != E; ++I) {
4241 S += " ";
4242 // Handle nested closure invocation. For example:
4243 //
4244 // void (^myImportedClosure)(void);
4245 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4246 //
4247 // void (^anotherClosure)(void);
4248 // anotherClosure = ^(void) {
4249 // myImportedClosure(); // import and invoke the closure
4250 // };
4251 //
4252 if (isTopLevelBlockPointerType((*I)->getType())) {
4253 RewriteBlockPointerTypeVariable(S, (*I));
4254 S += " = (";
4255 RewriteBlockPointerType(S, (*I)->getType());
4256 S += ")";
4257 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4258 }
4259 else {
4260 std::string Name = (*I)->getNameAsString();
4261 QualType QT = (*I)->getType();
4262 if (HasLocalVariableExternalStorage(*I))
4263 QT = Context->getPointerType(QT);
4264 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4265 S += Name + " = __cself->" +
4266 (*I)->getNameAsString() + "; // bound by copy\n";
4267 }
4268 }
4269 std::string RewrittenStr = RewrittenBlockExprs[CE];
4270 const char *cstr = RewrittenStr.c_str();
4271 while (*cstr++ != '{') ;
4272 S += cstr;
4273 S += "\n";
4274 return S;
4275}
4276
4277std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4278 StringRef funcName,
4279 std::string Tag) {
4280 std::string StructRef = "struct " + Tag;
4281 std::string S = "static void __";
4282
4283 S += funcName;
4284 S += "_block_copy_" + utostr(i);
4285 S += "(" + StructRef;
4286 S += "*dst, " + StructRef;
4287 S += "*src) {";
4288 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4289 E = ImportedBlockDecls.end(); I != E; ++I) {
4290 ValueDecl *VD = (*I);
4291 S += "_Block_object_assign((void*)&dst->";
4292 S += (*I)->getNameAsString();
4293 S += ", (void*)src->";
4294 S += (*I)->getNameAsString();
4295 if (BlockByRefDeclsPtrSet.count((*I)))
4296 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4297 else if (VD->getType()->isBlockPointerType())
4298 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4299 else
4300 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4301 }
4302 S += "}\n";
4303
4304 S += "\nstatic void __";
4305 S += funcName;
4306 S += "_block_dispose_" + utostr(i);
4307 S += "(" + StructRef;
4308 S += "*src) {";
4309 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4310 E = ImportedBlockDecls.end(); I != E; ++I) {
4311 ValueDecl *VD = (*I);
4312 S += "_Block_object_dispose((void*)src->";
4313 S += (*I)->getNameAsString();
4314 if (BlockByRefDeclsPtrSet.count((*I)))
4315 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4316 else if (VD->getType()->isBlockPointerType())
4317 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4318 else
4319 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4320 }
4321 S += "}\n";
4322 return S;
4323}
4324
4325std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4326 std::string Desc) {
4327 std::string S = "\nstruct " + Tag;
4328 std::string Constructor = " " + Tag;
4329
4330 S += " {\n struct __block_impl impl;\n";
4331 S += " struct " + Desc;
4332 S += "* Desc;\n";
4333
4334 Constructor += "(void *fp, "; // Invoke function pointer.
4335 Constructor += "struct " + Desc; // Descriptor pointer.
4336 Constructor += " *desc";
4337
4338 if (BlockDeclRefs.size()) {
4339 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004340 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004341 E = BlockByCopyDecls.end(); I != E; ++I) {
4342 S += " ";
4343 std::string FieldName = (*I)->getNameAsString();
4344 std::string ArgName = "_" + FieldName;
4345 // Handle nested closure invocation. For example:
4346 //
4347 // void (^myImportedBlock)(void);
4348 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4349 //
4350 // void (^anotherBlock)(void);
4351 // anotherBlock = ^(void) {
4352 // myImportedBlock(); // import and invoke the closure
4353 // };
4354 //
4355 if (isTopLevelBlockPointerType((*I)->getType())) {
4356 S += "struct __block_impl *";
4357 Constructor += ", void *" + ArgName;
4358 } else {
4359 QualType QT = (*I)->getType();
4360 if (HasLocalVariableExternalStorage(*I))
4361 QT = Context->getPointerType(QT);
4362 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4363 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4364 Constructor += ", " + ArgName;
4365 }
4366 S += FieldName + ";\n";
4367 }
4368 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004369 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004370 E = BlockByRefDecls.end(); I != E; ++I) {
4371 S += " ";
4372 std::string FieldName = (*I)->getNameAsString();
4373 std::string ArgName = "_" + FieldName;
4374 {
4375 std::string TypeString;
4376 RewriteByRefString(TypeString, FieldName, (*I));
4377 TypeString += " *";
4378 FieldName = TypeString + FieldName;
4379 ArgName = TypeString + ArgName;
4380 Constructor += ", " + ArgName;
4381 }
4382 S += FieldName + "; // by ref\n";
4383 }
4384 // Finish writing the constructor.
4385 Constructor += ", int flags=0)";
4386 // Initialize all "by copy" arguments.
4387 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004388 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004389 E = BlockByCopyDecls.end(); I != E; ++I) {
4390 std::string Name = (*I)->getNameAsString();
4391 if (firsTime) {
4392 Constructor += " : ";
4393 firsTime = false;
4394 }
4395 else
4396 Constructor += ", ";
4397 if (isTopLevelBlockPointerType((*I)->getType()))
4398 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4399 else
4400 Constructor += Name + "(_" + Name + ")";
4401 }
4402 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004403 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004404 E = BlockByRefDecls.end(); I != E; ++I) {
4405 std::string Name = (*I)->getNameAsString();
4406 if (firsTime) {
4407 Constructor += " : ";
4408 firsTime = false;
4409 }
4410 else
4411 Constructor += ", ";
4412 Constructor += Name + "(_" + Name + "->__forwarding)";
4413 }
4414
4415 Constructor += " {\n";
4416 if (GlobalVarDecl)
4417 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4418 else
4419 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4420 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4421
4422 Constructor += " Desc = desc;\n";
4423 } else {
4424 // Finish writing the constructor.
4425 Constructor += ", int flags=0) {\n";
4426 if (GlobalVarDecl)
4427 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4428 else
4429 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4430 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4431 Constructor += " Desc = desc;\n";
4432 }
4433 Constructor += " ";
4434 Constructor += "}\n";
4435 S += Constructor;
4436 S += "};\n";
4437 return S;
4438}
4439
4440std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4441 std::string ImplTag, int i,
4442 StringRef FunName,
4443 unsigned hasCopy) {
4444 std::string S = "\nstatic struct " + DescTag;
4445
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004446 S += " {\n size_t reserved;\n";
4447 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004448 if (hasCopy) {
4449 S += " void (*copy)(struct ";
4450 S += ImplTag; S += "*, struct ";
4451 S += ImplTag; S += "*);\n";
4452
4453 S += " void (*dispose)(struct ";
4454 S += ImplTag; S += "*);\n";
4455 }
4456 S += "} ";
4457
4458 S += DescTag + "_DATA = { 0, sizeof(struct ";
4459 S += ImplTag + ")";
4460 if (hasCopy) {
4461 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4462 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4463 }
4464 S += "};\n";
4465 return S;
4466}
4467
4468void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4469 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004470 bool RewriteSC = (GlobalVarDecl &&
4471 !Blocks.empty() &&
4472 GlobalVarDecl->getStorageClass() == SC_Static &&
4473 GlobalVarDecl->getType().getCVRQualifiers());
4474 if (RewriteSC) {
4475 std::string SC(" void __");
4476 SC += GlobalVarDecl->getNameAsString();
4477 SC += "() {}";
4478 InsertText(FunLocStart, SC);
4479 }
4480
4481 // Insert closures that were part of the function.
4482 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4483 CollectBlockDeclRefInfo(Blocks[i]);
4484 // Need to copy-in the inner copied-in variables not actually used in this
4485 // block.
4486 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004487 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004488 ValueDecl *VD = Exp->getDecl();
4489 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004490 if (!VD->hasAttr<BlocksAttr>()) {
4491 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4492 BlockByCopyDeclsPtrSet.insert(VD);
4493 BlockByCopyDecls.push_back(VD);
4494 }
4495 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004496 }
John McCall113bee02012-03-10 09:33:50 +00004497
4498 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004499 BlockByRefDeclsPtrSet.insert(VD);
4500 BlockByRefDecls.push_back(VD);
4501 }
John McCall113bee02012-03-10 09:33:50 +00004502
Fariborz Jahanian11671902012-02-07 17:11:38 +00004503 // imported objects in the inner blocks not used in the outer
4504 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004505 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004506 VD->getType()->isBlockPointerType())
4507 ImportedBlockDecls.insert(VD);
4508 }
4509
4510 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4511 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4512
4513 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4514
4515 InsertText(FunLocStart, CI);
4516
4517 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4518
4519 InsertText(FunLocStart, CF);
4520
4521 if (ImportedBlockDecls.size()) {
4522 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4523 InsertText(FunLocStart, HF);
4524 }
4525 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4526 ImportedBlockDecls.size() > 0);
4527 InsertText(FunLocStart, BD);
4528
4529 BlockDeclRefs.clear();
4530 BlockByRefDecls.clear();
4531 BlockByRefDeclsPtrSet.clear();
4532 BlockByCopyDecls.clear();
4533 BlockByCopyDeclsPtrSet.clear();
4534 ImportedBlockDecls.clear();
4535 }
4536 if (RewriteSC) {
4537 // Must insert any 'const/volatile/static here. Since it has been
4538 // removed as result of rewriting of block literals.
4539 std::string SC;
4540 if (GlobalVarDecl->getStorageClass() == SC_Static)
4541 SC = "static ";
4542 if (GlobalVarDecl->getType().isConstQualified())
4543 SC += "const ";
4544 if (GlobalVarDecl->getType().isVolatileQualified())
4545 SC += "volatile ";
4546 if (GlobalVarDecl->getType().isRestrictQualified())
4547 SC += "restrict ";
4548 InsertText(FunLocStart, SC);
4549 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004550 if (GlobalConstructionExp) {
4551 // extra fancy dance for global literal expression.
4552
4553 // Always the latest block expression on the block stack.
4554 std::string Tag = "__";
4555 Tag += FunName;
4556 Tag += "_block_impl_";
4557 Tag += utostr(Blocks.size()-1);
4558 std::string globalBuf = "static ";
4559 globalBuf += Tag; globalBuf += " ";
4560 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004561
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004562 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004563 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004564 PrintingPolicy(LangOpts));
4565 globalBuf += constructorExprBuf.str();
4566 globalBuf += ";\n";
4567 InsertText(FunLocStart, globalBuf);
4568 GlobalConstructionExp = 0;
4569 }
4570
Fariborz Jahanian11671902012-02-07 17:11:38 +00004571 Blocks.clear();
4572 InnerDeclRefsCount.clear();
4573 InnerDeclRefs.clear();
4574 RewrittenBlockExprs.clear();
4575}
4576
4577void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004578 SourceLocation FunLocStart =
4579 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4580 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004581 StringRef FuncName = FD->getName();
4582
4583 SynthesizeBlockLiterals(FunLocStart, FuncName);
4584}
4585
4586static void BuildUniqueMethodName(std::string &Name,
4587 ObjCMethodDecl *MD) {
4588 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4589 Name = IFace->getName();
4590 Name += "__" + MD->getSelector().getAsString();
4591 // Convert colons to underscores.
4592 std::string::size_type loc = 0;
4593 while ((loc = Name.find(":", loc)) != std::string::npos)
4594 Name.replace(loc, 1, "_");
4595}
4596
4597void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4598 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4599 //SourceLocation FunLocStart = MD->getLocStart();
4600 SourceLocation FunLocStart = MD->getLocStart();
4601 std::string FuncName;
4602 BuildUniqueMethodName(FuncName, MD);
4603 SynthesizeBlockLiterals(FunLocStart, FuncName);
4604}
4605
4606void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4607 for (Stmt::child_range CI = S->children(); CI; ++CI)
4608 if (*CI) {
4609 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4610 GetBlockDeclRefExprs(CBE->getBody());
4611 else
4612 GetBlockDeclRefExprs(*CI);
4613 }
4614 // Handle specific things.
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004615 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4616 if (DRE->refersToEnclosingLocal()) {
4617 // FIXME: Handle enums.
4618 if (!isa<FunctionDecl>(DRE->getDecl()))
4619 BlockDeclRefs.push_back(DRE);
4620 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4621 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004622 }
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004623 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004624
4625 return;
4626}
4627
Craig Topper5603df42013-07-05 19:34:19 +00004628void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4629 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004630 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4631 for (Stmt::child_range CI = S->children(); CI; ++CI)
4632 if (*CI) {
4633 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4634 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4635 GetInnerBlockDeclRefExprs(CBE->getBody(),
4636 InnerBlockDeclRefs,
4637 InnerContexts);
4638 }
4639 else
4640 GetInnerBlockDeclRefExprs(*CI,
4641 InnerBlockDeclRefs,
4642 InnerContexts);
4643
4644 }
4645 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004646 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4647 if (DRE->refersToEnclosingLocal()) {
4648 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4649 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4650 InnerBlockDeclRefs.push_back(DRE);
4651 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4652 if (Var->isFunctionOrMethodVarDecl())
4653 ImportedLocalExternalDecls.insert(Var);
4654 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004655 }
4656
4657 return;
4658}
4659
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004660/// convertObjCTypeToCStyleType - This routine converts such objc types
4661/// as qualified objects, and blocks to their closest c/c++ types that
4662/// it can. It returns true if input type was modified.
4663bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4664 QualType oldT = T;
4665 convertBlockPointerToFunctionPointer(T);
4666 if (T->isFunctionPointerType()) {
4667 QualType PointeeTy;
4668 if (const PointerType* PT = T->getAs<PointerType>()) {
4669 PointeeTy = PT->getPointeeType();
4670 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4671 T = convertFunctionTypeOfBlocks(FT);
4672 T = Context->getPointerType(T);
4673 }
4674 }
4675 }
4676
4677 convertToUnqualifiedObjCType(T);
4678 return T != oldT;
4679}
4680
Fariborz Jahanian11671902012-02-07 17:11:38 +00004681/// convertFunctionTypeOfBlocks - This routine converts a function type
4682/// whose result type may be a block pointer or whose argument type(s)
4683/// might be block pointers to an equivalent function type replacing
4684/// all block pointers to function pointers.
4685QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4686 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4687 // FTP will be null for closures that don't take arguments.
4688 // Generate a funky cast.
4689 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004690 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004691 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004692
4693 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004694 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4695 E = FTP->param_type_end();
4696 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004697 QualType t = *I;
4698 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004699 if (convertObjCTypeToCStyleType(t))
4700 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004701 ArgTypes.push_back(t);
4702 }
4703 }
4704 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004705 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004706 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004707 else FuncType = QualType(FT, 0);
4708 return FuncType;
4709}
4710
4711Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4712 // Navigate to relevant type information.
4713 const BlockPointerType *CPT = 0;
4714
4715 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4716 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004717 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4718 CPT = MExpr->getType()->getAs<BlockPointerType>();
4719 }
4720 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4721 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4722 }
4723 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4724 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4725 else if (const ConditionalOperator *CEXPR =
4726 dyn_cast<ConditionalOperator>(BlockExp)) {
4727 Expr *LHSExp = CEXPR->getLHS();
4728 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4729 Expr *RHSExp = CEXPR->getRHS();
4730 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4731 Expr *CONDExp = CEXPR->getCond();
4732 ConditionalOperator *CondExpr =
4733 new (Context) ConditionalOperator(CONDExp,
4734 SourceLocation(), cast<Expr>(LHSStmt),
4735 SourceLocation(), cast<Expr>(RHSStmt),
4736 Exp->getType(), VK_RValue, OK_Ordinary);
4737 return CondExpr;
4738 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4739 CPT = IRE->getType()->getAs<BlockPointerType>();
4740 } else if (const PseudoObjectExpr *POE
4741 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4742 CPT = POE->getType()->castAs<BlockPointerType>();
4743 } else {
4744 assert(1 && "RewriteBlockClass: Bad type");
4745 }
4746 assert(CPT && "RewriteBlockClass: Bad type");
4747 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4748 assert(FT && "RewriteBlockClass: Bad type");
4749 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4750 // FTP will be null for closures that don't take arguments.
4751
4752 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4753 SourceLocation(), SourceLocation(),
4754 &Context->Idents.get("__block_impl"));
4755 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4756
4757 // Generate a funky cast.
4758 SmallVector<QualType, 8> ArgTypes;
4759
4760 // Push the block argument type.
4761 ArgTypes.push_back(PtrBlock);
4762 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004763 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4764 E = FTP->param_type_end();
4765 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004766 QualType t = *I;
4767 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4768 if (!convertBlockPointerToFunctionPointer(t))
4769 convertToUnqualifiedObjCType(t);
4770 ArgTypes.push_back(t);
4771 }
4772 }
4773 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004774 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004775
4776 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4777
4778 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4779 CK_BitCast,
4780 const_cast<Expr*>(BlockExp));
4781 // Don't forget the parens to enforce the proper binding.
4782 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4783 BlkCast);
4784 //PE->dump();
4785
4786 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4787 SourceLocation(),
4788 &Context->Idents.get("FuncPtr"),
4789 Context->VoidPtrTy, 0,
4790 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004791 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004792 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4793 FD->getType(), VK_LValue,
4794 OK_Ordinary);
4795
4796
4797 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4798 CK_BitCast, ME);
4799 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4800
4801 SmallVector<Expr*, 8> BlkExprs;
4802 // Add the implicit argument.
4803 BlkExprs.push_back(BlkCast);
4804 // Add the user arguments.
4805 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4806 E = Exp->arg_end(); I != E; ++I) {
4807 BlkExprs.push_back(*I);
4808 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004809 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004810 Exp->getType(), VK_RValue,
4811 SourceLocation());
4812 return CE;
4813}
4814
4815// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004816// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004817// For example:
4818//
4819// int main() {
4820// __block Foo *f;
4821// __block int i;
4822//
4823// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004824// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004825// i = 77;
4826// };
4827//}
John McCall113bee02012-03-10 09:33:50 +00004828Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004829 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4830 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004831 ValueDecl *VD = DeclRefExp->getDecl();
4832 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004833
4834 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4835 SourceLocation(),
4836 &Context->Idents.get("__forwarding"),
4837 Context->VoidPtrTy, 0,
4838 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004839 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004840 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4841 FD, SourceLocation(),
4842 FD->getType(), VK_LValue,
4843 OK_Ordinary);
4844
4845 StringRef Name = VD->getName();
4846 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4847 &Context->Idents.get(Name),
4848 Context->VoidPtrTy, 0,
4849 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004850 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004851 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4852 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4853
4854
4855
4856 // Need parens to enforce precedence.
4857 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4858 DeclRefExp->getExprLoc(),
4859 ME);
4860 ReplaceStmt(DeclRefExp, PE);
4861 return PE;
4862}
4863
4864// Rewrites the imported local variable V with external storage
4865// (static, extern, etc.) as *V
4866//
4867Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4868 ValueDecl *VD = DRE->getDecl();
4869 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4870 if (!ImportedLocalExternalDecls.count(Var))
4871 return DRE;
4872 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4873 VK_LValue, OK_Ordinary,
4874 DRE->getLocation());
4875 // Need parens to enforce precedence.
4876 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4877 Exp);
4878 ReplaceStmt(DRE, PE);
4879 return PE;
4880}
4881
4882void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4883 SourceLocation LocStart = CE->getLParenLoc();
4884 SourceLocation LocEnd = CE->getRParenLoc();
4885
4886 // Need to avoid trying to rewrite synthesized casts.
4887 if (LocStart.isInvalid())
4888 return;
4889 // Need to avoid trying to rewrite casts contained in macros.
4890 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4891 return;
4892
4893 const char *startBuf = SM->getCharacterData(LocStart);
4894 const char *endBuf = SM->getCharacterData(LocEnd);
4895 QualType QT = CE->getType();
4896 const Type* TypePtr = QT->getAs<Type>();
4897 if (isa<TypeOfExprType>(TypePtr)) {
4898 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4899 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4900 std::string TypeAsString = "(";
4901 RewriteBlockPointerType(TypeAsString, QT);
4902 TypeAsString += ")";
4903 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4904 return;
4905 }
4906 // advance the location to startArgList.
4907 const char *argPtr = startBuf;
4908
4909 while (*argPtr++ && (argPtr < endBuf)) {
4910 switch (*argPtr) {
4911 case '^':
4912 // Replace the '^' with '*'.
4913 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4914 ReplaceText(LocStart, 1, "*");
4915 break;
4916 }
4917 }
4918 return;
4919}
4920
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004921void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4922 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004923 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4924 CastKind != CK_AnyPointerToBlockPointerCast)
4925 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004926
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004927 QualType QT = IC->getType();
4928 (void)convertBlockPointerToFunctionPointer(QT);
4929 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4930 std::string Str = "(";
4931 Str += TypeString;
4932 Str += ")";
4933 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4934
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004935 return;
4936}
4937
Fariborz Jahanian11671902012-02-07 17:11:38 +00004938void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4939 SourceLocation DeclLoc = FD->getLocation();
4940 unsigned parenCount = 0;
4941
4942 // We have 1 or more arguments that have closure pointers.
4943 const char *startBuf = SM->getCharacterData(DeclLoc);
4944 const char *startArgList = strchr(startBuf, '(');
4945
4946 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4947
4948 parenCount++;
4949 // advance the location to startArgList.
4950 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4951 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4952
4953 const char *argPtr = startArgList;
4954
4955 while (*argPtr++ && parenCount) {
4956 switch (*argPtr) {
4957 case '^':
4958 // Replace the '^' with '*'.
4959 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4960 ReplaceText(DeclLoc, 1, "*");
4961 break;
4962 case '(':
4963 parenCount++;
4964 break;
4965 case ')':
4966 parenCount--;
4967 break;
4968 }
4969 }
4970 return;
4971}
4972
4973bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4974 const FunctionProtoType *FTP;
4975 const PointerType *PT = QT->getAs<PointerType>();
4976 if (PT) {
4977 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4978 } else {
4979 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4980 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4981 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4982 }
4983 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004984 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4985 E = FTP->param_type_end();
4986 I != E; ++I)
Fariborz Jahanian11671902012-02-07 17:11:38 +00004987 if (isTopLevelBlockPointerType(*I))
4988 return true;
4989 }
4990 return false;
4991}
4992
4993bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4994 const FunctionProtoType *FTP;
4995 const PointerType *PT = QT->getAs<PointerType>();
4996 if (PT) {
4997 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4998 } else {
4999 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5000 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5001 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5002 }
5003 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005004 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
5005 E = FTP->param_type_end();
5006 I != E; ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005007 if ((*I)->isObjCQualifiedIdType())
5008 return true;
5009 if ((*I)->isObjCObjectPointerType() &&
5010 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5011 return true;
5012 }
5013
5014 }
5015 return false;
5016}
5017
5018void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5019 const char *&RParen) {
5020 const char *argPtr = strchr(Name, '(');
5021 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
5022
5023 LParen = argPtr; // output the start.
5024 argPtr++; // skip past the left paren.
5025 unsigned parenCount = 1;
5026
5027 while (*argPtr && parenCount) {
5028 switch (*argPtr) {
5029 case '(': parenCount++; break;
5030 case ')': parenCount--; break;
5031 default: break;
5032 }
5033 if (parenCount) argPtr++;
5034 }
5035 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5036 RParen = argPtr; // output the end
5037}
5038
5039void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5040 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5041 RewriteBlockPointerFunctionArgs(FD);
5042 return;
5043 }
5044 // Handle Variables and Typedefs.
5045 SourceLocation DeclLoc = ND->getLocation();
5046 QualType DeclT;
5047 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5048 DeclT = VD->getType();
5049 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5050 DeclT = TDD->getUnderlyingType();
5051 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5052 DeclT = FD->getType();
5053 else
5054 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5055
5056 const char *startBuf = SM->getCharacterData(DeclLoc);
5057 const char *endBuf = startBuf;
5058 // scan backward (from the decl location) for the end of the previous decl.
5059 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5060 startBuf--;
5061 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5062 std::string buf;
5063 unsigned OrigLength=0;
5064 // *startBuf != '^' if we are dealing with a pointer to function that
5065 // may take block argument types (which will be handled below).
5066 if (*startBuf == '^') {
5067 // Replace the '^' with '*', computing a negative offset.
5068 buf = '*';
5069 startBuf++;
5070 OrigLength++;
5071 }
5072 while (*startBuf != ')') {
5073 buf += *startBuf;
5074 startBuf++;
5075 OrigLength++;
5076 }
5077 buf += ')';
5078 OrigLength++;
5079
5080 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5081 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5082 // Replace the '^' with '*' for arguments.
5083 // Replace id<P> with id/*<>*/
5084 DeclLoc = ND->getLocation();
5085 startBuf = SM->getCharacterData(DeclLoc);
5086 const char *argListBegin, *argListEnd;
5087 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5088 while (argListBegin < argListEnd) {
5089 if (*argListBegin == '^')
5090 buf += '*';
5091 else if (*argListBegin == '<') {
5092 buf += "/*";
5093 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005094 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005095 while (*argListBegin != '>') {
5096 buf += *argListBegin++;
5097 OrigLength++;
5098 }
5099 buf += *argListBegin;
5100 buf += "*/";
5101 }
5102 else
5103 buf += *argListBegin;
5104 argListBegin++;
5105 OrigLength++;
5106 }
5107 buf += ')';
5108 OrigLength++;
5109 }
5110 ReplaceText(Start, OrigLength, buf);
5111
5112 return;
5113}
5114
5115
5116/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5117/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5118/// struct Block_byref_id_object *src) {
5119/// _Block_object_assign (&_dest->object, _src->object,
5120/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5121/// [|BLOCK_FIELD_IS_WEAK]) // object
5122/// _Block_object_assign(&_dest->object, _src->object,
5123/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5124/// [|BLOCK_FIELD_IS_WEAK]) // block
5125/// }
5126/// And:
5127/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5128/// _Block_object_dispose(_src->object,
5129/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5130/// [|BLOCK_FIELD_IS_WEAK]) // object
5131/// _Block_object_dispose(_src->object,
5132/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5133/// [|BLOCK_FIELD_IS_WEAK]) // block
5134/// }
5135
5136std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5137 int flag) {
5138 std::string S;
5139 if (CopyDestroyCache.count(flag))
5140 return S;
5141 CopyDestroyCache.insert(flag);
5142 S = "static void __Block_byref_id_object_copy_";
5143 S += utostr(flag);
5144 S += "(void *dst, void *src) {\n";
5145
5146 // offset into the object pointer is computed as:
5147 // void * + void* + int + int + void* + void *
5148 unsigned IntSize =
5149 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5150 unsigned VoidPtrSize =
5151 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5152
5153 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5154 S += " _Block_object_assign((char*)dst + ";
5155 S += utostr(offset);
5156 S += ", *(void * *) ((char*)src + ";
5157 S += utostr(offset);
5158 S += "), ";
5159 S += utostr(flag);
5160 S += ");\n}\n";
5161
5162 S += "static void __Block_byref_id_object_dispose_";
5163 S += utostr(flag);
5164 S += "(void *src) {\n";
5165 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5166 S += utostr(offset);
5167 S += "), ";
5168 S += utostr(flag);
5169 S += ");\n}\n";
5170 return S;
5171}
5172
5173/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5174/// the declaration into:
5175/// struct __Block_byref_ND {
5176/// void *__isa; // NULL for everything except __weak pointers
5177/// struct __Block_byref_ND *__forwarding;
5178/// int32_t __flags;
5179/// int32_t __size;
5180/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5181/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5182/// typex ND;
5183/// };
5184///
5185/// It then replaces declaration of ND variable with:
5186/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5187/// __size=sizeof(struct __Block_byref_ND),
5188/// ND=initializer-if-any};
5189///
5190///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005191void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5192 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005193 int flag = 0;
5194 int isa = 0;
5195 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5196 if (DeclLoc.isInvalid())
5197 // If type location is missing, it is because of missing type (a warning).
5198 // Use variable's location which is good for this case.
5199 DeclLoc = ND->getLocation();
5200 const char *startBuf = SM->getCharacterData(DeclLoc);
5201 SourceLocation X = ND->getLocEnd();
5202 X = SM->getExpansionLoc(X);
5203 const char *endBuf = SM->getCharacterData(X);
5204 std::string Name(ND->getNameAsString());
5205 std::string ByrefType;
5206 RewriteByRefString(ByrefType, Name, ND, true);
5207 ByrefType += " {\n";
5208 ByrefType += " void *__isa;\n";
5209 RewriteByRefString(ByrefType, Name, ND);
5210 ByrefType += " *__forwarding;\n";
5211 ByrefType += " int __flags;\n";
5212 ByrefType += " int __size;\n";
5213 // Add void *__Block_byref_id_object_copy;
5214 // void *__Block_byref_id_object_dispose; if needed.
5215 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005216 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005217 if (HasCopyAndDispose) {
5218 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5219 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5220 }
5221
5222 QualType T = Ty;
5223 (void)convertBlockPointerToFunctionPointer(T);
5224 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5225
5226 ByrefType += " " + Name + ";\n";
5227 ByrefType += "};\n";
5228 // Insert this type in global scope. It is needed by helper function.
5229 SourceLocation FunLocStart;
5230 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005231 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005232 else {
5233 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5234 FunLocStart = CurMethodDef->getLocStart();
5235 }
5236 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005237
Fariborz Jahanian11671902012-02-07 17:11:38 +00005238 if (Ty.isObjCGCWeak()) {
5239 flag |= BLOCK_FIELD_IS_WEAK;
5240 isa = 1;
5241 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005242 if (HasCopyAndDispose) {
5243 flag = BLOCK_BYREF_CALLER;
5244 QualType Ty = ND->getType();
5245 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5246 if (Ty->isBlockPointerType())
5247 flag |= BLOCK_FIELD_IS_BLOCK;
5248 else
5249 flag |= BLOCK_FIELD_IS_OBJECT;
5250 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5251 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005252 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005253 }
5254
5255 // struct __Block_byref_ND ND =
5256 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5257 // initializer-if-any};
5258 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005259 // FIXME. rewriter does not support __block c++ objects which
5260 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005261 if (hasInit)
5262 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5263 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5264 if (CXXDecl && CXXDecl->isDefaultConstructor())
5265 hasInit = false;
5266 }
5267
Fariborz Jahanian11671902012-02-07 17:11:38 +00005268 unsigned flags = 0;
5269 if (HasCopyAndDispose)
5270 flags |= BLOCK_HAS_COPY_DISPOSE;
5271 Name = ND->getNameAsString();
5272 ByrefType.clear();
5273 RewriteByRefString(ByrefType, Name, ND);
5274 std::string ForwardingCastType("(");
5275 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005276 ByrefType += " " + Name + " = {(void*)";
5277 ByrefType += utostr(isa);
5278 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5279 ByrefType += utostr(flags);
5280 ByrefType += ", ";
5281 ByrefType += "sizeof(";
5282 RewriteByRefString(ByrefType, Name, ND);
5283 ByrefType += ")";
5284 if (HasCopyAndDispose) {
5285 ByrefType += ", __Block_byref_id_object_copy_";
5286 ByrefType += utostr(flag);
5287 ByrefType += ", __Block_byref_id_object_dispose_";
5288 ByrefType += utostr(flag);
5289 }
5290
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005291 if (!firstDecl) {
5292 // In multiple __block declarations, and for all but 1st declaration,
5293 // find location of the separating comma. This would be start location
5294 // where new text is to be inserted.
5295 DeclLoc = ND->getLocation();
5296 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5297 const char *commaBuf = startDeclBuf;
5298 while (*commaBuf != ',')
5299 commaBuf--;
5300 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5301 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5302 startBuf = commaBuf;
5303 }
5304
Fariborz Jahanian11671902012-02-07 17:11:38 +00005305 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005306 ByrefType += "};\n";
5307 unsigned nameSize = Name.size();
5308 // for block or function pointer declaration. Name is aleady
5309 // part of the declaration.
5310 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5311 nameSize = 1;
5312 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5313 }
5314 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005315 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005316 SourceLocation startLoc;
5317 Expr *E = ND->getInit();
5318 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5319 startLoc = ECE->getLParenLoc();
5320 else
5321 startLoc = E->getLocStart();
5322 startLoc = SM->getExpansionLoc(startLoc);
5323 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005324 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005325
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005326 const char separator = lastDecl ? ';' : ',';
5327 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5328 const char *separatorBuf = strchr(startInitializerBuf, separator);
5329 assert((*separatorBuf == separator) &&
5330 "RewriteByRefVar: can't find ';' or ','");
5331 SourceLocation separatorLoc =
5332 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5333
5334 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005335 }
5336 return;
5337}
5338
5339void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5340 // Add initializers for any closure decl refs.
5341 GetBlockDeclRefExprs(Exp->getBody());
5342 if (BlockDeclRefs.size()) {
5343 // Unique all "by copy" declarations.
5344 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005345 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005346 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5347 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5348 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5349 }
5350 }
5351 // Unique all "by ref" declarations.
5352 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005353 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005354 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5355 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5356 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5357 }
5358 }
5359 // Find any imported blocks...they will need special attention.
5360 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005361 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005362 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5363 BlockDeclRefs[i]->getType()->isBlockPointerType())
5364 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5365 }
5366}
5367
5368FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5369 IdentifierInfo *ID = &Context->Idents.get(name);
5370 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5371 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5372 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005373 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005374}
5375
5376Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005377 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005378
Fariborz Jahanian11671902012-02-07 17:11:38 +00005379 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005380
Fariborz Jahanian11671902012-02-07 17:11:38 +00005381 Blocks.push_back(Exp);
5382
5383 CollectBlockDeclRefInfo(Exp);
5384
5385 // Add inner imported variables now used in current block.
5386 int countOfInnerDecls = 0;
5387 if (!InnerBlockDeclRefs.empty()) {
5388 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005389 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005390 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005391 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005392 // We need to save the copied-in variables in nested
5393 // blocks because it is needed at the end for some of the API generations.
5394 // See SynthesizeBlockLiterals routine.
5395 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5396 BlockDeclRefs.push_back(Exp);
5397 BlockByCopyDeclsPtrSet.insert(VD);
5398 BlockByCopyDecls.push_back(VD);
5399 }
John McCall113bee02012-03-10 09:33:50 +00005400 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005401 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5402 BlockDeclRefs.push_back(Exp);
5403 BlockByRefDeclsPtrSet.insert(VD);
5404 BlockByRefDecls.push_back(VD);
5405 }
5406 }
5407 // Find any imported blocks...they will need special attention.
5408 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005409 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005410 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5411 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5412 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5413 }
5414 InnerDeclRefsCount.push_back(countOfInnerDecls);
5415
5416 std::string FuncName;
5417
5418 if (CurFunctionDef)
5419 FuncName = CurFunctionDef->getNameAsString();
5420 else if (CurMethodDef)
5421 BuildUniqueMethodName(FuncName, CurMethodDef);
5422 else if (GlobalVarDecl)
5423 FuncName = std::string(GlobalVarDecl->getNameAsString());
5424
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005425 bool GlobalBlockExpr =
5426 block->getDeclContext()->getRedeclContext()->isFileContext();
5427
5428 if (GlobalBlockExpr && !GlobalVarDecl) {
5429 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5430 GlobalBlockExpr = false;
5431 }
5432
Fariborz Jahanian11671902012-02-07 17:11:38 +00005433 std::string BlockNumber = utostr(Blocks.size()-1);
5434
Fariborz Jahanian11671902012-02-07 17:11:38 +00005435 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5436
5437 // Get a pointer to the function type so we can cast appropriately.
5438 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5439 QualType FType = Context->getPointerType(BFT);
5440
5441 FunctionDecl *FD;
5442 Expr *NewRep;
5443
Benjamin Kramer60509af2013-09-09 14:48:42 +00005444 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005445 std::string Tag;
5446
5447 if (GlobalBlockExpr)
5448 Tag = "__global_";
5449 else
5450 Tag = "__";
5451 Tag += FuncName + "_block_impl_" + BlockNumber;
5452
Fariborz Jahanian11671902012-02-07 17:11:38 +00005453 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005454 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005455 SourceLocation());
5456
5457 SmallVector<Expr*, 4> InitExprs;
5458
5459 // Initialize the block function.
5460 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005461 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5462 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005463 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5464 CK_BitCast, Arg);
5465 InitExprs.push_back(castExpr);
5466
5467 // Initialize the block descriptor.
5468 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5469
5470 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5471 SourceLocation(), SourceLocation(),
5472 &Context->Idents.get(DescData.c_str()),
5473 Context->VoidPtrTy, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005474 SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005475 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005476 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005477 Context->VoidPtrTy,
5478 VK_LValue,
5479 SourceLocation()),
5480 UO_AddrOf,
5481 Context->getPointerType(Context->VoidPtrTy),
5482 VK_RValue, OK_Ordinary,
5483 SourceLocation());
5484 InitExprs.push_back(DescRefExpr);
5485
5486 // Add initializers for any closure decl refs.
5487 if (BlockDeclRefs.size()) {
5488 Expr *Exp;
5489 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005490 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005491 E = BlockByCopyDecls.end(); I != E; ++I) {
5492 if (isObjCType((*I)->getType())) {
5493 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5494 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005495 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5496 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005497 if (HasLocalVariableExternalStorage(*I)) {
5498 QualType QT = (*I)->getType();
5499 QT = Context->getPointerType(QT);
5500 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5501 OK_Ordinary, SourceLocation());
5502 }
5503 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5504 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005505 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5506 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005507 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5508 CK_BitCast, Arg);
5509 } else {
5510 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005511 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5512 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005513 if (HasLocalVariableExternalStorage(*I)) {
5514 QualType QT = (*I)->getType();
5515 QT = Context->getPointerType(QT);
5516 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5517 OK_Ordinary, SourceLocation());
5518 }
5519
5520 }
5521 InitExprs.push_back(Exp);
5522 }
5523 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005524 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005525 E = BlockByRefDecls.end(); I != E; ++I) {
5526 ValueDecl *ND = (*I);
5527 std::string Name(ND->getNameAsString());
5528 std::string RecName;
5529 RewriteByRefString(RecName, Name, ND, true);
5530 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5531 + sizeof("struct"));
5532 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5533 SourceLocation(), SourceLocation(),
5534 II);
5535 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5536 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5537
5538 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005539 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005540 SourceLocation());
5541 bool isNestedCapturedVar = false;
5542 if (block)
5543 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5544 ce = block->capture_end(); ci != ce; ++ci) {
5545 const VarDecl *variable = ci->getVariable();
5546 if (variable == ND && ci->isNested()) {
5547 assert (ci->isByRef() &&
5548 "SynthBlockInitExpr - captured block variable is not byref");
5549 isNestedCapturedVar = true;
5550 break;
5551 }
5552 }
5553 // captured nested byref variable has its address passed. Do not take
5554 // its address again.
5555 if (!isNestedCapturedVar)
5556 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5557 Context->getPointerType(Exp->getType()),
5558 VK_RValue, OK_Ordinary, SourceLocation());
5559 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5560 InitExprs.push_back(Exp);
5561 }
5562 }
5563 if (ImportedBlockDecls.size()) {
5564 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5565 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5566 unsigned IntSize =
5567 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5568 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5569 Context->IntTy, SourceLocation());
5570 InitExprs.push_back(FlagExp);
5571 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005572 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005573 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005574
5575 if (GlobalBlockExpr) {
5576 assert (GlobalConstructionExp == 0 &&
5577 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5578 GlobalConstructionExp = NewRep;
5579 NewRep = DRE;
5580 }
5581
Fariborz Jahanian11671902012-02-07 17:11:38 +00005582 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5583 Context->getPointerType(NewRep->getType()),
5584 VK_RValue, OK_Ordinary, SourceLocation());
5585 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5586 NewRep);
5587 BlockDeclRefs.clear();
5588 BlockByRefDecls.clear();
5589 BlockByRefDeclsPtrSet.clear();
5590 BlockByCopyDecls.clear();
5591 BlockByCopyDeclsPtrSet.clear();
5592 ImportedBlockDecls.clear();
5593 return NewRep;
5594}
5595
5596bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5597 if (const ObjCForCollectionStmt * CS =
5598 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5599 return CS->getElement() == DS;
5600 return false;
5601}
5602
5603//===----------------------------------------------------------------------===//
5604// Function Body / Expression rewriting
5605//===----------------------------------------------------------------------===//
5606
5607Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5608 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5609 isa<DoStmt>(S) || isa<ForStmt>(S))
5610 Stmts.push_back(S);
5611 else if (isa<ObjCForCollectionStmt>(S)) {
5612 Stmts.push_back(S);
5613 ObjCBcLabelNo.push_back(++BcLabelCount);
5614 }
5615
5616 // Pseudo-object operations and ivar references need special
5617 // treatment because we're going to recursively rewrite them.
5618 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5619 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5620 return RewritePropertyOrImplicitSetter(PseudoOp);
5621 } else {
5622 return RewritePropertyOrImplicitGetter(PseudoOp);
5623 }
5624 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5625 return RewriteObjCIvarRefExpr(IvarRefExpr);
5626 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005627 else if (isa<OpaqueValueExpr>(S))
5628 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005629
5630 SourceRange OrigStmtRange = S->getSourceRange();
5631
5632 // Perform a bottom up rewrite of all children.
5633 for (Stmt::child_range CI = S->children(); CI; ++CI)
5634 if (*CI) {
5635 Stmt *childStmt = (*CI);
5636 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5637 if (newStmt) {
5638 *CI = newStmt;
5639 }
5640 }
5641
5642 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005643 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005644 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5645 InnerContexts.insert(BE->getBlockDecl());
5646 ImportedLocalExternalDecls.clear();
5647 GetInnerBlockDeclRefExprs(BE->getBody(),
5648 InnerBlockDeclRefs, InnerContexts);
5649 // Rewrite the block body in place.
5650 Stmt *SaveCurrentBody = CurrentBody;
5651 CurrentBody = BE->getBody();
5652 PropParentMap = 0;
5653 // block literal on rhs of a property-dot-sytax assignment
5654 // must be replaced by its synthesize ast so getRewrittenText
5655 // works as expected. In this case, what actually ends up on RHS
5656 // is the blockTranscribed which is the helper function for the
5657 // block literal; as in: self.c = ^() {[ace ARR];};
5658 bool saveDisableReplaceStmt = DisableReplaceStmt;
5659 DisableReplaceStmt = false;
5660 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5661 DisableReplaceStmt = saveDisableReplaceStmt;
5662 CurrentBody = SaveCurrentBody;
5663 PropParentMap = 0;
5664 ImportedLocalExternalDecls.clear();
5665 // Now we snarf the rewritten text and stash it away for later use.
5666 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5667 RewrittenBlockExprs[BE] = Str;
5668
5669 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5670
5671 //blockTranscribed->dump();
5672 ReplaceStmt(S, blockTranscribed);
5673 return blockTranscribed;
5674 }
5675 // Handle specific things.
5676 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5677 return RewriteAtEncode(AtEncode);
5678
5679 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5680 return RewriteAtSelector(AtSelector);
5681
5682 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5683 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005684
5685 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5686 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005687
Patrick Beard0caa3942012-04-19 00:25:12 +00005688 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5689 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005690
5691 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5692 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005693
5694 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5695 dyn_cast<ObjCDictionaryLiteral>(S))
5696 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005697
5698 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5699#if 0
5700 // Before we rewrite it, put the original message expression in a comment.
5701 SourceLocation startLoc = MessExpr->getLocStart();
5702 SourceLocation endLoc = MessExpr->getLocEnd();
5703
5704 const char *startBuf = SM->getCharacterData(startLoc);
5705 const char *endBuf = SM->getCharacterData(endLoc);
5706
5707 std::string messString;
5708 messString += "// ";
5709 messString.append(startBuf, endBuf-startBuf+1);
5710 messString += "\n";
5711
5712 // FIXME: Missing definition of
5713 // InsertText(clang::SourceLocation, char const*, unsigned int).
5714 // InsertText(startLoc, messString.c_str(), messString.size());
5715 // Tried this, but it didn't work either...
5716 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5717#endif
5718 return RewriteMessageExpr(MessExpr);
5719 }
5720
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005721 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5722 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5723 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5724 }
5725
Fariborz Jahanian11671902012-02-07 17:11:38 +00005726 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5727 return RewriteObjCTryStmt(StmtTry);
5728
5729 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5730 return RewriteObjCSynchronizedStmt(StmtTry);
5731
5732 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5733 return RewriteObjCThrowStmt(StmtThrow);
5734
5735 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5736 return RewriteObjCProtocolExpr(ProtocolExp);
5737
5738 if (ObjCForCollectionStmt *StmtForCollection =
5739 dyn_cast<ObjCForCollectionStmt>(S))
5740 return RewriteObjCForCollectionStmt(StmtForCollection,
5741 OrigStmtRange.getEnd());
5742 if (BreakStmt *StmtBreakStmt =
5743 dyn_cast<BreakStmt>(S))
5744 return RewriteBreakStmt(StmtBreakStmt);
5745 if (ContinueStmt *StmtContinueStmt =
5746 dyn_cast<ContinueStmt>(S))
5747 return RewriteContinueStmt(StmtContinueStmt);
5748
5749 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5750 // and cast exprs.
5751 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5752 // FIXME: What we're doing here is modifying the type-specifier that
5753 // precedes the first Decl. In the future the DeclGroup should have
5754 // a separate type-specifier that we can rewrite.
5755 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5756 // the context of an ObjCForCollectionStmt. For example:
5757 // NSArray *someArray;
5758 // for (id <FooProtocol> index in someArray) ;
5759 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5760 // and it depends on the original text locations/positions.
5761 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5762 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5763
5764 // Blocks rewrite rules.
5765 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5766 DI != DE; ++DI) {
5767 Decl *SD = *DI;
5768 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5769 if (isTopLevelBlockPointerType(ND->getType()))
5770 RewriteBlockPointerDecl(ND);
5771 else if (ND->getType()->isFunctionPointerType())
5772 CheckFunctionPointerDecl(ND->getType(), ND);
5773 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5774 if (VD->hasAttr<BlocksAttr>()) {
5775 static unsigned uniqueByrefDeclCount = 0;
5776 assert(!BlockByRefDeclNo.count(ND) &&
5777 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5778 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005779 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005780 }
5781 else
5782 RewriteTypeOfDecl(VD);
5783 }
5784 }
5785 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5786 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5787 RewriteBlockPointerDecl(TD);
5788 else if (TD->getUnderlyingType()->isFunctionPointerType())
5789 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5790 }
5791 }
5792 }
5793
5794 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5795 RewriteObjCQualifiedInterfaceTypes(CE);
5796
5797 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5798 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5799 assert(!Stmts.empty() && "Statement stack is empty");
5800 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5801 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5802 && "Statement stack mismatch");
5803 Stmts.pop_back();
5804 }
5805 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005806 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5807 ValueDecl *VD = DRE->getDecl();
5808 if (VD->hasAttr<BlocksAttr>())
5809 return RewriteBlockDeclRefExpr(DRE);
5810 if (HasLocalVariableExternalStorage(VD))
5811 return RewriteLocalVariableExternalStorage(DRE);
5812 }
5813
5814 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5815 if (CE->getCallee()->getType()->isBlockPointerType()) {
5816 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5817 ReplaceStmt(S, BlockCall);
5818 return BlockCall;
5819 }
5820 }
5821 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5822 RewriteCastExpr(CE);
5823 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005824 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5825 RewriteImplicitCastObjCExpr(ICE);
5826 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005827#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005828
Fariborz Jahanian11671902012-02-07 17:11:38 +00005829 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5830 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5831 ICE->getSubExpr(),
5832 SourceLocation());
5833 // Get the new text.
5834 std::string SStr;
5835 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005836 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005837 const std::string &Str = Buf.str();
5838
5839 printf("CAST = %s\n", &Str[0]);
5840 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5841 delete S;
5842 return Replacement;
5843 }
5844#endif
5845 // Return this stmt unmodified.
5846 return S;
5847}
5848
5849void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5850 for (RecordDecl::field_iterator i = RD->field_begin(),
5851 e = RD->field_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00005852 FieldDecl *FD = *i;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005853 if (isTopLevelBlockPointerType(FD->getType()))
5854 RewriteBlockPointerDecl(FD);
5855 if (FD->getType()->isObjCQualifiedIdType() ||
5856 FD->getType()->isObjCQualifiedInterfaceType())
5857 RewriteObjCQualifiedInterfaceTypes(FD);
5858 }
5859}
5860
5861/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5862/// main file of the input.
5863void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5864 switch (D->getKind()) {
5865 case Decl::Function: {
5866 FunctionDecl *FD = cast<FunctionDecl>(D);
5867 if (FD->isOverloadedOperator())
5868 return;
5869
5870 // Since function prototypes don't have ParmDecl's, we check the function
5871 // prototype. This enables us to rewrite function declarations and
5872 // definitions using the same code.
5873 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5874
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005875 if (!FD->isThisDeclarationADefinition())
5876 break;
5877
Fariborz Jahanian11671902012-02-07 17:11:38 +00005878 // FIXME: If this should support Obj-C++, support CXXTryStmt
5879 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5880 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005881 CurrentBody = Body;
5882 Body =
5883 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5884 FD->setBody(Body);
5885 CurrentBody = 0;
5886 if (PropParentMap) {
5887 delete PropParentMap;
5888 PropParentMap = 0;
5889 }
5890 // This synthesizes and inserts the block "impl" struct, invoke function,
5891 // and any copy/dispose helper functions.
5892 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005893 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005894 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005895 }
5896 break;
5897 }
5898 case Decl::ObjCMethod: {
5899 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5900 if (CompoundStmt *Body = MD->getCompoundBody()) {
5901 CurMethodDef = MD;
5902 CurrentBody = Body;
5903 Body =
5904 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5905 MD->setBody(Body);
5906 CurrentBody = 0;
5907 if (PropParentMap) {
5908 delete PropParentMap;
5909 PropParentMap = 0;
5910 }
5911 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005912 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005913 CurMethodDef = 0;
5914 }
5915 break;
5916 }
5917 case Decl::ObjCImplementation: {
5918 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5919 ClassImplementation.push_back(CI);
5920 break;
5921 }
5922 case Decl::ObjCCategoryImpl: {
5923 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5924 CategoryImplementation.push_back(CI);
5925 break;
5926 }
5927 case Decl::Var: {
5928 VarDecl *VD = cast<VarDecl>(D);
5929 RewriteObjCQualifiedInterfaceTypes(VD);
5930 if (isTopLevelBlockPointerType(VD->getType()))
5931 RewriteBlockPointerDecl(VD);
5932 else if (VD->getType()->isFunctionPointerType()) {
5933 CheckFunctionPointerDecl(VD->getType(), VD);
5934 if (VD->getInit()) {
5935 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5936 RewriteCastExpr(CE);
5937 }
5938 }
5939 } else if (VD->getType()->isRecordType()) {
5940 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5941 if (RD->isCompleteDefinition())
5942 RewriteRecordBody(RD);
5943 }
5944 if (VD->getInit()) {
5945 GlobalVarDecl = VD;
5946 CurrentBody = VD->getInit();
5947 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5948 CurrentBody = 0;
5949 if (PropParentMap) {
5950 delete PropParentMap;
5951 PropParentMap = 0;
5952 }
5953 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5954 GlobalVarDecl = 0;
5955
5956 // This is needed for blocks.
5957 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5958 RewriteCastExpr(CE);
5959 }
5960 }
5961 break;
5962 }
5963 case Decl::TypeAlias:
5964 case Decl::Typedef: {
5965 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5966 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5967 RewriteBlockPointerDecl(TD);
5968 else if (TD->getUnderlyingType()->isFunctionPointerType())
5969 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005970 else
5971 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005972 }
5973 break;
5974 }
5975 case Decl::CXXRecord:
5976 case Decl::Record: {
5977 RecordDecl *RD = cast<RecordDecl>(D);
5978 if (RD->isCompleteDefinition())
5979 RewriteRecordBody(RD);
5980 break;
5981 }
5982 default:
5983 break;
5984 }
5985 // Nothing yet.
5986}
5987
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005988/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5989/// protocol reference symbols in the for of:
5990/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5991static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5992 ObjCProtocolDecl *PDecl,
5993 std::string &Result) {
5994 // Also output .objc_protorefs$B section and its meta-data.
5995 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005996 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005997 Result += "struct _protocol_t *";
5998 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5999 Result += PDecl->getNameAsString();
6000 Result += " = &";
6001 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6002 Result += ";\n";
6003}
6004
Fariborz Jahanian11671902012-02-07 17:11:38 +00006005void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
6006 if (Diags.hasErrorOccurred())
6007 return;
6008
6009 RewriteInclude();
6010
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006011 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006012 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006013 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006014 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006015 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
6016 HandleTopLevelSingleDecl(FDecl);
6017 }
6018
Fariborz Jahanian11671902012-02-07 17:11:38 +00006019 // Here's a great place to add any extra declarations that may be needed.
6020 // Write out meta data for each @protocol(<expr>).
6021 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006022 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006023 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006024 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
6025 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006026
6027 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00006028
6029 if (ClassImplementation.size() || CategoryImplementation.size())
6030 RewriteImplementations();
6031
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00006032 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6033 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6034 // Write struct declaration for the class matching its ivar declarations.
6035 // Note that for modern abi, this is postponed until the end of TU
6036 // because class extensions and the implementation might declare their own
6037 // private ivars.
6038 RewriteInterfaceDecl(CDecl);
6039 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006040
Fariborz Jahanian11671902012-02-07 17:11:38 +00006041 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6042 // we are done.
6043 if (const RewriteBuffer *RewriteBuf =
6044 Rewrite.getRewriteBufferFor(MainFileID)) {
6045 //printf("Changed:\n");
6046 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6047 } else {
6048 llvm::errs() << "No changes\n";
6049 }
6050
6051 if (ClassImplementation.size() || CategoryImplementation.size() ||
6052 ProtocolExprDecls.size()) {
6053 // Rewrite Objective-c meta data*
6054 std::string ResultStr;
6055 RewriteMetaDataIntoBuffer(ResultStr);
6056 // Emit metadata.
6057 *OutFile << ResultStr;
6058 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006059 // Emit ImageInfo;
6060 {
6061 std::string ResultStr;
6062 WriteImageInfo(ResultStr);
6063 *OutFile << ResultStr;
6064 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006065 OutFile->flush();
6066}
6067
6068void RewriteModernObjC::Initialize(ASTContext &context) {
6069 InitializeCommon(context);
6070
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00006071 Preamble += "#ifndef __OBJC2__\n";
6072 Preamble += "#define __OBJC2__\n";
6073 Preamble += "#endif\n";
6074
Fariborz Jahanian11671902012-02-07 17:11:38 +00006075 // declaring objc_selector outside the parameter list removes a silly
6076 // scope related warning...
6077 if (IsHeader)
6078 Preamble = "#pragma once\n";
6079 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00006080 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6081 Preamble += "\n\tstruct objc_object *superClass; ";
6082 // Add a constructor for creating temporary objects.
6083 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6084 Preamble += ": object(o), superClass(s) {} ";
6085 Preamble += "\n};\n";
6086
Fariborz Jahanian11671902012-02-07 17:11:38 +00006087 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006088 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006089 // These are currently generated.
6090 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006091 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006092 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006093 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6094 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006095 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006096 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006097 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6098 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006099 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006100
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006101 // These need be generated for performance. Currently they are not,
6102 // using API calls instead.
6103 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6104 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6105 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6106
Fariborz Jahanian11671902012-02-07 17:11:38 +00006107 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006108 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6109 Preamble += "typedef struct objc_object Protocol;\n";
6110 Preamble += "#define _REWRITER_typedef_Protocol\n";
6111 Preamble += "#endif\n";
6112 if (LangOpts.MicrosoftExt) {
6113 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6114 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006115 }
6116 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006117 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006118
6119 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6120 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6121 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6122 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6123 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6124
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006125 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006126 Preamble += "(const char *);\n";
6127 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6128 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006129 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006130 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00006131 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006132 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00006133 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6134 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006135 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00006136 Preamble += "#ifdef _WIN64\n";
6137 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6138 Preamble += "#else\n";
6139 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6140 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006141 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6142 Preamble += "struct __objcFastEnumerationState {\n\t";
6143 Preamble += "unsigned long state;\n\t";
6144 Preamble += "void **itemsPtr;\n\t";
6145 Preamble += "unsigned long *mutationsPtr;\n\t";
6146 Preamble += "unsigned long extra[5];\n};\n";
6147 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6148 Preamble += "#define __FASTENUMERATIONSTATE\n";
6149 Preamble += "#endif\n";
6150 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6151 Preamble += "struct __NSConstantStringImpl {\n";
6152 Preamble += " int *isa;\n";
6153 Preamble += " int flags;\n";
6154 Preamble += " char *str;\n";
6155 Preamble += " long length;\n";
6156 Preamble += "};\n";
6157 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6158 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6159 Preamble += "#else\n";
6160 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6161 Preamble += "#endif\n";
6162 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6163 Preamble += "#endif\n";
6164 // Blocks preamble.
6165 Preamble += "#ifndef BLOCK_IMPL\n";
6166 Preamble += "#define BLOCK_IMPL\n";
6167 Preamble += "struct __block_impl {\n";
6168 Preamble += " void *isa;\n";
6169 Preamble += " int Flags;\n";
6170 Preamble += " int Reserved;\n";
6171 Preamble += " void *FuncPtr;\n";
6172 Preamble += "};\n";
6173 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6174 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6175 Preamble += "extern \"C\" __declspec(dllexport) "
6176 "void _Block_object_assign(void *, const void *, const int);\n";
6177 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6178 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6179 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6180 Preamble += "#else\n";
6181 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6182 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6183 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6184 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6185 Preamble += "#endif\n";
6186 Preamble += "#endif\n";
6187 if (LangOpts.MicrosoftExt) {
6188 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6189 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6190 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6191 Preamble += "#define __attribute__(X)\n";
6192 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006193 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006194 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006195 Preamble += "#endif\n";
6196 Preamble += "#ifndef __block\n";
6197 Preamble += "#define __block\n";
6198 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006199 }
6200 else {
6201 Preamble += "#define __block\n";
6202 Preamble += "#define __weak\n";
6203 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006204
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006205 // Declarations required for modern objective-c array and dictionary literals.
6206 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006207 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006208 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006209 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006210 Preamble += "\tva_list marker;\n";
6211 Preamble += "\tva_start(marker, count);\n";
6212 Preamble += "\tarr = new void *[count];\n";
6213 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6214 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6215 Preamble += "\tva_end( marker );\n";
6216 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006217 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006218 Preamble += "\tdelete[] arr;\n";
6219 Preamble += " }\n";
6220 Preamble += "};\n";
6221
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006222 // Declaration required for implementation of @autoreleasepool statement.
6223 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6224 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6225 Preamble += "struct __AtAutoreleasePool {\n";
6226 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6227 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6228 Preamble += " void * atautoreleasepoolobj;\n";
6229 Preamble += "};\n";
6230
Fariborz Jahanian11671902012-02-07 17:11:38 +00006231 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6232 // as this avoids warning in any 64bit/32bit compilation model.
6233 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6234}
6235
6236/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6237/// ivar offset.
6238void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6239 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006240 Result += "__OFFSETOFIVAR__(struct ";
6241 Result += ivar->getContainingInterface()->getNameAsString();
6242 if (LangOpts.MicrosoftExt)
6243 Result += "_IMPL";
6244 Result += ", ";
6245 if (ivar->isBitField())
6246 ObjCIvarBitfieldGroupDecl(ivar, Result);
6247 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006248 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006249 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006250}
6251
6252/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6253/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006254/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006255/// char *attributes;
6256/// }
6257
6258/// struct _prop_list_t {
6259/// uint32_t entsize; // sizeof(struct _prop_t)
6260/// uint32_t count_of_properties;
6261/// struct _prop_t prop_list[count_of_properties];
6262/// }
6263
6264/// struct _protocol_t;
6265
6266/// struct _protocol_list_t {
6267/// long protocol_count; // Note, this is 32/64 bit
6268/// struct _protocol_t * protocol_list[protocol_count];
6269/// }
6270
6271/// struct _objc_method {
6272/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006273/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006274/// char *_imp;
6275/// }
6276
6277/// struct _method_list_t {
6278/// uint32_t entsize; // sizeof(struct _objc_method)
6279/// uint32_t method_count;
6280/// struct _objc_method method_list[method_count];
6281/// }
6282
6283/// struct _protocol_t {
6284/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006285/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006286/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006287/// const struct method_list_t *instance_methods;
6288/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006289/// const struct method_list_t *optionalInstanceMethods;
6290/// const struct method_list_t *optionalClassMethods;
6291/// const struct _prop_list_t * properties;
6292/// const uint32_t size; // sizeof(struct _protocol_t)
6293/// const uint32_t flags; // = 0
6294/// const char ** extendedMethodTypes;
6295/// }
6296
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006297/// struct _ivar_t {
6298/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006299/// const char *name;
6300/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006301/// uint32_t alignment;
6302/// uint32_t size;
6303/// }
6304
6305/// struct _ivar_list_t {
6306/// uint32 entsize; // sizeof(struct _ivar_t)
6307/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006308/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006309/// }
6310
6311/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006312/// uint32_t flags;
6313/// uint32_t instanceStart;
6314/// uint32_t instanceSize;
6315/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006316/// const uint8_t *ivarLayout;
6317/// const char *name;
6318/// const struct _method_list_t *baseMethods;
6319/// const struct _protocol_list_t *baseProtocols;
6320/// const struct _ivar_list_t *ivars;
6321/// const uint8_t *weakIvarLayout;
6322/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006323/// }
6324
6325/// struct _class_t {
6326/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006327/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006328/// void *cache;
6329/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006330/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006331/// }
6332
6333/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006334/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006335/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006336/// const struct _method_list_t *instance_methods;
6337/// const struct _method_list_t *class_methods;
6338/// const struct _protocol_list_t *protocols;
6339/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006340/// }
6341
6342/// MessageRefTy - LLVM for:
6343/// struct _message_ref_t {
6344/// IMP messenger;
6345/// SEL name;
6346/// };
6347
6348/// SuperMessageRefTy - LLVM for:
6349/// struct _super_message_ref_t {
6350/// SUPER_IMP messenger;
6351/// SEL name;
6352/// };
6353
Fariborz Jahanian45489622012-03-14 18:09:23 +00006354static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006355 static bool meta_data_declared = false;
6356 if (meta_data_declared)
6357 return;
6358
6359 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006360 Result += "\tconst char *name;\n";
6361 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006362 Result += "};\n";
6363
6364 Result += "\nstruct _protocol_t;\n";
6365
Fariborz Jahanian11671902012-02-07 17:11:38 +00006366 Result += "\nstruct _objc_method {\n";
6367 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006368 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006369 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006370 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006371
6372 Result += "\nstruct _protocol_t {\n";
6373 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006374 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006375 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006376 Result += "\tconst struct method_list_t *instance_methods;\n";
6377 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006378 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6379 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6380 Result += "\tconst struct _prop_list_t * properties;\n";
6381 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6382 Result += "\tconst unsigned int flags; // = 0\n";
6383 Result += "\tconst char ** extendedMethodTypes;\n";
6384 Result += "};\n";
6385
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006386 Result += "\nstruct _ivar_t {\n";
6387 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006388 Result += "\tconst char *name;\n";
6389 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006390 Result += "\tunsigned int alignment;\n";
6391 Result += "\tunsigned int size;\n";
6392 Result += "};\n";
6393
6394 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006395 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006396 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006397 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006398 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6399 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006400 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006401 Result += "\tconst unsigned char *ivarLayout;\n";
6402 Result += "\tconst char *name;\n";
6403 Result += "\tconst struct _method_list_t *baseMethods;\n";
6404 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6405 Result += "\tconst struct _ivar_list_t *ivars;\n";
6406 Result += "\tconst unsigned char *weakIvarLayout;\n";
6407 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006408 Result += "};\n";
6409
6410 Result += "\nstruct _class_t {\n";
6411 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006412 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006413 Result += "\tvoid *cache;\n";
6414 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006415 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006416 Result += "};\n";
6417
6418 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006419 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006420 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006421 Result += "\tconst struct _method_list_t *instance_methods;\n";
6422 Result += "\tconst struct _method_list_t *class_methods;\n";
6423 Result += "\tconst struct _protocol_list_t *protocols;\n";
6424 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006425 Result += "};\n";
6426
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006427 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006428 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006429 meta_data_declared = true;
6430}
6431
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006432static void Write_protocol_list_t_TypeDecl(std::string &Result,
6433 long super_protocol_count) {
6434 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6435 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6436 Result += "\tstruct _protocol_t *super_protocols[";
6437 Result += utostr(super_protocol_count); Result += "];\n";
6438 Result += "}";
6439}
6440
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006441static void Write_method_list_t_TypeDecl(std::string &Result,
6442 unsigned int method_count) {
6443 Result += "struct /*_method_list_t*/"; Result += " {\n";
6444 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6445 Result += "\tunsigned int method_count;\n";
6446 Result += "\tstruct _objc_method method_list[";
6447 Result += utostr(method_count); Result += "];\n";
6448 Result += "}";
6449}
6450
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006451static void Write__prop_list_t_TypeDecl(std::string &Result,
6452 unsigned int property_count) {
6453 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6454 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6455 Result += "\tunsigned int count_of_properties;\n";
6456 Result += "\tstruct _prop_t prop_list[";
6457 Result += utostr(property_count); Result += "];\n";
6458 Result += "}";
6459}
6460
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006461static void Write__ivar_list_t_TypeDecl(std::string &Result,
6462 unsigned int ivar_count) {
6463 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6464 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6465 Result += "\tunsigned int count;\n";
6466 Result += "\tstruct _ivar_t ivar_list[";
6467 Result += utostr(ivar_count); Result += "];\n";
6468 Result += "}";
6469}
6470
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006471static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6472 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6473 StringRef VarName,
6474 StringRef ProtocolName) {
6475 if (SuperProtocols.size() > 0) {
6476 Result += "\nstatic ";
6477 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6478 Result += " "; Result += VarName;
6479 Result += ProtocolName;
6480 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6481 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6482 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6483 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6484 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6485 Result += SuperPD->getNameAsString();
6486 if (i == e-1)
6487 Result += "\n};\n";
6488 else
6489 Result += ",\n";
6490 }
6491 }
6492}
6493
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006494static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6495 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006496 ArrayRef<ObjCMethodDecl *> Methods,
6497 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006498 StringRef TopLevelDeclName,
6499 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006500 if (Methods.size() > 0) {
6501 Result += "\nstatic ";
6502 Write_method_list_t_TypeDecl(Result, Methods.size());
6503 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006504 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006505 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6506 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6507 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6508 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6509 ObjCMethodDecl *MD = Methods[i];
6510 if (i == 0)
6511 Result += "\t{{(struct objc_selector *)\"";
6512 else
6513 Result += "\t{(struct objc_selector *)\"";
6514 Result += (MD)->getSelector().getAsString(); Result += "\"";
6515 Result += ", ";
6516 std::string MethodTypeString;
6517 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6518 Result += "\""; Result += MethodTypeString; Result += "\"";
6519 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006520 if (!MethodImpl)
6521 Result += "0";
6522 else {
6523 Result += "(void *)";
6524 Result += RewriteObj.MethodInternalNames[MD];
6525 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006526 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006527 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006528 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006529 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006530 }
6531 Result += "};\n";
6532 }
6533}
6534
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006535static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006536 ASTContext *Context, std::string &Result,
6537 ArrayRef<ObjCPropertyDecl *> Properties,
6538 const Decl *Container,
6539 StringRef VarName,
6540 StringRef ProtocolName) {
6541 if (Properties.size() > 0) {
6542 Result += "\nstatic ";
6543 Write__prop_list_t_TypeDecl(Result, Properties.size());
6544 Result += " "; Result += VarName;
6545 Result += ProtocolName;
6546 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6547 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6548 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6549 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6550 ObjCPropertyDecl *PropDecl = Properties[i];
6551 if (i == 0)
6552 Result += "\t{{\"";
6553 else
6554 Result += "\t{\"";
6555 Result += PropDecl->getName(); Result += "\",";
6556 std::string PropertyTypeString, QuotePropertyTypeString;
6557 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6558 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6559 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6560 if (i == e-1)
6561 Result += "}}\n";
6562 else
6563 Result += "},\n";
6564 }
6565 Result += "};\n";
6566 }
6567}
6568
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006569// Metadata flags
6570enum MetaDataDlags {
6571 CLS = 0x0,
6572 CLS_META = 0x1,
6573 CLS_ROOT = 0x2,
6574 OBJC2_CLS_HIDDEN = 0x10,
6575 CLS_EXCEPTION = 0x20,
6576
6577 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6578 CLS_HAS_IVAR_RELEASER = 0x40,
6579 /// class was compiled with -fobjc-arr
6580 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6581};
6582
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006583static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6584 unsigned int flags,
6585 const std::string &InstanceStart,
6586 const std::string &InstanceSize,
6587 ArrayRef<ObjCMethodDecl *>baseMethods,
6588 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6589 ArrayRef<ObjCIvarDecl *>ivars,
6590 ArrayRef<ObjCPropertyDecl *>Properties,
6591 StringRef VarName,
6592 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006593 Result += "\nstatic struct _class_ro_t ";
6594 Result += VarName; Result += ClassName;
6595 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6596 Result += "\t";
6597 Result += llvm::utostr(flags); Result += ", ";
6598 Result += InstanceStart; Result += ", ";
6599 Result += InstanceSize; Result += ", \n";
6600 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006601 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6602 if (Triple.getArch() == llvm::Triple::x86_64)
6603 // uint32_t const reserved; // only when building for 64bit targets
6604 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006605 // const uint8_t * const ivarLayout;
6606 Result += "0, \n\t";
6607 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006608 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006609 if (baseMethods.size() > 0) {
6610 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006611 if (metaclass)
6612 Result += "_OBJC_$_CLASS_METHODS_";
6613 else
6614 Result += "_OBJC_$_INSTANCE_METHODS_";
6615 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006616 Result += ",\n\t";
6617 }
6618 else
6619 Result += "0, \n\t";
6620
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006621 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006622 Result += "(const struct _objc_protocol_list *)&";
6623 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6624 Result += ",\n\t";
6625 }
6626 else
6627 Result += "0, \n\t";
6628
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006629 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006630 Result += "(const struct _ivar_list_t *)&";
6631 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6632 Result += ",\n\t";
6633 }
6634 else
6635 Result += "0, \n\t";
6636
6637 // weakIvarLayout
6638 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006639 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006640 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006641 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006642 Result += ",\n";
6643 }
6644 else
6645 Result += "0, \n";
6646
6647 Result += "};\n";
6648}
6649
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006650static void Write_class_t(ASTContext *Context, std::string &Result,
6651 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006652 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6653 bool rootClass = (!CDecl->getSuperClass());
6654 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006655
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006656 if (!rootClass) {
6657 // Find the Root class
6658 RootClass = CDecl->getSuperClass();
6659 while (RootClass->getSuperClass()) {
6660 RootClass = RootClass->getSuperClass();
6661 }
6662 }
6663
6664 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006665 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006666 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006667 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006668 if (CDecl->getImplementation())
6669 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006670 else
6671 Result += "__declspec(dllimport) ";
6672
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006673 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006674 Result += CDecl->getNameAsString();
6675 Result += ";\n";
6676 }
6677 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006678 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006679 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006680 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006681 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006682 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006683 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006684 else
6685 Result += "__declspec(dllimport) ";
6686
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006687 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006688 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006689 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006690 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006691
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006692 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006693 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006694 if (RootClass->getImplementation())
6695 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006696 else
6697 Result += "__declspec(dllimport) ";
6698
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006699 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006700 Result += VarName;
6701 Result += RootClass->getNameAsString();
6702 Result += ";\n";
6703 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006704 }
6705
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006706 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6707 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006708 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6709 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006710 if (metaclass) {
6711 if (!rootClass) {
6712 Result += "0, // &"; Result += VarName;
6713 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006714 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006715 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006716 Result += CDecl->getSuperClass()->getNameAsString();
6717 Result += ",\n\t";
6718 }
6719 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006720 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006721 Result += CDecl->getNameAsString();
6722 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006723 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006724 Result += ",\n\t";
6725 }
6726 }
6727 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006728 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006729 Result += CDecl->getNameAsString();
6730 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006731 if (!rootClass) {
6732 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006733 Result += CDecl->getSuperClass()->getNameAsString();
6734 Result += ",\n\t";
6735 }
6736 else
6737 Result += "0,\n\t";
6738 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006739 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6740 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6741 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006742 Result += "&_OBJC_METACLASS_RO_$_";
6743 else
6744 Result += "&_OBJC_CLASS_RO_$_";
6745 Result += CDecl->getNameAsString();
6746 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006747
6748 // Add static function to initialize some of the meta-data fields.
6749 // avoid doing it twice.
6750 if (metaclass)
6751 return;
6752
6753 const ObjCInterfaceDecl *SuperClass =
6754 rootClass ? CDecl : CDecl->getSuperClass();
6755
6756 Result += "static void OBJC_CLASS_SETUP_$_";
6757 Result += CDecl->getNameAsString();
6758 Result += "(void ) {\n";
6759 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6760 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006761 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006762
6763 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006764 Result += ".superclass = ";
6765 if (rootClass)
6766 Result += "&OBJC_CLASS_$_";
6767 else
6768 Result += "&OBJC_METACLASS_$_";
6769
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006770 Result += SuperClass->getNameAsString(); Result += ";\n";
6771
6772 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6773 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6774
6775 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6776 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6777 Result += CDecl->getNameAsString(); Result += ";\n";
6778
6779 if (!rootClass) {
6780 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6781 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6782 Result += SuperClass->getNameAsString(); Result += ";\n";
6783 }
6784
6785 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6786 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6787 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006788}
6789
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006790static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6791 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006792 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006793 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006794 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6795 ArrayRef<ObjCMethodDecl *> ClassMethods,
6796 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6797 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006798 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006799 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006800 // must declare an extern class object in case this class is not implemented
6801 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006802 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006803 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006804 if (ClassDecl->getImplementation())
6805 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006806 else
6807 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006808
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006809 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006810 Result += "OBJC_CLASS_$_"; Result += ClassName;
6811 Result += ";\n";
6812
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006813 Result += "\nstatic struct _category_t ";
6814 Result += "_OBJC_$_CATEGORY_";
6815 Result += ClassName; Result += "_$_"; Result += CatName;
6816 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6817 Result += "{\n";
6818 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006819 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006820 Result += ",\n";
6821 if (InstanceMethods.size() > 0) {
6822 Result += "\t(const struct _method_list_t *)&";
6823 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6824 Result += ClassName; Result += "_$_"; Result += CatName;
6825 Result += ",\n";
6826 }
6827 else
6828 Result += "\t0,\n";
6829
6830 if (ClassMethods.size() > 0) {
6831 Result += "\t(const struct _method_list_t *)&";
6832 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6833 Result += ClassName; Result += "_$_"; Result += CatName;
6834 Result += ",\n";
6835 }
6836 else
6837 Result += "\t0,\n";
6838
6839 if (RefedProtocols.size() > 0) {
6840 Result += "\t(const struct _protocol_list_t *)&";
6841 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6842 Result += ClassName; Result += "_$_"; Result += CatName;
6843 Result += ",\n";
6844 }
6845 else
6846 Result += "\t0,\n";
6847
6848 if (ClassProperties.size() > 0) {
6849 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6850 Result += ClassName; Result += "_$_"; Result += CatName;
6851 Result += ",\n";
6852 }
6853 else
6854 Result += "\t0,\n";
6855
6856 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006857
6858 // Add static function to initialize the class pointer in the category structure.
6859 Result += "static void OBJC_CATEGORY_SETUP_$_";
6860 Result += ClassDecl->getNameAsString();
6861 Result += "_$_";
6862 Result += CatName;
6863 Result += "(void ) {\n";
6864 Result += "\t_OBJC_$_CATEGORY_";
6865 Result += ClassDecl->getNameAsString();
6866 Result += "_$_";
6867 Result += CatName;
6868 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6869 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006870}
6871
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006872static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6873 ASTContext *Context, std::string &Result,
6874 ArrayRef<ObjCMethodDecl *> Methods,
6875 StringRef VarName,
6876 StringRef ProtocolName) {
6877 if (Methods.size() == 0)
6878 return;
6879
6880 Result += "\nstatic const char *";
6881 Result += VarName; Result += ProtocolName;
6882 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6883 Result += "{\n";
6884 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6885 ObjCMethodDecl *MD = Methods[i];
6886 std::string MethodTypeString, QuoteMethodTypeString;
6887 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6888 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6889 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6890 if (i == e-1)
6891 Result += "\n};\n";
6892 else {
6893 Result += ",\n";
6894 }
6895 }
6896}
6897
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006898static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6899 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006900 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006901 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006902 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006903 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6904 // this is what happens:
6905 /**
6906 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6907 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6908 Class->getVisibility() == HiddenVisibility)
6909 Visibility shoud be: HiddenVisibility;
6910 else
6911 Visibility shoud be: DefaultVisibility;
6912 */
6913
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006914 Result += "\n";
6915 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6916 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006917 if (Context->getLangOpts().MicrosoftExt)
6918 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6919
6920 if (!Context->getLangOpts().MicrosoftExt ||
6921 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006922 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006923 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006924 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006925 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006926 if (Ivars[i]->isBitField())
6927 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6928 else
6929 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006930 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6931 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006932 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6933 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006934 if (Ivars[i]->isBitField()) {
6935 // skip over rest of the ivar bitfields.
6936 SKIP_BITFIELDS(i , e, Ivars);
6937 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006938 }
6939}
6940
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006941static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6942 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006943 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006944 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006945 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006946 if (OriginalIvars.size() > 0) {
6947 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6948 SmallVector<ObjCIvarDecl *, 8> Ivars;
6949 // strip off all but the first ivar bitfield from each group of ivars.
6950 // Such ivars in the ivar list table will be replaced by their grouping struct
6951 // 'ivar'.
6952 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6953 if (OriginalIvars[i]->isBitField()) {
6954 Ivars.push_back(OriginalIvars[i]);
6955 // skip over rest of the ivar bitfields.
6956 SKIP_BITFIELDS(i , e, OriginalIvars);
6957 }
6958 else
6959 Ivars.push_back(OriginalIvars[i]);
6960 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006961
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006962 Result += "\nstatic ";
6963 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6964 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006965 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006966 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6967 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6968 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6969 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6970 ObjCIvarDecl *IvarDecl = Ivars[i];
6971 if (i == 0)
6972 Result += "\t{{";
6973 else
6974 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006975 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006976 if (Ivars[i]->isBitField())
6977 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6978 else
6979 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006980 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006981
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006982 Result += "\"";
6983 if (Ivars[i]->isBitField())
6984 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6985 else
6986 Result += IvarDecl->getName();
6987 Result += "\", ";
6988
6989 QualType IVQT = IvarDecl->getType();
6990 if (IvarDecl->isBitField())
6991 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6992
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006993 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006994 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006995 IvarDecl);
6996 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6997 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6998
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006999 // FIXME. this alignment represents the host alignment and need be changed to
7000 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007001 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007002 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007003 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007004 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00007005 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007006 if (i == e-1)
7007 Result += "}}\n";
7008 else
7009 Result += "},\n";
7010 }
7011 Result += "};\n";
7012 }
7013}
7014
Fariborz Jahanian11671902012-02-07 17:11:38 +00007015/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007016void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
7017 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00007018
Fariborz Jahanian11671902012-02-07 17:11:38 +00007019 // Do not synthesize the protocol more than once.
7020 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
7021 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00007022 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007023
7024 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
7025 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007026 // Must write out all protocol definitions in current qualifier list,
7027 // and in their nested qualifiers before writing out current definition.
7028 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7029 E = PDecl->protocol_end(); I != E; ++I)
7030 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007031
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007032 // Construct method lists.
7033 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7034 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
7035 for (ObjCProtocolDecl::instmeth_iterator
7036 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
7037 I != E; ++I) {
7038 ObjCMethodDecl *MD = *I;
7039 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7040 OptInstanceMethods.push_back(MD);
7041 } else {
7042 InstanceMethods.push_back(MD);
7043 }
7044 }
7045
7046 for (ObjCProtocolDecl::classmeth_iterator
7047 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
7048 I != E; ++I) {
7049 ObjCMethodDecl *MD = *I;
7050 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7051 OptClassMethods.push_back(MD);
7052 } else {
7053 ClassMethods.push_back(MD);
7054 }
7055 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007056 std::vector<ObjCMethodDecl *> AllMethods;
7057 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7058 AllMethods.push_back(InstanceMethods[i]);
7059 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7060 AllMethods.push_back(ClassMethods[i]);
7061 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7062 AllMethods.push_back(OptInstanceMethods[i]);
7063 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7064 AllMethods.push_back(OptClassMethods[i]);
7065
7066 Write__extendedMethodTypes_initializer(*this, Context, Result,
7067 AllMethods,
7068 "_OBJC_PROTOCOL_METHOD_TYPES_",
7069 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007070 // Protocol's super protocol list
7071 std::vector<ObjCProtocolDecl *> SuperProtocols;
7072 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7073 E = PDecl->protocol_end(); I != E; ++I)
7074 SuperProtocols.push_back(*I);
7075
7076 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7077 "_OBJC_PROTOCOL_REFS_",
7078 PDecl->getNameAsString());
7079
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007080 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007081 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007082 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007083
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007084 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007085 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007086 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007087
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007088 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007089 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007090 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007091
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007092 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007093 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007094 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007095
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007096 // Protocol's property metadata.
7097 std::vector<ObjCPropertyDecl *> ProtocolProperties;
7098 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
7099 E = PDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007100 ProtocolProperties.push_back(*I);
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007101
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007102 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007103 /* Container */0,
7104 "_OBJC_PROTOCOL_PROPERTIES_",
7105 PDecl->getNameAsString());
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007106
Fariborz Jahanian48985802012-02-08 00:50:52 +00007107 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007108 Result += "\n";
7109 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007110 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007111 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007112 Result += PDecl->getNameAsString();
Fariborz Jahanian48985802012-02-08 00:50:52 +00007113 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7114 Result += "\t0,\n"; // id is; is null
7115 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007116 if (SuperProtocols.size() > 0) {
7117 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7118 Result += PDecl->getNameAsString(); Result += ",\n";
7119 }
7120 else
7121 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007122 if (InstanceMethods.size() > 0) {
7123 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7124 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007125 }
7126 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007127 Result += "\t0,\n";
7128
7129 if (ClassMethods.size() > 0) {
7130 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7131 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007132 }
7133 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007134 Result += "\t0,\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007135
Fariborz Jahanian48985802012-02-08 00:50:52 +00007136 if (OptInstanceMethods.size() > 0) {
7137 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7138 Result += PDecl->getNameAsString(); Result += ",\n";
7139 }
7140 else
7141 Result += "\t0,\n";
7142
7143 if (OptClassMethods.size() > 0) {
7144 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7145 Result += PDecl->getNameAsString(); Result += ",\n";
7146 }
7147 else
7148 Result += "\t0,\n";
7149
7150 if (ProtocolProperties.size() > 0) {
7151 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7152 Result += PDecl->getNameAsString(); Result += ",\n";
7153 }
7154 else
7155 Result += "\t0,\n";
7156
7157 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7158 Result += "\t0,\n";
7159
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007160 if (AllMethods.size() > 0) {
7161 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7162 Result += PDecl->getNameAsString();
7163 Result += "\n};\n";
7164 }
7165 else
7166 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007167
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007168 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007169 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007170 Result += "struct _protocol_t *";
7171 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7172 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7173 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007174
Fariborz Jahanian11671902012-02-07 17:11:38 +00007175 // Mark this protocol as having been generated.
7176 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7177 llvm_unreachable("protocol already synthesized");
7178
7179}
7180
7181void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7182 const ObjCList<ObjCProtocolDecl> &Protocols,
7183 StringRef prefix, StringRef ClassName,
7184 std::string &Result) {
7185 if (Protocols.empty()) return;
7186
7187 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007188 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007189
7190 // Output the top lovel protocol meta-data for the class.
7191 /* struct _objc_protocol_list {
7192 struct _objc_protocol_list *next;
7193 int protocol_count;
7194 struct _objc_protocol *class_protocols[];
7195 }
7196 */
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007197 Result += "\n";
7198 if (LangOpts.MicrosoftExt)
7199 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7200 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007201 Result += "\tstruct _objc_protocol_list *next;\n";
7202 Result += "\tint protocol_count;\n";
7203 Result += "\tstruct _objc_protocol *class_protocols[";
7204 Result += utostr(Protocols.size());
7205 Result += "];\n} _OBJC_";
7206 Result += prefix;
7207 Result += "_PROTOCOLS_";
7208 Result += ClassName;
7209 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7210 "{\n\t0, ";
7211 Result += utostr(Protocols.size());
7212 Result += "\n";
7213
7214 Result += "\t,{&_OBJC_PROTOCOL_";
7215 Result += Protocols[0]->getNameAsString();
7216 Result += " \n";
7217
7218 for (unsigned i = 1; i != Protocols.size(); i++) {
7219 Result += "\t ,&_OBJC_PROTOCOL_";
7220 Result += Protocols[i]->getNameAsString();
7221 Result += "\n";
7222 }
7223 Result += "\t }\n};\n";
7224}
7225
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007226/// hasObjCExceptionAttribute - Return true if this class or any super
7227/// class has the __objc_exception__ attribute.
7228/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7229static bool hasObjCExceptionAttribute(ASTContext &Context,
7230 const ObjCInterfaceDecl *OID) {
7231 if (OID->hasAttr<ObjCExceptionAttr>())
7232 return true;
7233 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7234 return hasObjCExceptionAttribute(Context, Super);
7235 return false;
7236}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007237
Fariborz Jahanian11671902012-02-07 17:11:38 +00007238void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7239 std::string &Result) {
7240 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7241
7242 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007243 if (CDecl->isImplicitInterfaceDecl())
7244 assert(false &&
7245 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007246
Fariborz Jahanian45489622012-03-14 18:09:23 +00007247 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007248 SmallVector<ObjCIvarDecl *, 8> IVars;
7249
7250 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7251 IVD; IVD = IVD->getNextIvar()) {
7252 // Ignore unnamed bit-fields.
7253 if (!IVD->getDeclName())
7254 continue;
7255 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007256 }
7257
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007258 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007259 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007260 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007261
7262 // Build _objc_method_list for class's instance methods if needed
7263 SmallVector<ObjCMethodDecl *, 32>
7264 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7265
7266 // If any of our property implementations have associated getters or
7267 // setters, produce metadata for them as well.
7268 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7269 PropEnd = IDecl->propimpl_end();
7270 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007271 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007272 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007273 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007274 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007275 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007276 if (!PD)
7277 continue;
7278 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007279 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007280 InstanceMethods.push_back(Getter);
7281 if (PD->isReadOnly())
7282 continue;
7283 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007284 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007285 InstanceMethods.push_back(Setter);
7286 }
7287
7288 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7289 "_OBJC_$_INSTANCE_METHODS_",
7290 IDecl->getNameAsString(), true);
7291
7292 SmallVector<ObjCMethodDecl *, 32>
7293 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7294
7295 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7296 "_OBJC_$_CLASS_METHODS_",
7297 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007298
7299 // Protocols referenced in class declaration?
7300 // Protocol's super protocol list
7301 std::vector<ObjCProtocolDecl *> RefedProtocols;
7302 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7303 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7304 E = Protocols.end();
7305 I != E; ++I) {
7306 RefedProtocols.push_back(*I);
7307 // Must write out all protocol definitions in current qualifier list,
7308 // and in their nested qualifiers before writing out current definition.
7309 RewriteObjCProtocolMetaData(*I, Result);
7310 }
7311
7312 Write_protocol_list_initializer(Context, Result,
7313 RefedProtocols,
7314 "_OBJC_CLASS_PROTOCOLS_$_",
7315 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007316
7317 // Protocol's property metadata.
7318 std::vector<ObjCPropertyDecl *> ClassProperties;
7319 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7320 E = CDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007321 ClassProperties.push_back(*I);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007322
7323 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007324 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007325 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007326 CDecl->getNameAsString());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007327
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007328
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007329 // Data for initializing _class_ro_t metaclass meta-data
7330 uint32_t flags = CLS_META;
7331 std::string InstanceSize;
7332 std::string InstanceStart;
7333
7334
7335 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7336 if (classIsHidden)
7337 flags |= OBJC2_CLS_HIDDEN;
7338
7339 if (!CDecl->getSuperClass())
7340 // class is root
7341 flags |= CLS_ROOT;
7342 InstanceSize = "sizeof(struct _class_t)";
7343 InstanceStart = InstanceSize;
7344 Write__class_ro_t_initializer(Context, Result, flags,
7345 InstanceStart, InstanceSize,
7346 ClassMethods,
7347 0,
7348 0,
7349 0,
7350 "_OBJC_METACLASS_RO_$_",
7351 CDecl->getNameAsString());
7352
7353
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007354 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007355 flags = CLS;
7356 if (classIsHidden)
7357 flags |= OBJC2_CLS_HIDDEN;
7358
7359 if (hasObjCExceptionAttribute(*Context, CDecl))
7360 flags |= CLS_EXCEPTION;
7361
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007362 if (!CDecl->getSuperClass())
7363 // class is root
7364 flags |= CLS_ROOT;
7365
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007366 InstanceSize.clear();
7367 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007368 if (!ObjCSynthesizedStructs.count(CDecl)) {
7369 InstanceSize = "0";
7370 InstanceStart = "0";
7371 }
7372 else {
7373 InstanceSize = "sizeof(struct ";
7374 InstanceSize += CDecl->getNameAsString();
7375 InstanceSize += "_IMPL)";
7376
7377 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7378 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007379 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007380 }
7381 else
7382 InstanceStart = InstanceSize;
7383 }
7384 Write__class_ro_t_initializer(Context, Result, flags,
7385 InstanceStart, InstanceSize,
7386 InstanceMethods,
7387 RefedProtocols,
7388 IVars,
7389 ClassProperties,
7390 "_OBJC_CLASS_RO_$_",
7391 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007392
7393 Write_class_t(Context, Result,
7394 "OBJC_METACLASS_$_",
7395 CDecl, /*metaclass*/true);
7396
7397 Write_class_t(Context, Result,
7398 "OBJC_CLASS_$_",
7399 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007400
7401 if (ImplementationIsNonLazy(IDecl))
7402 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007403
Fariborz Jahanian11671902012-02-07 17:11:38 +00007404}
7405
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007406void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7407 int ClsDefCount = ClassImplementation.size();
7408 if (!ClsDefCount)
7409 return;
7410 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7411 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7412 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7413 for (int i = 0; i < ClsDefCount; i++) {
7414 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7415 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7416 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7417 Result += CDecl->getName(); Result += ",\n";
7418 }
7419 Result += "};\n";
7420}
7421
Fariborz Jahanian11671902012-02-07 17:11:38 +00007422void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7423 int ClsDefCount = ClassImplementation.size();
7424 int CatDefCount = CategoryImplementation.size();
7425
7426 // For each implemented class, write out all its meta data.
7427 for (int i = 0; i < ClsDefCount; i++)
7428 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7429
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007430 RewriteClassSetupInitHook(Result);
7431
Fariborz Jahanian11671902012-02-07 17:11:38 +00007432 // For each implemented category, write out all its meta data.
7433 for (int i = 0; i < CatDefCount; i++)
7434 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7435
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007436 RewriteCategorySetupInitHook(Result);
7437
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007438 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007439 if (LangOpts.MicrosoftExt)
7440 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007441 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7442 Result += llvm::utostr(ClsDefCount); Result += "]";
7443 Result +=
7444 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7445 "regular,no_dead_strip\")))= {\n";
7446 for (int i = 0; i < ClsDefCount; i++) {
7447 Result += "\t&OBJC_CLASS_$_";
7448 Result += ClassImplementation[i]->getNameAsString();
7449 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007450 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007451 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007452
7453 if (!DefinedNonLazyClasses.empty()) {
7454 if (LangOpts.MicrosoftExt)
7455 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7456 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7457 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7458 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7459 Result += ",\n";
7460 }
7461 Result += "};\n";
7462 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007463 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007464
7465 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007466 if (LangOpts.MicrosoftExt)
7467 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007468 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7469 Result += llvm::utostr(CatDefCount); Result += "]";
7470 Result +=
7471 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7472 "regular,no_dead_strip\")))= {\n";
7473 for (int i = 0; i < CatDefCount; i++) {
7474 Result += "\t&_OBJC_$_CATEGORY_";
7475 Result +=
7476 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7477 Result += "_$_";
7478 Result += CategoryImplementation[i]->getNameAsString();
7479 Result += ",\n";
7480 }
7481 Result += "};\n";
7482 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007483
7484 if (!DefinedNonLazyCategories.empty()) {
7485 if (LangOpts.MicrosoftExt)
7486 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7487 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7488 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7489 Result += "\t&_OBJC_$_CATEGORY_";
7490 Result +=
7491 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7492 Result += "_$_";
7493 Result += DefinedNonLazyCategories[i]->getNameAsString();
7494 Result += ",\n";
7495 }
7496 Result += "};\n";
7497 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007498}
7499
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007500void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7501 if (LangOpts.MicrosoftExt)
7502 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7503
7504 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7505 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007506 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007507}
7508
Fariborz Jahanian11671902012-02-07 17:11:38 +00007509/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7510/// implementation.
7511void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7512 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007513 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007514 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7515 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007516 ObjCCategoryDecl *CDecl
7517 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007518
7519 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007520 FullCategoryName += "_$_";
7521 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007522
7523 // Build _objc_method_list for class's instance methods if needed
7524 SmallVector<ObjCMethodDecl *, 32>
7525 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7526
7527 // If any of our property implementations have associated getters or
7528 // setters, produce metadata for them as well.
7529 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7530 PropEnd = IDecl->propimpl_end();
7531 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007532 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007533 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007534 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007535 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007536 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007537 if (!PD)
7538 continue;
7539 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7540 InstanceMethods.push_back(Getter);
7541 if (PD->isReadOnly())
7542 continue;
7543 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7544 InstanceMethods.push_back(Setter);
7545 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007546
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007547 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7548 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7549 FullCategoryName, true);
7550
7551 SmallVector<ObjCMethodDecl *, 32>
7552 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7553
7554 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7555 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7556 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007557
7558 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007559 // Protocol's super protocol list
7560 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidise7f3ef32012-03-13 01:09:41 +00007561 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7562 E = CDecl->protocol_end();
7563
7564 I != E; ++I) {
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007565 RefedProtocols.push_back(*I);
7566 // Must write out all protocol definitions in current qualifier list,
7567 // and in their nested qualifiers before writing out current definition.
7568 RewriteObjCProtocolMetaData(*I, Result);
7569 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007570
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007571 Write_protocol_list_initializer(Context, Result,
7572 RefedProtocols,
7573 "_OBJC_CATEGORY_PROTOCOLS_$_",
7574 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007575
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007576 // Protocol's property metadata.
7577 std::vector<ObjCPropertyDecl *> ClassProperties;
7578 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7579 E = CDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007580 ClassProperties.push_back(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007581
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007582 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007583 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007584 "_OBJC_$_PROP_LIST_",
7585 FullCategoryName);
7586
7587 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007588 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007589 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007590 InstanceMethods,
7591 ClassMethods,
7592 RefedProtocols,
7593 ClassProperties);
7594
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007595 // Determine if this category is also "non-lazy".
7596 if (ImplementationIsNonLazy(IDecl))
7597 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007598
7599}
7600
7601void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7602 int CatDefCount = CategoryImplementation.size();
7603 if (!CatDefCount)
7604 return;
7605 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7606 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7607 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7608 for (int i = 0; i < CatDefCount; i++) {
7609 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7610 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7611 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7612 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7613 Result += ClassDecl->getName();
7614 Result += "_$_";
7615 Result += CatDecl->getName();
7616 Result += ",\n";
7617 }
7618 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007619}
7620
7621// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7622/// class methods.
7623template<typename MethodIterator>
7624void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7625 MethodIterator MethodEnd,
7626 bool IsInstanceMethod,
7627 StringRef prefix,
7628 StringRef ClassName,
7629 std::string &Result) {
7630 if (MethodBegin == MethodEnd) return;
7631
7632 if (!objc_impl_method) {
7633 /* struct _objc_method {
7634 SEL _cmd;
7635 char *method_types;
7636 void *_imp;
7637 }
7638 */
7639 Result += "\nstruct _objc_method {\n";
7640 Result += "\tSEL _cmd;\n";
7641 Result += "\tchar *method_types;\n";
7642 Result += "\tvoid *_imp;\n";
7643 Result += "};\n";
7644
7645 objc_impl_method = true;
7646 }
7647
7648 // Build _objc_method_list for class's methods if needed
7649
7650 /* struct {
7651 struct _objc_method_list *next_method;
7652 int method_count;
7653 struct _objc_method method_list[];
7654 }
7655 */
7656 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007657 Result += "\n";
7658 if (LangOpts.MicrosoftExt) {
7659 if (IsInstanceMethod)
7660 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7661 else
7662 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7663 }
7664 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007665 Result += "\tstruct _objc_method_list *next_method;\n";
7666 Result += "\tint method_count;\n";
7667 Result += "\tstruct _objc_method method_list[";
7668 Result += utostr(NumMethods);
7669 Result += "];\n} _OBJC_";
7670 Result += prefix;
7671 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7672 Result += "_METHODS_";
7673 Result += ClassName;
7674 Result += " __attribute__ ((used, section (\"__OBJC, __";
7675 Result += IsInstanceMethod ? "inst" : "cls";
7676 Result += "_meth\")))= ";
7677 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7678
7679 Result += "\t,{{(SEL)\"";
7680 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7681 std::string MethodTypeString;
7682 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7683 Result += "\", \"";
7684 Result += MethodTypeString;
7685 Result += "\", (void *)";
7686 Result += MethodInternalNames[*MethodBegin];
7687 Result += "}\n";
7688 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7689 Result += "\t ,{(SEL)\"";
7690 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7691 std::string MethodTypeString;
7692 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7693 Result += "\", \"";
7694 Result += MethodTypeString;
7695 Result += "\", (void *)";
7696 Result += MethodInternalNames[*MethodBegin];
7697 Result += "}\n";
7698 }
7699 Result += "\t }\n};\n";
7700}
7701
7702Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7703 SourceRange OldRange = IV->getSourceRange();
7704 Expr *BaseExpr = IV->getBase();
7705
7706 // Rewrite the base, but without actually doing replaces.
7707 {
7708 DisableReplaceStmtScope S(*this);
7709 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7710 IV->setBase(BaseExpr);
7711 }
7712
7713 ObjCIvarDecl *D = IV->getDecl();
7714
7715 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007716
Fariborz Jahanian11671902012-02-07 17:11:38 +00007717 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7718 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007719 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007720 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7721 // lookup which class implements the instance variable.
7722 ObjCInterfaceDecl *clsDeclared = 0;
7723 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7724 clsDeclared);
7725 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7726
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007727 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007728 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007729 if (D->isBitField())
7730 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7731 else
7732 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007733
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007734 ReferencedIvars[clsDeclared].insert(D);
7735
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007736 // cast offset to "char *".
7737 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7738 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007739 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007740 BaseExpr);
7741 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7742 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007743 Context->UnsignedLongTy, 0, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007744 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7745 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007746 SourceLocation());
7747 BinaryOperator *addExpr =
7748 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7749 Context->getPointerType(Context->CharTy),
Lang Hames5de91cc2012-10-02 04:45:10 +00007750 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007751 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007752 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7753 SourceLocation(),
7754 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007755 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007756 if (D->isBitField())
7757 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007758
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007759 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007760 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007761 RD = RD->getDefinition();
7762 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007763 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007764 ObjCContainerDecl *CDecl =
7765 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7766 // ivar in class extensions requires special treatment.
7767 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7768 CDecl = CatDecl->getClassInterface();
7769 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007770 RecName += "_IMPL";
7771 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7772 SourceLocation(), SourceLocation(),
7773 &Context->Idents.get(RecName.c_str()));
7774 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7775 unsigned UnsignedIntSize =
7776 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7777 Expr *Zero = IntegerLiteral::Create(*Context,
7778 llvm::APInt(UnsignedIntSize, 0),
7779 Context->UnsignedIntTy, SourceLocation());
7780 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7781 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7782 Zero);
7783 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7784 SourceLocation(),
7785 &Context->Idents.get(D->getNameAsString()),
7786 IvarT, 0,
7787 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00007788 ICIS_NoInit);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007789 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7790 FD->getType(), VK_LValue,
7791 OK_Ordinary);
7792 IvarT = Context->getDecltypeType(ME, ME->getType());
7793 }
7794 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007795 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007796 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007797
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007798 castExpr = NoTypeInfoCStyleCastExpr(Context,
7799 castT,
7800 CK_BitCast,
7801 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007802
7803
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007804 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007805 VK_LValue, OK_Ordinary,
7806 SourceLocation());
7807 PE = new (Context) ParenExpr(OldRange.getBegin(),
7808 OldRange.getEnd(),
7809 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007810
7811 if (D->isBitField()) {
7812 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7813 SourceLocation(),
7814 &Context->Idents.get(D->getNameAsString()),
7815 D->getType(), 0,
7816 /*BitWidth=*/D->getBitWidth(),
7817 /*Mutable=*/true,
7818 ICIS_NoInit);
7819 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7820 FD->getType(), VK_LValue,
7821 OK_Ordinary);
7822 Replacement = ME;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007823
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007824 }
7825 else
7826 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007827 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007828
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007829 ReplaceStmtWithRange(IV, Replacement, OldRange);
7830 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007831}